code
stringlengths
1
2.08M
language
stringclasses
1 value
/* * jQuery plugin that makes elements editable * * @author Victor Jonsson (http://victorjonsson.se/) * @website https://github.com/victorjonsson/jquery-editable/ * @license GPLv2 http://www.gnu.org/licenses/gpl-2.0.html * @version 1.3.6.dev * @donations http://victorjonsson.se/donations/ */ (function($, window) { 'use strict'; var $win = $(window), // Reference to window // Reference to textarea $textArea = false, // Reference to currently edit element $currentlyEdited = false, // Some constants EVENT_ATTR = 'data-edit-event', IS_EDITING_ATTR = 'data-is-editing', EMPTY_ATTR = 'data-is-empty', DBL_TAP_EVENT = 'dbltap', SUPPORTS_TOUCH = 'ontouchend' in window, TINYMCE_INSTALLED = 'tinyMCE' in window && typeof window.tinyMCE.init == 'function', // reference to old is function oldjQueryIs = $.fn.is, /* * Function responsible of triggering double tap event */ lastTap = 0, tapper = function() { var now = new Date().getTime(); if( (now-lastTap) < 250 ) { $(this).trigger(DBL_TAP_EVENT); } lastTap = now; }, /** * Event listener that largens font size */ keyHandler = function(e) { if( e.keyCode == 13 && e.data.closeOnEnter ) { $currentlyEdited.editable('close'); } else if( e.data.toggleFontSize && (e.metaKey && (e.keyCode == 38 || e.keyCode == 40)) ) { var fontSize = parseInt($textArea.css('font-size'), 10); fontSize += e.keyCode == 40 ? -1 : 1; $textArea.css('font-size', fontSize+'px'); return false; } }, /** * Adjusts the height of the textarea to remove scroll * @todo This way of doing it does not make the textarea smaller when the number of text lines gets smaller */ adjustTextAreaHeight = function() { if( $textArea[0].scrollHeight !== parseInt($textArea.attr('data-scroll'), 10) ) { $textArea.css('height', $textArea[0].scrollHeight +'px'); $textArea.attr('data-scroll', $textArea[0].scrollHeight); } }, /** * @param {jQuery} $el * @param {String} newText */ resetElement = function($el, newText, emptyMessage) { $el.removeAttr(IS_EDITING_ATTR); if (newText.length == 0 && emptyMessage) { $el.html(emptyMessage); $el.attr(EMPTY_ATTR, 'empty'); } else { $el.html( newText ); $el.removeAttr(EMPTY_ATTR); } $textArea.remove(); }, /** * Function creating editor */ elementEditor = function($el, opts) { if( $el.is(':editing') ) return; $currentlyEdited = $el; $el.attr(IS_EDITING_ATTR, '1'); if ($el.is(':empty')) { $el.removeAttr(EMPTY_ATTR); $el.html(''); } var defaultText = $.trim( $el.html() ), defaultFontSize = $el.css('font-size'), elementHeight = $el.height(), textareaStyle = 'width: 96%; padding:0; margin:0; border:0; background:none;'+ 'font-family: '+$el.css('font-family')+'; font-size: '+$el.css('font-size')+';'+ 'font-weight: '+$el.css('font-weight')+';'; if( opts.lineBreaks ) { defaultText = defaultText.replace(/<br( |)(|\/)>/g, '\n'); } $textArea = $('<textarea></textarea>'); $el.text(''); if( navigator.userAgent.match(/webkit/i) !== null ) { textareaStyle = document.defaultView.getComputedStyle($el.get(0), "").cssText; } // The editor should always be static textareaStyle += 'position: static'; /* TINYMCE EDITOR */ if( opts.tinyMCE !== false ) { var id = 'editable-area-'+(new Date().getTime()); $textArea .val(defaultText) .appendTo($el) .attr('id', id); if( typeof opts.tinyMCE != 'object' ) opts.tinyMCE = {}; opts.tinyMCE.mode = 'exact'; opts.tinyMCE.elements = id; opts.tinyMCE.width = $el.innerWidth(); opts.tinyMCE.height = $el.height() + 200; opts.tinyMCE.theme_advanced_resize_vertical = true; opts.tinyMCE.setup = function (ed) { ed.onInit.add(function(editor, evt) { var editorWindow = editor.getWin(); var hasPressedKey = false; var editorBlur = function() { var newText = $(editor.getDoc()).find('body').html(); if( $(newText).get(0).nodeName == $el.get(0).nodeName ) { newText = $(newText).html(); } // Update element and remove editor resetElement($el, newText, opts.emptyMessage); editor.remove(); $textArea = false; $win.unbind('click', editorBlur); $currentlyEdited = false; // Run callback if( typeof opts.callback == 'function' ) { opts.callback({ content : newText == defaultText || !hasPressedKey ? false : newText, fontSize : false, $el : $el }); } }; // Blur editor when user clicks outside the editor setTimeout(function() { $win.bind('click', editorBlur); }, 500); // Create a dummy textarea that will called upon when // programmatically interacting with the editor $textArea = $('<textarea></textarea>'); $textArea.bind('blur', editorBlur); editorWindow.onkeydown = function() { hasPressedKey = true; }; editorWindow.focus(); }); }; tinyMCE.init(opts.tinyMCE); } /* TEXTAREA EDITOR */ else { if( opts.toggleFontSize || opts.closeOnEnter ) { $win.bind('keydown', opts, keyHandler); } $win.bind('keyup', adjustTextAreaHeight); $textArea .val(defaultText) .blur(function() { $currentlyEdited = false; // Get new text and font size var newText = $.trim( $textArea.val() ), newFontSize = $textArea.css('font-size'); if( opts.lineBreaks ) { newText = newText.replace(new RegExp('\n','g'), '<br />'); } // Update element resetElement($el, newText, opts.emptyMessage); if( newFontSize != defaultFontSize ) { $el.css('font-size', newFontSize); } // remove textarea and size toggles $win.unbind('keydown', keyHandler); $win.unbind('keyup', adjustTextAreaHeight); // Run callback if( typeof opts.callback == 'function' ) { opts.callback({ content : newText == defaultText ? false : newText, fontSize : newFontSize == defaultFontSize ? false : newFontSize, $el : $el }); } }) .attr('style', textareaStyle) .appendTo($el) .css({ margin: 0, padding: 0, height : elementHeight +'px', overflow : 'hidden' }) .css(opts.editorStyle) .focus() .get(0).select(); adjustTextAreaHeight(); } $el.trigger('edit', [$textArea]); }, /** * Event listener */ editEvent = function(event) { if( $currentlyEdited !== false ) { // Not closing the currently open editor before opening a new // editor makes things go crazy $currentlyEdited.editable('close'); elementEditor($(this), event.data); } else { elementEditor($(this), event.data); } return false; }; /** * Jquery plugin that makes elments editable * @param {Object|String} [opts] Either callback function or the string 'destroy' if wanting to remove the editor event * @return {jQuery|Boolean} */ $.fn.editable = function(opts) { if(typeof opts == 'string') { if( this.is(':editable') ) { switch (opts) { case 'open': if( !this.is(':editing') ) { this.trigger(this.attr(EVENT_ATTR)); } break; case 'close': if( this.is(':editing') ) { $textArea.trigger('blur'); } break; case 'destroy': if( this.is(':editing') ) { $textArea.trigger('blur'); } this.unbind(this.attr(EVENT_ATTR)); this.removeAttr(EVENT_ATTR); break; default: console.warn('Unknown command "'+opts+'" for jquery.editable'); } } else { console.error('Calling .editable() on an element that is not editable, call .editable() first'); } } else { if( this.is(':editable') ) { console.warn('Making an already editable element editable, call .editable("destroy") first'); this.editable('destroy'); } opts = $.extend({ event : 'dblclick', touch : true, lineBreaks : true, toggleFontSize : true, closeOnEnter : false, emptyMessage : false, tinyMCE : false, editorStyle : {} }, opts); if( opts.tinyMCE !== false && !TINYMCE_INSTALLED ) { console.warn('Trying to use tinyMCE as editor but id does not seem to be installed'); opts.tinyMCE = false; } if( SUPPORTS_TOUCH && opts.touch ) { opts.event = DBL_TAP_EVENT; this.unbind('touchend', tapper); this.bind('touchend', tapper); } else { opts.event += '.textEditor'; } this.bind(opts.event, opts, editEvent); this.attr(EVENT_ATTR, opts.event); // If it is empty to start with, apply the empty message if (this.html().length == 0 && opts.emptyMessage) { this.html(opts.emptyMessage); this.attr(EMPTY_ATTR, 'empty'); } else { this.removeAttr(EMPTY_ATTR); } } return this; }; /** * Add :editable :editing to $.is() * @param {Object} statement * @return {*} */ $.fn.is = function(statement) { if( typeof statement == 'string' && statement.indexOf(':') === 0) { if( statement == ':editable' ) { return this.attr(EVENT_ATTR) !== undefined; } else if( statement == ':editing' ) { return this.attr(IS_EDITING_ATTR) !== undefined; } else if( statement == ':empty' ) { return this.attr(EMPTY_ATTR) !== undefined; } } return oldjQueryIs.apply(this, arguments); } })(jQuery, window);
JavaScript
/*! * jQuery Stepy - A Wizard Plugin * -------------------------------------------------------------- * * jQuery Stepy is a plugin that generates a customizable wizard. * * Licensed under The MIT License * * @version 1.1.0 * @since 2010-07-03 * @author Washington Botelho * @documentation wbotelhos.com/stepy * * -------------------------------------------------------------- * * <form> * <fieldset title="Step 1"> * <legend>description one</legend> * <!-- inputs --> * </fieldset> * * <fieldset title="Step 2"> * <legend>description two</legend> * <!-- inputs --> * </fieldset> * * <input type="submit" /> * </form> * * $('form').stepy(); * */ ;(function($) { var methods = { init: function(settings) { return this.each(function() { methods.destroy.call(this); this.opt = $.extend({}, $.fn.stepy.defaults, settings); var self = this, that = $(this), id = that.attr('id'); if (id === undefined || id === '') { var id = methods._hash.call(self); that.attr('id', id); } // Remove Validator... if (self.opt.validate) { jQuery.validator.setDefaults({ ignore: self.opt.ignore }); that.append('<div class="stepy-errors" />'); } self.header = methods._header.call(self); self.steps = that.children('fieldset'); self.steps.each(function(index) { methods._createHead.call(self, this, index); methods._createButtons.call(self, this, index); }); self.heads = self.header.children('li'); self.heads.first().addClass('stepy-active'); if (self.opt.finishButton) { methods._bindFinish.call(self); } // WIP... if (self.opt.titleClick) { self.heads.click(function() { var array = self.heads.filter('.stepy-active').attr('id').split('-'), // TODO: try keep the number in an attribute. current = parseInt(array[array.length - 1], 10), clicked = $(this).index(); if (clicked > current) { if (self.opt.next && !methods._execute.call(that, self.opt.next, clicked)) { return false; } } else if (clicked < current) { if (self.opt.back && !methods._execute.call(that, self.opt.back, clicked)) { return false; } } if (clicked != current) { methods.step.call(self, (clicked) + 1); } }); } else { self.heads.css('cursor', 'default'); } if (self.opt.enter) { methods._bindEnter.call(self); } self.steps.first().find(':input:visible:enabled').first().select().focus(); that.data({ 'settings': this.opt, 'stepy': true }); }); }, _bindEnter: function() { var self = this; self.steps.delegate('input[type="text"], input[type="password"]', 'keypress', function(evt) { var key = (evt.keyCode ? evt.keyCode : evt.which); if (key == 13) { evt.preventDefault(); var buttons = $(this).closest('fieldset').find('.stepy-navigator'); if (buttons.length) { var next = buttons.children('.button-next'); if (next.length) { next.click(); } else if (self.finish) { self.finish.click(); } } } }); }, _bindFinish: function() { var self = this, that = $(this), finish = that.children('input[type="submit"]'); self.finish = (finish.length === 1) ? finish : that.children('.btn .btn-succes .stepy-finish'); if (self.finish.length) { var isForm = that.is('form'), onSubmit = undefined; if (isForm && self.opt.finish) { onSubmit = that.attr('onsubmit'); that.attr('onsubmit', 'return false;'); } self.finish.on('click.stepy', function(evt) { if (self.opt.finish && !methods._execute.call(that, self.opt.finish, self.steps.length - 1)) { evt.preventDefault(); } else if (isForm) { if (onSubmit) { that.attr('onsubmit', onSubmit); } else { that.removeAttr('onsubmit'); } var isSubmit = self.finish.attr('type') === 'submit'; if (!isSubmit && (!self.opt.validate || methods.validate.call(that, self.steps.length - 1))) { that.submit(); } } }); self.steps.last().children('.stepy-navigator').append(self.finish); } else { $.error('Submit button or element with class "stepy-finish" missing!'); } }, _createBackButton: function(nav, index) { var self = this, that = $(this), attributes = { href: '#', 'class': 'btn btn-default', html: self.opt.backLabel }; $('<a />', attributes).on('click.stepy', function(e) { e.preventDefault(); if (!self.opt.back || methods._execute.call(self, self.opt.back, index - 1)) { methods.step.call(self, (index - 1) + 1); } }).appendTo(nav); }, _createButtons: function(step, index) { var nav = methods._navigator.call(this).appendTo(step); if (index === 0) { if (this.steps.length > 1) { methods._createNextButton.call(this, nav, index); } } else { $(step).hide(); methods._createBackButton.call(this, nav, index); if (index < this.steps.length - 1) { methods._createNextButton.call(this, nav, index); } } }, _createHead: function(step, index) { var step = $(step).attr('id', $(this).attr('id') + '-step-' + index).addClass('stepy-step'), head = methods._head.call(this, index); head.append(methods._title.call(this, step)); if (this.opt.description) { head.append(methods._description.call(this, step)); } this.header.append(head); }, _createNextButton: function(nav, index) { var self = this, that = $(this), attributes = { href: '#', 'class': 'btn btn-primary', html: self.opt.nextLabel }; $('<a/>', attributes).on('click.stepy', function(e) { e.preventDefault(); if (!self.opt.next || methods._execute.call(that, self.opt.next, index + 1)) { methods.step.call(self, (index + 1) + 1); } }).appendTo(nav); }, _description: function(step) { var legend = step.children('legend'); if (!this.opt.legend) { legend.hide(); } if (legend.length) { return $('<span />', { html: legend.html() }); } methods._error.call(this, '<legend /> element missing!'); }, _error: function(message) { $(this).html(message); $.error(message); }, _execute: function(callback, index) { var isValid = callback.call(this, index + 1); return isValid || isValid === undefined; }, _hash: function() { this.hash = 'stepy-' + Math.random().toString().substring(2) return this.hash; }, _head: function(index) { return $('<li />', { id: $(this).attr('id') + '-head-' + index }); }, _header: function() { var header = $('<ul />', { id: $(this).attr('id') + '-header', 'class': 'stepy-header' }); if (this.opt.titleTarget) { header.appendTo(this.opt.titleTarget); } else { header.insertBefore(this); } return header; }, _navigator: function(index) { return $('<div class="stepy-navigator panel-footer" />'); }, _title: function(step) { return $('<div />', { html: step.attr('title') || '--' }); }, destroy: function() { return $(this).each(function() { var that = $(this); if (that.data('stepy')) { var steps = that.data('stepy', false).children('fieldset').css('display', ''); that.children('.stepy-errors').remove(); this.finish.appendTo(steps.last()); steps.find('.stepy-navigator').remove(); } }); }, step: function(index) { var self = this that = $(this), opt = that[0].opt; index--; var steps = that.children('fieldset'); if (index > steps.length - 1) { index = steps.length - 1; } var max = index; // Remove Validator... if (opt.validate) { var isValid = true; for (var i = 0; i < index; i++) { isValid &= methods.validate.call(this, i); if (opt.block && !isValid) { max = i; break; } } } // WIP... var stepsCount = steps.length; if (opt.transition == 'fade') { steps.fadeOut(opt.duration, function() { if (--stepsCount > 0) { return; } steps.eq(max).fadeIn(opt.duration); }); } else if (opt.transition == 'slide') { steps.slideUp(opt.duration, function() { if (--stepsCount > 0) { return; } steps.eq(max).slideDown(opt.duration); }); } else { steps.hide(opt.duration).eq(max).show(opt.duration); } that[0].heads.removeClass('stepy-active').eq(max).addClass('stepy-active'); if (that.is('form')) { var $fields = undefined; if (max == index) { $fields = steps.eq(max).find(':input:enabled:visible'); } else { $fields = steps.eq(max).find('.error').select().focus(); } $fields.first().select().focus(); } if (opt.select) { opt.select.call(this, max + 1); } return that; }, validate: function(index) { // WIP... var that = $(this); if (!that.is('form')) { return true; } var self = this, step = that.children('fieldset').eq(index), isValid = true, $title = $('#' + that.attr('id') + '-header').children().eq(index), $validate = that.validate(); $(step.find(':input:enabled').get().reverse()).each(function() { var fieldIsValid = $validate.element($(this)); if (fieldIsValid === undefined) { fieldIsValid = true; } isValid &= fieldIsValid; if (isValid) { if (self.opt.errorImage) { $title.removeClass('stepy-error'); } } else { if (self.opt.errorImage) { $title.addClass('stepy-error'); } $validate.focusInvalid(); } }); return isValid; } }; $.fn.stepy = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist!'); } }; $.fn.stepy.defaults = { back : undefined, backLabel : '<i class="fa fa-long-arrow-left"></i> Back', block : false, // WIP... description : true, duration : undefined, enter : true, errorImage : false, // WIP... finish : undefined, finishButton : true, ignore : '', // WIP... legend : true, next : undefined, nextLabel : 'Next <i class="fa fa-long-arrow-right"></i>', select : undefined, titleClick : false, titleTarget : undefined, transition : undefined, validate : false // WIP... }; })(jQuery);
JavaScript
/* * jQuery Pines Notify (pnotify) Plugin 1.2.0 * * http://pinesframework.org/pnotify/ * Copyright (c) 2009-2012 Hunter Perrin * * Triple license under the GPL, LGPL, and MPL: * http://www.gnu.org/licenses/gpl.html * http://www.gnu.org/licenses/lgpl.html * http://www.mozilla.org/MPL/MPL-1.1.html */ (function($) { var history_handle_top, timer, body, jwindow = $(window), styling = { jqueryui: { container: "ui-widget ui-widget-content ui-corner-all", notice: "ui-state-highlight", // (The actual jQUI notice icon looks terrible.) notice_icon: "ui-icon ui-icon-info", info: "", info_icon: "ui-icon ui-icon-info", success: "ui-state-default", success_icon: "ui-icon ui-icon-circle-check", error: "ui-state-error", error_icon: "ui-icon ui-icon-alert", closer: "ui-icon ui-icon-close", pin_up: "ui-icon ui-icon-pin-w", pin_down: "ui-icon ui-icon-pin-s", hi_menu: "ui-state-default ui-corner-bottom", hi_btn: "ui-state-default ui-corner-all", hi_btnhov: "ui-state-hover", hi_hnd: "ui-icon ui-icon-grip-dotted-horizontal" }, bootstrap: { container: "alert", notice: "", notice_icon: "fa-exclamation", info: "alert-info", info_icon: "fa fa-info", success: "alert-success", success_icon: "fa fa-check", error: "alert-danger", error_icon: "fa fa-exclamation-triangle", closer: "fa fa-times", pin_up: "fa fa-pause", pin_down: "fa fa-play", hi_menu: "well", hi_btn: "btn", hi_btnhov: "", hi_hnd: "fa fa-chevron-down" } }; // Set global variables. var do_when_ready = function(){ body = $("body"); jwindow = $(window); // Reposition the notices when the window resizes. jwindow.bind('resize', function(){ if (timer) clearTimeout(timer); timer = setTimeout($.pnotify_position_all, 10); }); }; if (document.body) do_when_ready(); else $(do_when_ready); $.extend({ pnotify_remove_all: function () { var notices_data = jwindow.data("pnotify"); /* POA: Added null-check */ if (notices_data && notices_data.length) { $.each(notices_data, function(){ if (this.pnotify_remove) this.pnotify_remove(); }); } }, pnotify_position_all: function () { // This timer is used for queueing this function so it doesn't run // repeatedly. if (timer) clearTimeout(timer); timer = null; // Get all the notices. var notices_data = jwindow.data("pnotify"); if (!notices_data || !notices_data.length) return; // Reset the next position data. $.each(notices_data, function(){ var s = this.opts.stack; if (!s) return; s.nextpos1 = s.firstpos1; s.nextpos2 = s.firstpos2; s.addpos2 = 0; s.animation = true; }); $.each(notices_data, function(){ this.pnotify_position(); }); }, pnotify: function(options) { // Stores what is currently being animated (in or out). var animating; // Build main options. var opts; if (typeof options != "object") { opts = $.extend({}, $.pnotify.defaults); opts.text = options; } else { opts = $.extend({}, $.pnotify.defaults, options); } // Translate old pnotify_ style options. for (var i in opts) { if (typeof i == "string" && i.match(/^pnotify_/)) opts[i.replace(/^pnotify_/, "")] = opts[i]; } if (opts.before_init) { if (opts.before_init(opts) === false) return null; } // This keeps track of the last element the mouse was over, so // mouseleave, mouseenter, etc can be called. var nonblock_last_elem; // This is used to pass events through the notice if it is non-blocking. var nonblock_pass = function(e, e_name){ pnotify.css("display", "none"); var element_below = document.elementFromPoint(e.clientX, e.clientY); pnotify.css("display", "block"); var jelement_below = $(element_below); var cursor_style = jelement_below.css("cursor"); pnotify.css("cursor", cursor_style != "auto" ? cursor_style : "default"); // If the element changed, call mouseenter, mouseleave, etc. if (!nonblock_last_elem || nonblock_last_elem.get(0) != element_below) { if (nonblock_last_elem) { dom_event.call(nonblock_last_elem.get(0), "mouseleave", e.originalEvent); dom_event.call(nonblock_last_elem.get(0), "mouseout", e.originalEvent); } dom_event.call(element_below, "mouseenter", e.originalEvent); dom_event.call(element_below, "mouseover", e.originalEvent); } dom_event.call(element_below, e_name, e.originalEvent); // Remember the latest element the mouse was over. nonblock_last_elem = jelement_below; }; // Get our styling object. var styles = styling[opts.styling]; // Create our widget. // Stop animation, reset the removal timer, and show the close // button when the user mouses over. var pnotify = $("<div />", { "class": "ui-pnotify "+opts.addclass, "css": {"display": "none"}, "mouseenter": function(e){ if (opts.nonblock) e.stopPropagation(); if (opts.mouse_reset && animating == "out") { // If it's animating out, animate back in really quickly. pnotify.stop(true); animating = "in"; pnotify.css("height", "auto").animate({"width": opts.width, "opacity": opts.nonblock ? opts.nonblock_opacity : opts.opacity}, "fast"); } if (opts.nonblock) { // If it's non-blocking, animate to the other opacity. pnotify.animate({"opacity": opts.nonblock_opacity}, "fast"); } // Stop the close timer. if (opts.hide && opts.mouse_reset) pnotify.pnotify_cancel_remove(); // Show the buttons. if (opts.sticker && !opts.nonblock) pnotify.sticker.trigger("pnotify_icon").css("visibility", "visible"); if (opts.closer && !opts.nonblock) pnotify.closer.css("visibility", "visible"); }, "mouseleave": function(e){ if (opts.nonblock) e.stopPropagation(); nonblock_last_elem = null; pnotify.css("cursor", "auto"); // Animate back to the normal opacity. if (opts.nonblock && animating != "out") pnotify.animate({"opacity": opts.opacity}, "fast"); // Start the close timer. if (opts.hide && opts.mouse_reset) pnotify.pnotify_queue_remove(); // Hide the buttons. if (opts.sticker_hover) pnotify.sticker.css("visibility", "hidden"); if (opts.closer_hover) pnotify.closer.css("visibility", "hidden"); $.pnotify_position_all(); }, "mouseover": function(e){ if (opts.nonblock) e.stopPropagation(); }, "mouseout": function(e){ if (opts.nonblock) e.stopPropagation(); }, "mousemove": function(e){ if (opts.nonblock) { e.stopPropagation(); nonblock_pass(e, "onmousemove"); } }, "mousedown": function(e){ if (opts.nonblock) { e.stopPropagation(); e.preventDefault(); nonblock_pass(e, "onmousedown"); } }, "mouseup": function(e){ if (opts.nonblock) { e.stopPropagation(); e.preventDefault(); nonblock_pass(e, "onmouseup"); } }, "click": function(e){ if (opts.nonblock) { e.stopPropagation(); nonblock_pass(e, "onclick"); } }, "dblclick": function(e){ if (opts.nonblock) { e.stopPropagation(); nonblock_pass(e, "ondblclick"); } } }); pnotify.opts = opts; // Create a container for the notice contents. pnotify.container = $("<div />", {"class": styles.container+" ui-pnotify-container "+(opts.type == "error" ? styles.error : (opts.type == "info" ? styles.info : (opts.type == "success" ? styles.success : styles.notice)))}) .appendTo(pnotify); if (opts.cornerclass != "") pnotify.container.removeClass("ui-corner-all").addClass(opts.cornerclass); // Create a drop shadow. if (opts.shadow) pnotify.container.addClass("ui-pnotify-shadow"); // The current version of Pines Notify. pnotify.pnotify_version = "1.2.0"; // This function is for updating the notice. pnotify.pnotify = function(options) { // Update the notice. var old_opts = opts; if (typeof options == "string") opts.text = options; else opts = $.extend({}, opts, options); // Translate old pnotify_ style options. for (var i in opts) { if (typeof i == "string" && i.match(/^pnotify_/)) opts[i.replace(/^pnotify_/, "")] = opts[i]; } pnotify.opts = opts; // Update the corner class. if (opts.cornerclass != old_opts.cornerclass) pnotify.container.removeClass("ui-corner-all").addClass(opts.cornerclass); // Update the shadow. if (opts.shadow != old_opts.shadow) { if (opts.shadow) pnotify.container.addClass("ui-pnotify-shadow"); else pnotify.container.removeClass("ui-pnotify-shadow"); } // Update the additional classes. if (opts.addclass === false) pnotify.removeClass(old_opts.addclass); else if (opts.addclass !== old_opts.addclass) pnotify.removeClass(old_opts.addclass).addClass(opts.addclass); // Update the title. if (opts.title === false) pnotify.title_container.slideUp("fast"); else if (opts.title !== old_opts.title) { if (opts.title_escape) pnotify.title_container.text(opts.title).slideDown(200); else pnotify.title_container.html(opts.title).slideDown(200); } // Update the text. if (opts.text === false) { pnotify.text_container.slideUp("fast"); } else if (opts.text !== old_opts.text) { if (opts.text_escape) pnotify.text_container.text(opts.text).slideDown(200); else pnotify.text_container.html(opts.insert_brs ? String(opts.text).replace(/\n/g, "<br />") : opts.text).slideDown(200); } // Update values for history menu access. pnotify.pnotify_history = opts.history; pnotify.pnotify_hide = opts.hide; // Change the notice type. if (opts.type != old_opts.type) pnotify.container.removeClass(styles.error+" "+styles.notice+" "+styles.success+" "+styles.info).addClass(opts.type == "error" ? styles.error : (opts.type == "info" ? styles.info : (opts.type == "success" ? styles.success : styles.notice))); if (opts.icon !== old_opts.icon || (opts.icon === true && opts.type != old_opts.type)) { // Remove any old icon. pnotify.container.find("div.ui-pnotify-icon").remove(); if (opts.icon !== false) { // Build the new icon. $("<div />", {"class": "ui-pnotify-icon"}) .append($("<span />", {"class": opts.icon === true ? (opts.type == "error" ? styles.error_icon : (opts.type == "info" ? styles.info_icon : (opts.type == "success" ? styles.success_icon : styles.notice_icon))) : opts.icon})) .prependTo(pnotify.container); } } // Update the width. if (opts.width !== old_opts.width) pnotify.animate({width: opts.width}); // Update the minimum height. if (opts.min_height !== old_opts.min_height) pnotify.container.animate({minHeight: opts.min_height}); // Update the opacity. if (opts.opacity !== old_opts.opacity) pnotify.fadeTo(opts.animate_speed, opts.opacity); // Update the sticker and closer buttons. if (!opts.closer || opts.nonblock) pnotify.closer.css("display", "none"); else pnotify.closer.css("display", "block"); if (!opts.sticker || opts.nonblock) pnotify.sticker.css("display", "none"); else pnotify.sticker.css("display", "block"); // Update the sticker icon. pnotify.sticker.trigger("pnotify_icon"); // Update the hover status of the buttons. if (opts.sticker_hover) pnotify.sticker.css("visibility", "hidden"); else if (!opts.nonblock) pnotify.sticker.css("visibility", "visible"); if (opts.closer_hover) pnotify.closer.css("visibility", "hidden"); else if (!opts.nonblock) pnotify.closer.css("visibility", "visible"); // Update the timed hiding. if (!opts.hide) pnotify.pnotify_cancel_remove(); else if (!old_opts.hide) pnotify.pnotify_queue_remove(); pnotify.pnotify_queue_position(); return pnotify; }; // Position the notice. dont_skip_hidden causes the notice to // position even if it's not visible. pnotify.pnotify_position = function(dont_skip_hidden){ // Get the notice's stack. var s = pnotify.opts.stack; if (!s) return; if (!s.nextpos1) s.nextpos1 = s.firstpos1; if (!s.nextpos2) s.nextpos2 = s.firstpos2; if (!s.addpos2) s.addpos2 = 0; var hidden = pnotify.css("display") == "none"; // Skip this notice if it's not shown. if (!hidden || dont_skip_hidden) { var curpos1, curpos2; // Store what will need to be animated. var animate = {}; // Calculate the current pos1 value. var csspos1; switch (s.dir1) { case "down": csspos1 = "top"; break; case "up": csspos1 = "bottom"; break; case "left": csspos1 = "right"; break; case "right": csspos1 = "left"; break; } curpos1 = parseInt(pnotify.css(csspos1)); if (isNaN(curpos1)) curpos1 = 0; // Remember the first pos1, so the first visible notice goes there. if (typeof s.firstpos1 == "undefined" && !hidden) { s.firstpos1 = curpos1; s.nextpos1 = s.firstpos1; } // Calculate the current pos2 value. var csspos2; switch (s.dir2) { case "down": csspos2 = "top"; break; case "up": csspos2 = "bottom"; break; case "left": csspos2 = "right"; break; case "right": csspos2 = "left"; break; } curpos2 = parseInt(pnotify.css(csspos2)); if (isNaN(curpos2)) curpos2 = 0; // Remember the first pos2, so the first visible notice goes there. if (typeof s.firstpos2 == "undefined" && !hidden) { s.firstpos2 = curpos2; s.nextpos2 = s.firstpos2; } // Check that it's not beyond the viewport edge. if ((s.dir1 == "down" && s.nextpos1 + pnotify.height() > jwindow.height()) || (s.dir1 == "up" && s.nextpos1 + pnotify.height() > jwindow.height()) || (s.dir1 == "left" && s.nextpos1 + pnotify.width() > jwindow.width()) || (s.dir1 == "right" && s.nextpos1 + pnotify.width() > jwindow.width()) ) { // If it is, it needs to go back to the first pos1, and over on pos2. s.nextpos1 = s.firstpos1; s.nextpos2 += s.addpos2 + (typeof s.spacing2 == "undefined" ? 25 : s.spacing2); s.addpos2 = 0; } // Animate if we're moving on dir2. if (s.animation && s.nextpos2 < curpos2) { switch (s.dir2) { case "down": animate.top = s.nextpos2+"px"; break; case "up": animate.bottom = s.nextpos2+"px"; break; case "left": animate.right = s.nextpos2+"px"; break; case "right": animate.left = s.nextpos2+"px"; break; } } else pnotify.css(csspos2, s.nextpos2+"px"); // Keep track of the widest/tallest notice in the column/row, so we can push the next column/row. switch (s.dir2) { case "down": case "up": if (pnotify.outerHeight(true) > s.addpos2) s.addpos2 = pnotify.height(); break; case "left": case "right": if (pnotify.outerWidth(true) > s.addpos2) s.addpos2 = pnotify.width(); break; } // Move the notice on dir1. if (s.nextpos1) { // Animate if we're moving toward the first pos. if (s.animation && (curpos1 > s.nextpos1 || animate.top || animate.bottom || animate.right || animate.left)) { switch (s.dir1) { case "down": animate.top = s.nextpos1+"px"; break; case "up": animate.bottom = s.nextpos1+"px"; break; case "left": animate.right = s.nextpos1+"px"; break; case "right": animate.left = s.nextpos1+"px"; break; } } else pnotify.css(csspos1, s.nextpos1+"px"); } // Run the animation. if (animate.top || animate.bottom || animate.right || animate.left) pnotify.animate(animate, {duration: 500, queue: false}); // Calculate the next dir1 position. switch (s.dir1) { case "down": case "up": s.nextpos1 += pnotify.height() + (typeof s.spacing1 == "undefined" ? 25 : s.spacing1); break; case "left": case "right": s.nextpos1 += pnotify.width() + (typeof s.spacing1 == "undefined" ? 25 : s.spacing1); break; } } }; // Queue the positiona all function so it doesn't run repeatedly and // use up resources. pnotify.pnotify_queue_position = function(milliseconds){ if (timer) clearTimeout(timer); if (!milliseconds) milliseconds = 10; timer = setTimeout($.pnotify_position_all, milliseconds); }; // Display the notice. pnotify.pnotify_display = function() { // If the notice is not in the DOM, append it. if (!pnotify.parent().length) pnotify.appendTo(body); // Run callback. if (opts.before_open) { if (opts.before_open(pnotify) === false) return; } // Try to put it in the right position. if (opts.stack.push != "top") pnotify.pnotify_position(true); // First show it, then set its opacity, then hide it. if (opts.animation == "fade" || opts.animation.effect_in == "fade") { // If it's fading in, it should start at 0. pnotify.show().fadeTo(0, 0).hide(); } else { // Or else it should be set to the opacity. if (opts.opacity != 1) pnotify.show().fadeTo(0, opts.opacity).hide(); } pnotify.animate_in(function(){ if (opts.after_open) opts.after_open(pnotify); pnotify.pnotify_queue_position(); // Now set it to hide. if (opts.hide) pnotify.pnotify_queue_remove(); }); }; // Remove the notice. pnotify.pnotify_remove = function() { if (pnotify.timer) { window.clearTimeout(pnotify.timer); pnotify.timer = null; } // Run callback. if (opts.before_close) { if (opts.before_close(pnotify) === false) return; } pnotify.animate_out(function(){ if (opts.after_close) { if (opts.after_close(pnotify) === false) return; } pnotify.pnotify_queue_position(); // If we're supposed to remove the notice from the DOM, do it. if (opts.remove) pnotify.detach(); }); }; // Animate the notice in. pnotify.animate_in = function(callback){ // Declare that the notice is animating in. (Or has completed animating in.) animating = "in"; var animation; if (typeof opts.animation.effect_in != "undefined") animation = opts.animation.effect_in; else animation = opts.animation; if (animation == "none") { pnotify.show(); callback(); } else if (animation == "show") pnotify.show(opts.animate_speed, callback); else if (animation == "fade") pnotify.show().fadeTo(opts.animate_speed, opts.opacity, callback); else if (animation == "slide") pnotify.slideDown(opts.animate_speed, callback); else if (typeof animation == "function") animation("in", callback, pnotify); else pnotify.show(animation, (typeof opts.animation.options_in == "object" ? opts.animation.options_in : {}), opts.animate_speed, callback); }; // Animate the notice out. pnotify.animate_out = function(callback){ // Declare that the notice is animating out. (Or has completed animating out.) animating = "out"; var animation; if (typeof opts.animation.effect_out != "undefined") animation = opts.animation.effect_out; else animation = opts.animation; if (animation == "none") { pnotify.hide(); callback(); } else if (animation == "show") pnotify.hide(opts.animate_speed, callback); else if (animation == "fade") pnotify.fadeOut(opts.animate_speed, callback); else if (animation == "slide") pnotify.slideUp(opts.animate_speed, callback); else if (typeof animation == "function") animation("out", callback, pnotify); else pnotify.hide(animation, (typeof opts.animation.options_out == "object" ? opts.animation.options_out : {}), opts.animate_speed, callback); }; // Cancel any pending removal timer. pnotify.pnotify_cancel_remove = function() { if (pnotify.timer) window.clearTimeout(pnotify.timer); }; // Queue a removal timer. pnotify.pnotify_queue_remove = function() { // Cancel any current removal timer. pnotify.pnotify_cancel_remove(); pnotify.timer = window.setTimeout(function(){ pnotify.pnotify_remove(); }, (isNaN(opts.delay) ? 0 : opts.delay)); }; // Provide a button to close the notice. pnotify.closer = $("<div />", { "class": "ui-pnotify-closer", "css": {"cursor": "pointer", "visibility": opts.closer_hover ? "hidden" : "visible"}, "click": function(){ pnotify.pnotify_remove(); pnotify.sticker.css("visibility", "hidden"); pnotify.closer.css("visibility", "hidden"); } }) .append($("<span />", {"class": styles.closer})) .appendTo(pnotify.container); if (!opts.closer || opts.nonblock) pnotify.closer.css("display", "none"); // Provide a button to stick the notice. pnotify.sticker = $("<div />", { "class": "ui-pnotify-sticker", "css": {"cursor": "pointer", "visibility": opts.sticker_hover ? "hidden" : "visible"}, "click": function(){ opts.hide = !opts.hide; if (opts.hide) pnotify.pnotify_queue_remove(); else pnotify.pnotify_cancel_remove(); $(this).trigger("pnotify_icon"); } }) .bind("pnotify_icon", function(){ $(this).children().removeClass(styles.pin_up+" "+styles.pin_down).addClass(opts.hide ? styles.pin_up : styles.pin_down); }) .append($("<span />", {"class": styles.pin_up})) .appendTo(pnotify.container); if (!opts.sticker || opts.nonblock) pnotify.sticker.css("display", "none"); // Add the appropriate icon. if (opts.icon !== false) { $("<div />", {"class": "ui-pnotify-icon"}) .append($("<span />", {"class": opts.icon === true ? (opts.type == "error" ? styles.error_icon : (opts.type == "info" ? styles.info_icon : (opts.type == "success" ? styles.success_icon : styles.notice_icon))) : opts.icon})) .prependTo(pnotify.container); } // Add a title. pnotify.title_container = $("<h4 />", { "class": "ui-pnotify-title" }) .appendTo(pnotify.container); if (opts.title === false) pnotify.title_container.hide(); else if (opts.title_escape) pnotify.title_container.text(opts.title); else pnotify.title_container.html(opts.title); // Add text. pnotify.text_container = $("<div />", { "class": "ui-pnotify-text" }) .appendTo(pnotify.container); if (opts.text === false) pnotify.text_container.hide(); else if (opts.text_escape) pnotify.text_container.text(opts.text); else pnotify.text_container.html(opts.insert_brs ? String(opts.text).replace(/\n/g, "<br />") : opts.text); // Set width and min height. if (typeof opts.width == "string") pnotify.css("width", opts.width); if (typeof opts.min_height == "string") pnotify.container.css("min-height", opts.min_height); // The history variable controls whether the notice gets redisplayed // by the history pull down. pnotify.pnotify_history = opts.history; // The hide variable controls whether the history pull down should // queue a removal timer. pnotify.pnotify_hide = opts.hide; // Add the notice to the notice array. var notices_data = jwindow.data("pnotify"); if (notices_data == null || typeof notices_data != "object") notices_data = []; if (opts.stack.push == "top") notices_data = $.merge([pnotify], notices_data); else notices_data = $.merge(notices_data, [pnotify]); jwindow.data("pnotify", notices_data); // Now position all the notices if they are to push to the top. if (opts.stack.push == "top") pnotify.pnotify_queue_position(1); // Run callback. if (opts.after_init) opts.after_init(pnotify); if (opts.history) { // If there isn't a history pull down, create one. var history_menu = jwindow.data("pnotify_history"); if (typeof history_menu == "undefined") { history_menu = $("<div />", { "class": "ui-pnotify-history-container "+styles.hi_menu, "mouseleave": function(){ history_menu.animate({top: "-"+history_handle_top+"px"}, {duration: 100, queue: false}); } }) .append($("<div />", {"class": "ui-pnotify-history-header", "text": "Redisplay"})) .append($("<button />", { "class": "ui-pnotify-history-all "+styles.hi_btn, "text": "All", "mouseenter": function(){ $(this).addClass(styles.hi_btnhov); }, "mouseleave": function(){ $(this).removeClass(styles.hi_btnhov); }, "click": function(){ // Display all notices. (Disregarding non-history notices.) $.each(notices_data, function(){ if (this.pnotify_history) { if (this.is(":visible")) { if (this.pnotify_hide) this.pnotify_queue_remove(); } else if (this.pnotify_display) this.pnotify_display(); } }); return false; } })) .append($("<button />", { "class": "ui-pnotify-history-last "+styles.hi_btn, "text": "Last", "mouseenter": function(){ $(this).addClass(styles.hi_btnhov); }, "mouseleave": function(){ $(this).removeClass(styles.hi_btnhov); }, "click": function(){ // Look up the last history notice, and display it. var i = -1; var notice; do { if (i == -1) notice = notices_data.slice(i); else notice = notices_data.slice(i, i+1); if (!notice[0]) break; i--; } while (!notice[0].pnotify_history || notice[0].is(":visible")); if (!notice[0]) return false; if (notice[0].pnotify_display) notice[0].pnotify_display(); return false; } })) .appendTo(body); // Make a handle so the user can pull down the history tab. var handle = $("<span />", { "class": "ui-pnotify-history-pulldown "+styles.hi_hnd, "mouseenter": function(){ history_menu.animate({top: "0"}, {duration: 100, queue: false}); } }) .appendTo(history_menu); // Get the top of the handle. history_handle_top = handle.offset().top + 2; // Hide the history pull down up to the top of the handle. history_menu.css({top: "-"+history_handle_top+"px"}); // Save the history pull down. jwindow.data("pnotify_history", history_menu); } } // Mark the stack so it won't animate the new notice. opts.stack.animation = false; // Display the notice. pnotify.pnotify_display(); return pnotify; } }); // Some useful regexes. var re_on = /^on/, re_mouse_events = /^(dbl)?click$|^mouse(move|down|up|over|out|enter|leave)$|^contextmenu$/, re_ui_events = /^(focus|blur|select|change|reset)$|^key(press|down|up)$/, re_html_events = /^(scroll|resize|(un)?load|abort|error)$/; // Fire a DOM event. var dom_event = function(e, orig_e){ var event_object; e = e.toLowerCase(); if (document.createEvent && this.dispatchEvent) { // FireFox, Opera, Safari, Chrome e = e.replace(re_on, ''); if (e.match(re_mouse_events)) { // This allows the click event to fire on the notice. There is // probably a much better way to do it. $(this).offset(); event_object = document.createEvent("MouseEvents"); event_object.initMouseEvent( e, orig_e.bubbles, orig_e.cancelable, orig_e.view, orig_e.detail, orig_e.screenX, orig_e.screenY, orig_e.clientX, orig_e.clientY, orig_e.ctrlKey, orig_e.altKey, orig_e.shiftKey, orig_e.metaKey, orig_e.button, orig_e.relatedTarget ); } else if (e.match(re_ui_events)) { event_object = document.createEvent("UIEvents"); event_object.initUIEvent(e, orig_e.bubbles, orig_e.cancelable, orig_e.view, orig_e.detail); } else if (e.match(re_html_events)) { event_object = document.createEvent("HTMLEvents"); event_object.initEvent(e, orig_e.bubbles, orig_e.cancelable); } if (!event_object) return; this.dispatchEvent(event_object); } else { // Internet Explorer if (!e.match(re_on)) e = "on"+e; event_object = document.createEventObject(orig_e); this.fireEvent(e, event_object); } }; $.pnotify.defaults = { // The notice's title. title: false, // Whether to escape the content of the title. (Not allow HTML.) title_escape: false, // The notice's text. text: false, // Whether to escape the content of the text. (Not allow HTML.) text_escape: false, // What styling classes to use. (Can be either jqueryui or bootstrap.) styling: "bootstrap", // Additional classes to be added to the notice. (For custom styling.) addclass: "", // Class to be added to the notice for corner styling. cornerclass: "", // Create a non-blocking notice. It lets the user click elements underneath it. nonblock: false, // The opacity of the notice (if it's non-blocking) when the mouse is over it. nonblock_opacity: .2, // Display a pull down menu to redisplay previous notices, and place the notice in the history. history: true, // Width of the notice. width: "300px", // Minimum height of the notice. It will expand to fit content. min_height: "16px", // Type of the notice. "notice", "info", "success", or "error". type: "notice", // Set icon to true to use the default icon for the selected style/type, false for no icon, or a string for your own icon class. icon: true, // The animation to use when displaying and hiding the notice. "none", "show", "fade", and "slide" are built in to jQuery. Others require jQuery UI. Use an object with effect_in and effect_out to use different effects. animation: "fade", // Speed at which the notice animates in and out. "slow", "def" or "normal", "fast" or number of milliseconds. animate_speed: "slow", // Opacity of the notice. opacity: 1, // Display a drop shadow. shadow: true, // Provide a button for the user to manually close the notice. closer: true, // Only show the closer button on hover. closer_hover: true, // Provide a button for the user to manually stick the notice. sticker: true, // Only show the sticker button on hover. sticker_hover: true, // After a delay, remove the notice. hide: true, // Delay in milliseconds before the notice is removed. delay: 8000, // Reset the hide timer if the mouse moves over the notice. mouse_reset: true, // Remove the notice's elements from the DOM after it is removed. remove: true, // Change new lines to br tags. insert_brs: true, // The stack on which the notices will be placed. Also controls the direction the notices stack. stack: {"dir1": "down", "dir2": "left", "push": "bottom", "spacing1": 25, "spacing2": 25} }; })(jQuery);
JavaScript
/* Flot plugin for stacking data sets rather than overlyaing them. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The plugin assumes the data is sorted on x (or y if stacking horizontally). For line charts, it is assumed that if a line has an undefined gap (from a null point), then the line above it should have the same gap - insert zeros instead of "null" if you want another behaviour. This also holds for the start and end of the chart. Note that stacking a mix of positive and negative values in most instances doesn't make sense (so it looks weird). Two or more series are stacked when their "stack" attribute is set to the same key (which can be any number or string or just "true"). To specify the default stack, you can set the stack option like this: series: { stack: null/false, true, or a key (number/string) } You can also specify it for a single series, like this: $.plot( $("#placeholder"), [{ data: [ ... ], stack: true }]) The stacking order is determined by the order of the data series in the array (later series end up on top of the previous). Internally, the plugin modifies the datapoints in each series, adding an offset to the y value. For line series, extra data points are inserted through interpolation. If there's a second y value, it's also adjusted (e.g for bar charts or filled areas). */ (function ($) { var options = { series: { stack: null } // or number/string }; function init(plot) { function findMatchingSeries(s, allseries) { var res = null; for (var i = 0; i < allseries.length; ++i) { if (s == allseries[i]) break; if (allseries[i].stack == s.stack) res = allseries[i]; } return res; } function stackData(plot, s, datapoints) { if (s.stack == null || s.stack === false) return; var other = findMatchingSeries(s, plot.getData()); if (!other) return; var ps = datapoints.pointsize, points = datapoints.points, otherps = other.datapoints.pointsize, otherpoints = other.datapoints.points, newpoints = [], px, py, intery, qx, qy, bottom, withlines = s.lines.show, horizontal = s.bars.horizontal, withbottom = ps > 2 && (horizontal ? datapoints.format[2].x : datapoints.format[2].y), withsteps = withlines && s.lines.steps, fromgap = true, keyOffset = horizontal ? 1 : 0, accumulateOffset = horizontal ? 0 : 1, i = 0, j = 0, l, m; while (true) { if (i >= points.length) break; l = newpoints.length; if (points[i] == null) { // copy gaps for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); i += ps; } else if (j >= otherpoints.length) { // for lines, we can't use the rest of the points if (!withlines) { for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); } i += ps; } else if (otherpoints[j] == null) { // oops, got a gap for (m = 0; m < ps; ++m) newpoints.push(null); fromgap = true; j += otherps; } else { // cases where we actually got two points px = points[i + keyOffset]; py = points[i + accumulateOffset]; qx = otherpoints[j + keyOffset]; qy = otherpoints[j + accumulateOffset]; bottom = 0; if (px == qx) { for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); newpoints[l + accumulateOffset] += qy; bottom = qy; i += ps; j += otherps; } else if (px > qx) { // we got past point below, might need to // insert interpolated extra point if (withlines && i > 0 && points[i - ps] != null) { intery = py + (points[i - ps + accumulateOffset] - py) * (qx - px) / (points[i - ps + keyOffset] - px); newpoints.push(qx); newpoints.push(intery + qy); for (m = 2; m < ps; ++m) newpoints.push(points[i + m]); bottom = qy; } j += otherps; } else { // px < qx if (fromgap && withlines) { // if we come from a gap, we just skip this point i += ps; continue; } for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); // we might be able to interpolate a point below, // this can give us a better y if (withlines && j > 0 && otherpoints[j - otherps] != null) bottom = qy + (otherpoints[j - otherps + accumulateOffset] - qy) * (px - qx) / (otherpoints[j - otherps + keyOffset] - qx); newpoints[l + accumulateOffset] += bottom; i += ps; } fromgap = false; if (l != newpoints.length && withbottom) newpoints[l + 2] += bottom; } // maintain the line steps invariant if (withsteps && l != newpoints.length && l > 0 && newpoints[l] != null && newpoints[l] != newpoints[l - ps] && newpoints[l + 1] != newpoints[l - ps + 1]) { for (m = 0; m < ps; ++m) newpoints[l + ps + m] = newpoints[l + m]; newpoints[l + 1] = newpoints[l - ps + 1]; } } datapoints.points = newpoints; } plot.hooks.processDatapoints.push(stackData); } $.plot.plugins.push({ init: init, options: options, name: 'stack', version: '1.2' }); })(jQuery);
JavaScript
/* Flot plugin for plotting error bars. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. Error bars are used to show standard deviation and other statistical properties in a plot. * Created by Rui Pereira - rui (dot) pereira (at) gmail (dot) com This plugin allows you to plot error-bars over points. Set "errorbars" inside the points series to the axis name over which there will be error values in your data array (*even* if you do not intend to plot them later, by setting "show: null" on xerr/yerr). The plugin supports these options: series: { points: { errorbars: "x" or "y" or "xy", xerr: { show: null/false or true, asymmetric: null/false or true, upperCap: null or "-" or function, lowerCap: null or "-" or function, color: null or color, radius: null or number }, yerr: { same options as xerr } } } Each data point array is expected to be of the type: "x" [ x, y, xerr ] "y" [ x, y, yerr ] "xy" [ x, y, xerr, yerr ] Where xerr becomes xerr_lower,xerr_upper for the asymmetric error case, and equivalently for yerr. Eg., a datapoint for the "xy" case with symmetric error-bars on X and asymmetric on Y would be: [ x, y, xerr, yerr_lower, yerr_upper ] By default no end caps are drawn. Setting upperCap and/or lowerCap to "-" will draw a small cap perpendicular to the error bar. They can also be set to a user-defined drawing function, with (ctx, x, y, radius) as parameters, as eg. function drawSemiCircle( ctx, x, y, radius ) { ctx.beginPath(); ctx.arc( x, y, radius, 0, Math.PI, false ); ctx.moveTo( x - radius, y ); ctx.lineTo( x + radius, y ); ctx.stroke(); } Color and radius both default to the same ones of the points series if not set. The independent radius parameter on xerr/yerr is useful for the case when we may want to add error-bars to a line, without showing the interconnecting points (with radius: 0), and still showing end caps on the error-bars. shadowSize and lineWidth are derived as well from the points series. */ (function ($) { var options = { series: { points: { errorbars: null, //should be 'x', 'y' or 'xy' xerr: { err: 'x', show: null, asymmetric: null, upperCap: null, lowerCap: null, color: null, radius: null}, yerr: { err: 'y', show: null, asymmetric: null, upperCap: null, lowerCap: null, color: null, radius: null} } } }; function processRawData(plot, series, data, datapoints){ if (!series.points.errorbars) return; // x,y values var format = [ { x: true, number: true, required: true }, { y: true, number: true, required: true } ]; var errors = series.points.errorbars; // error bars - first X then Y if (errors == 'x' || errors == 'xy') { // lower / upper error if (series.points.xerr.asymmetric) { format.push({ x: true, number: true, required: true }); format.push({ x: true, number: true, required: true }); } else format.push({ x: true, number: true, required: true }); } if (errors == 'y' || errors == 'xy') { // lower / upper error if (series.points.yerr.asymmetric) { format.push({ y: true, number: true, required: true }); format.push({ y: true, number: true, required: true }); } else format.push({ y: true, number: true, required: true }); } datapoints.format = format; } function parseErrors(series, i){ var points = series.datapoints.points; // read errors from points array var exl = null, exu = null, eyl = null, eyu = null; var xerr = series.points.xerr, yerr = series.points.yerr; var eb = series.points.errorbars; // error bars - first X if (eb == 'x' || eb == 'xy') { if (xerr.asymmetric) { exl = points[i + 2]; exu = points[i + 3]; if (eb == 'xy') if (yerr.asymmetric){ eyl = points[i + 4]; eyu = points[i + 5]; } else eyl = points[i + 4]; } else { exl = points[i + 2]; if (eb == 'xy') if (yerr.asymmetric) { eyl = points[i + 3]; eyu = points[i + 4]; } else eyl = points[i + 3]; } // only Y } else if (eb == 'y') if (yerr.asymmetric) { eyl = points[i + 2]; eyu = points[i + 3]; } else eyl = points[i + 2]; // symmetric errors? if (exu == null) exu = exl; if (eyu == null) eyu = eyl; var errRanges = [exl, exu, eyl, eyu]; // nullify if not showing if (!xerr.show){ errRanges[0] = null; errRanges[1] = null; } if (!yerr.show){ errRanges[2] = null; errRanges[3] = null; } return errRanges; } function drawSeriesErrors(plot, ctx, s){ var points = s.datapoints.points, ps = s.datapoints.pointsize, ax = [s.xaxis, s.yaxis], radius = s.points.radius, err = [s.points.xerr, s.points.yerr]; //sanity check, in case some inverted axis hack is applied to flot var invertX = false; if (ax[0].p2c(ax[0].max) < ax[0].p2c(ax[0].min)) { invertX = true; var tmp = err[0].lowerCap; err[0].lowerCap = err[0].upperCap; err[0].upperCap = tmp; } var invertY = false; if (ax[1].p2c(ax[1].min) < ax[1].p2c(ax[1].max)) { invertY = true; var tmp = err[1].lowerCap; err[1].lowerCap = err[1].upperCap; err[1].upperCap = tmp; } for (var i = 0; i < s.datapoints.points.length; i += ps) { //parse var errRanges = parseErrors(s, i); //cycle xerr & yerr for (var e = 0; e < err.length; e++){ var minmax = [ax[e].min, ax[e].max]; //draw this error? if (errRanges[e * err.length]){ //data coordinates var x = points[i], y = points[i + 1]; //errorbar ranges var upper = [x, y][e] + errRanges[e * err.length + 1], lower = [x, y][e] - errRanges[e * err.length]; //points outside of the canvas if (err[e].err == 'x') if (y > ax[1].max || y < ax[1].min || upper < ax[0].min || lower > ax[0].max) continue; if (err[e].err == 'y') if (x > ax[0].max || x < ax[0].min || upper < ax[1].min || lower > ax[1].max) continue; // prevent errorbars getting out of the canvas var drawUpper = true, drawLower = true; if (upper > minmax[1]) { drawUpper = false; upper = minmax[1]; } if (lower < minmax[0]) { drawLower = false; lower = minmax[0]; } //sanity check, in case some inverted axis hack is applied to flot if ((err[e].err == 'x' && invertX) || (err[e].err == 'y' && invertY)) { //swap coordinates var tmp = lower; lower = upper; upper = tmp; tmp = drawLower; drawLower = drawUpper; drawUpper = tmp; tmp = minmax[0]; minmax[0] = minmax[1]; minmax[1] = tmp; } // convert to pixels x = ax[0].p2c(x), y = ax[1].p2c(y), upper = ax[e].p2c(upper); lower = ax[e].p2c(lower); minmax[0] = ax[e].p2c(minmax[0]); minmax[1] = ax[e].p2c(minmax[1]); //same style as points by default var lw = err[e].lineWidth ? err[e].lineWidth : s.points.lineWidth, sw = s.points.shadowSize != null ? s.points.shadowSize : s.shadowSize; //shadow as for points if (lw > 0 && sw > 0) { var w = sw / 2; ctx.lineWidth = w; ctx.strokeStyle = "rgba(0,0,0,0.1)"; drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, w + w/2, minmax); ctx.strokeStyle = "rgba(0,0,0,0.2)"; drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, w/2, minmax); } ctx.strokeStyle = err[e].color? err[e].color: s.color; ctx.lineWidth = lw; //draw it drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, 0, minmax); } } } } function drawError(ctx,err,x,y,upper,lower,drawUpper,drawLower,radius,offset,minmax){ //shadow offset y += offset; upper += offset; lower += offset; // error bar - avoid plotting over circles if (err.err == 'x'){ if (upper > x + radius) drawPath(ctx, [[upper,y],[Math.max(x + radius,minmax[0]),y]]); else drawUpper = false; if (lower < x - radius) drawPath(ctx, [[Math.min(x - radius,minmax[1]),y],[lower,y]] ); else drawLower = false; } else { if (upper < y - radius) drawPath(ctx, [[x,upper],[x,Math.min(y - radius,minmax[0])]] ); else drawUpper = false; if (lower > y + radius) drawPath(ctx, [[x,Math.max(y + radius,minmax[1])],[x,lower]] ); else drawLower = false; } //internal radius value in errorbar, allows to plot radius 0 points and still keep proper sized caps //this is a way to get errorbars on lines without visible connecting dots radius = err.radius != null? err.radius: radius; // upper cap if (drawUpper) { if (err.upperCap == '-'){ if (err.err=='x') drawPath(ctx, [[upper,y - radius],[upper,y + radius]] ); else drawPath(ctx, [[x - radius,upper],[x + radius,upper]] ); } else if ($.isFunction(err.upperCap)){ if (err.err=='x') err.upperCap(ctx, upper, y, radius); else err.upperCap(ctx, x, upper, radius); } } // lower cap if (drawLower) { if (err.lowerCap == '-'){ if (err.err=='x') drawPath(ctx, [[lower,y - radius],[lower,y + radius]] ); else drawPath(ctx, [[x - radius,lower],[x + radius,lower]] ); } else if ($.isFunction(err.lowerCap)){ if (err.err=='x') err.lowerCap(ctx, lower, y, radius); else err.lowerCap(ctx, x, lower, radius); } } } function drawPath(ctx, pts){ ctx.beginPath(); ctx.moveTo(pts[0][0], pts[0][1]); for (var p=1; p < pts.length; p++) ctx.lineTo(pts[p][0], pts[p][1]); ctx.stroke(); } function draw(plot, ctx){ var plotOffset = plot.getPlotOffset(); ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); $.each(plot.getData(), function (i, s) { if (s.points.errorbars && (s.points.xerr.show || s.points.yerr.show)) drawSeriesErrors(plot, ctx, s); }); ctx.restore(); } function init(plot) { plot.hooks.processRawData.push(processRawData); plot.hooks.draw.push(draw); } $.plot.plugins.push({ init: init, options: options, name: 'errorbars', version: '1.0' }); })(jQuery);
JavaScript
/* Javascript plotting library for jQuery, version 0.8.1. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. */ // first an inline dependency, jquery.colorhelpers.js, we inline it here // for convenience /* Plugin for jQuery for working with colors. * * Version 1.1. * * Inspiration from jQuery color animation plugin by John Resig. * * Released under the MIT license by Ole Laursen, October 2009. * * Examples: * * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString() * var c = $.color.extract($("#mydiv"), 'background-color'); * console.log(c.r, c.g, c.b, c.a); * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)" * * Note that .scale() and .add() return the same modified object * instead of making a new one. * * V. 1.1: Fix error handling so e.g. parsing an empty string does * produce a color rather than just crashing. */ (function(B){B.color={};B.color.make=function(F,E,C,D){var G={};G.r=F||0;G.g=E||0;G.b=C||0;G.a=D!=null?D:1;G.add=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]+=I}return G.normalize()};G.scale=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]*=I}return G.normalize()};G.toString=function(){if(G.a>=1){return"rgb("+[G.r,G.g,G.b].join(",")+")"}else{return"rgba("+[G.r,G.g,G.b,G.a].join(",")+")"}};G.normalize=function(){function H(J,K,I){return K<J?J:(K>I?I:K)}G.r=H(0,parseInt(G.r),255);G.g=H(0,parseInt(G.g),255);G.b=H(0,parseInt(G.b),255);G.a=H(0,G.a,1);return G};G.clone=function(){return B.color.make(G.r,G.b,G.g,G.a)};return G.normalize()};B.color.extract=function(D,C){var E;do{E=D.css(C).toLowerCase();if(E!=""&&E!="transparent"){break}D=D.parent()}while(!B.nodeName(D.get(0),"body"));if(E=="rgba(0, 0, 0, 0)"){E="transparent"}return B.color.parse(E)};B.color.parse=function(F){var E,C=B.color.make;if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10))}if(E=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10),parseFloat(E[4]))}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55)}if(E=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55,parseFloat(E[4]))}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return C(parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16))}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return C(parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16))}var D=B.trim(F).toLowerCase();if(D=="transparent"){return C(255,255,255,0)}else{E=A[D]||[0,0,0];return C(E[0],E[1],E[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery); // the actual Flot code (function($) { // Cache the prototype hasOwnProperty for faster access var hasOwnProperty = Object.prototype.hasOwnProperty; /////////////////////////////////////////////////////////////////////////// // The Canvas object is a wrapper around an HTML5 <canvas> tag. // // @constructor // @param {string} cls List of classes to apply to the canvas. // @param {element} container Element onto which to append the canvas. // // Requiring a container is a little iffy, but unfortunately canvas // operations don't work unless the canvas is attached to the DOM. function Canvas(cls, container) { var element = container.children("." + cls)[0]; if (element == null) { element = document.createElement("canvas"); element.className = cls; $(element).css({ direction: "ltr", position: "absolute", left: 0, top: 0 }) .appendTo(container); // If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas if (!element.getContext) { if (window.G_vmlCanvasManager) { element = window.G_vmlCanvasManager.initElement(element); } else { throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode."); } } } this.element = element; var context = this.context = element.getContext("2d"); // Determine the screen's ratio of physical to device-independent // pixels. This is the ratio between the canvas width that the browser // advertises and the number of pixels actually present in that space. // The iPhone 4, for example, has a device-independent width of 320px, // but its screen is actually 640px wide. It therefore has a pixel // ratio of 2, while most normal devices have a ratio of 1. var devicePixelRatio = window.devicePixelRatio || 1, backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; this.pixelRatio = devicePixelRatio / backingStoreRatio; // Size the canvas to match the internal dimensions of its container this.resize(container.width(), container.height()); // Collection of HTML div layers for text overlaid onto the canvas this.textContainer = null; this.text = {}; // Cache of text fragments and metrics, so we can avoid expensively // re-calculating them when the plot is re-rendered in a loop. this._textCache = {}; } // Resizes the canvas to the given dimensions. // // @param {number} width New width of the canvas, in pixels. // @param {number} width New height of the canvas, in pixels. Canvas.prototype.resize = function(width, height) { if (width <= 0 || height <= 0) { throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height); } var element = this.element, context = this.context, pixelRatio = this.pixelRatio; // Resize the canvas, increasing its density based on the display's // pixel ratio; basically giving it more pixels without increasing the // size of its element, to take advantage of the fact that retina // displays have that many more pixels in the same advertised space. // Resizing should reset the state (excanvas seems to be buggy though) if (this.width != width) { element.width = width * pixelRatio; element.style.width = width + "px"; this.width = width; } if (this.height != height) { element.height = height * pixelRatio; element.style.height = height + "px"; this.height = height; } // Save the context, so we can reset in case we get replotted. The // restore ensure that we're really back at the initial state, and // should be safe even if we haven't saved the initial state yet. context.restore(); context.save(); // Scale the coordinate space to match the display density; so even though we // may have twice as many pixels, we still want lines and other drawing to // appear at the same size; the extra pixels will just make them crisper. context.scale(pixelRatio, pixelRatio); }; // Clears the entire canvas area, not including any overlaid HTML text Canvas.prototype.clear = function() { this.context.clearRect(0, 0, this.width, this.height); }; // Finishes rendering the canvas, including managing the text overlay. Canvas.prototype.render = function() { var cache = this._textCache; // For each text layer, add elements marked as active that haven't // already been rendered, and remove those that are no longer active. for (var layerKey in cache) { if (hasOwnProperty.call(cache, layerKey)) { var layer = this.getTextLayer(layerKey), layerCache = cache[layerKey]; layer.hide(); for (var styleKey in layerCache) { if (hasOwnProperty.call(layerCache, styleKey)) { var styleCache = layerCache[styleKey]; for (var key in styleCache) { if (hasOwnProperty.call(styleCache, key)) { var positions = styleCache[key].positions; for (var i = 0, position; position = positions[i]; i++) { if (position.active) { if (!position.rendered) { layer.append(position.element); position.rendered = true; } } else { positions.splice(i--, 1); if (position.rendered) { position.element.detach(); } } } if (positions.length == 0) { delete styleCache[key]; } } } } } layer.show(); } } }; // Creates (if necessary) and returns the text overlay container. // // @param {string} classes String of space-separated CSS classes used to // uniquely identify the text layer. // @return {object} The jQuery-wrapped text-layer div. Canvas.prototype.getTextLayer = function(classes) { var layer = this.text[classes]; // Create the text layer if it doesn't exist if (layer == null) { // Create the text layer container, if it doesn't exist if (this.textContainer == null) { this.textContainer = $("<div class='flot-text'></div>") .css({ position: "absolute", top: 0, left: 0, bottom: 0, right: 0, 'font-size': "smaller", color: "#545454" }) .insertAfter(this.element); } layer = this.text[classes] = $("<div></div>") .addClass(classes) .css({ position: "absolute", top: 0, left: 0, bottom: 0, right: 0 }) .appendTo(this.textContainer); } return layer; }; // Creates (if necessary) and returns a text info object. // // The object looks like this: // // { // width: Width of the text's wrapper div. // height: Height of the text's wrapper div. // element: The jQuery-wrapped HTML div containing the text. // positions: Array of positions at which this text is drawn. // } // // The positions array contains objects that look like this: // // { // active: Flag indicating whether the text should be visible. // rendered: Flag indicating whether the text is currently visible. // element: The jQuery-wrapped HTML div containing the text. // x: X coordinate at which to draw the text. // y: Y coordinate at which to draw the text. // } // // Each position after the first receives a clone of the original element. // // The idea is that that the width, height, and general 'identity' of the // text is constant no matter where it is placed; the placements are a // secondary property. // // Canvas maintains a cache of recently-used text info objects; getTextInfo // either returns the cached element or creates a new entry. // // @param {string} layer A string of space-separated CSS classes uniquely // identifying the layer containing this text. // @param {string} text Text string to retrieve info for. // @param {(string|object)=} font Either a string of space-separated CSS // classes or a font-spec object, defining the text's font and style. // @param {number=} angle Angle at which to rotate the text, in degrees. // Angle is currently unused, it will be implemented in the future. // @param {number=} width Maximum width of the text before it wraps. // @return {object} a text info object. Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) { var textStyle, layerCache, styleCache, info; // Cast the value to a string, in case we were given a number or such text = "" + text; // If the font is a font-spec object, generate a CSS font definition if (typeof font === "object") { textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family; } else { textStyle = font; } // Retrieve (or create) the cache for the text's layer and styles layerCache = this._textCache[layer]; if (layerCache == null) { layerCache = this._textCache[layer] = {}; } styleCache = layerCache[textStyle]; if (styleCache == null) { styleCache = layerCache[textStyle] = {}; } info = styleCache[text]; // If we can't find a matching element in our cache, create a new one if (info == null) { var element = $("<div></div>").html(text) .css({ position: "absolute", 'max-width': width, top: -9999 }) .appendTo(this.getTextLayer(layer)); if (typeof font === "object") { element.css({ font: textStyle, color: font.color }); } else if (typeof font === "string") { element.addClass(font); } info = styleCache[text] = { width: element.outerWidth(true), height: element.outerHeight(true), element: element, positions: [] }; element.detach(); } return info; }; // Adds a text string to the canvas text overlay. // // The text isn't drawn immediately; it is marked as rendering, which will // result in its addition to the canvas on the next render pass. // // @param {string} layer A string of space-separated CSS classes uniquely // identifying the layer containing this text. // @param {number} x X coordinate at which to draw the text. // @param {number} y Y coordinate at which to draw the text. // @param {string} text Text string to draw. // @param {(string|object)=} font Either a string of space-separated CSS // classes or a font-spec object, defining the text's font and style. // @param {number=} angle Angle at which to rotate the text, in degrees. // Angle is currently unused, it will be implemented in the future. // @param {number=} width Maximum width of the text before it wraps. // @param {string=} halign Horizontal alignment of the text; either "left", // "center" or "right". // @param {string=} valign Vertical alignment of the text; either "top", // "middle" or "bottom". Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) { var info = this.getTextInfo(layer, text, font, angle, width), positions = info.positions; // Tweak the div's position to match the text's alignment if (halign == "center") { x -= info.width / 2; } else if (halign == "right") { x -= info.width; } if (valign == "middle") { y -= info.height / 2; } else if (valign == "bottom") { y -= info.height; } // Determine whether this text already exists at this position. // If so, mark it for inclusion in the next render pass. for (var i = 0, position; position = positions[i]; i++) { if (position.x == x && position.y == y) { position.active = true; return; } } // If the text doesn't exist at this position, create a new entry // For the very first position we'll re-use the original element, // while for subsequent ones we'll clone it. position = { active: true, rendered: false, element: positions.length ? info.element.clone() : info.element, x: x, y: y } positions.push(position); // Move the element to its final position within the container position.element.css({ top: Math.round(y), left: Math.round(x), 'text-align': halign // In case the text wraps }); }; // Removes one or more text strings from the canvas text overlay. // // If no parameters are given, all text within the layer is removed. // // Note that the text is not immediately removed; it is simply marked as // inactive, which will result in its removal on the next render pass. // This avoids the performance penalty for 'clear and redraw' behavior, // where we potentially get rid of all text on a layer, but will likely // add back most or all of it later, as when redrawing axes, for example. // // @param {string} layer A string of space-separated CSS classes uniquely // identifying the layer containing this text. // @param {number=} x X coordinate of the text. // @param {number=} y Y coordinate of the text. // @param {string=} text Text string to remove. // @param {(string|object)=} font Either a string of space-separated CSS // classes or a font-spec object, defining the text's font and style. // @param {number=} angle Angle at which the text is rotated, in degrees. // Angle is currently unused, it will be implemented in the future. Canvas.prototype.removeText = function(layer, x, y, text, font, angle) { if (text == null) { var layerCache = this._textCache[layer]; if (layerCache != null) { for (var styleKey in layerCache) { if (hasOwnProperty.call(layerCache, styleKey)) { var styleCache = layerCache[styleKey]; for (var key in styleCache) { if (hasOwnProperty.call(styleCache, key)) { var positions = styleCache[key].positions; for (var i = 0, position; position = positions[i]; i++) { position.active = false; } } } } } } } else { var positions = this.getTextInfo(layer, text, font, angle).positions; for (var i = 0, position; position = positions[i]; i++) { if (position.x == x && position.y == y) { position.active = false; } } } }; /////////////////////////////////////////////////////////////////////////// // The top-level container for the entire plot. function Plot(placeholder, data_, options_, plugins) { // data is on the form: // [ series1, series2 ... ] // where series is either just the data as [ [x1, y1], [x2, y2], ... ] // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... } var series = [], options = { // the color theme used for graphs colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"], legend: { show: true, noColumns: 1, // number of colums in legend table labelFormatter: null, // fn: string -> string labelBoxBorderColor: "#ccc", // border color for the little label boxes container: null, // container (as jQuery object) to put legend in, null means default on top of graph position: "ne", // position of default legend container within plot margin: 5, // distance from grid edge to default legend container within plot backgroundColor: null, // null means auto-detect backgroundOpacity: 0.85, // set to 0 to avoid background sorted: null // default to no legend sorting }, xaxis: { show: null, // null = auto-detect, true = always, false = never position: "bottom", // or "top" mode: null, // null or "time" font: null, // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" } color: null, // base color, labels, ticks tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)" transform: null, // null or f: number -> number to transform axis inverseTransform: null, // if transform is set, this should be the inverse function min: null, // min. value to show, null means set automatically max: null, // max. value to show, null means set automatically autoscaleMargin: null, // margin in % to add if auto-setting min/max ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks tickFormatter: null, // fn: number -> string labelWidth: null, // size of tick labels in pixels labelHeight: null, reserveSpace: null, // whether to reserve space even if axis isn't shown tickLength: null, // size in pixels of ticks, or "full" for whole line alignTicksWithAxis: null, // axis number or null for no sync tickDecimals: null, // no. of decimals, null means auto tickSize: null, // number or [number, "unit"] minTickSize: null // number or [number, "unit"] }, yaxis: { autoscaleMargin: 0.02, position: "left" // or "right" }, xaxes: [], yaxes: [], series: { points: { show: false, radius: 3, lineWidth: 2, // in pixels fill: true, fillColor: "#ffffff", symbol: "circle" // or callback }, lines: { // we don't put in show: false so we can see // whether lines were actively disabled lineWidth: 2, // in pixels fill: false, fillColor: null, steps: false // Omit 'zero', so we can later default its value to // match that of the 'fill' option. }, bars: { show: false, lineWidth: 2, // in pixels barWidth: 1, // in units of the x axis fill: true, fillColor: null, align: "left", // "left", "right", or "center" horizontal: false, zero: true }, shadowSize: 3, highlightColor: null }, grid: { show: true, aboveData: false, color: "#545454", // primary color used for outline and labels backgroundColor: null, // null for transparent, else color borderColor: null, // set if different from the grid color tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)" margin: 0, // distance from the canvas edge to the grid labelMargin: 5, // in pixels axisMargin: 8, // in pixels borderWidth: 2, // in pixels minBorderMargin: null, // in pixels, null means taken from points radius markings: null, // array of ranges or fn: axes -> array of ranges markingsColor: "#f4f4f4", markingsLineWidth: 2, // interactive stuff clickable: false, hoverable: false, autoHighlight: true, // highlight in case mouse is near mouseActiveRadius: 10 // how far the mouse can be away to activate an item }, interaction: { redrawOverlayInterval: 1000/60 // time between updates, -1 means in same flow }, hooks: {} }, surface = null, // the canvas for the plot itself overlay = null, // canvas for interactive stuff on top of plot eventHolder = null, // jQuery object that events should be bound to ctx = null, octx = null, xaxes = [], yaxes = [], plotOffset = { left: 0, right: 0, top: 0, bottom: 0}, plotWidth = 0, plotHeight = 0, hooks = { processOptions: [], processRawData: [], processDatapoints: [], processOffset: [], drawBackground: [], drawSeries: [], draw: [], bindEvents: [], drawOverlay: [], shutdown: [] }, plot = this; // public functions plot.setData = setData; plot.setupGrid = setupGrid; plot.draw = draw; plot.getPlaceholder = function() { return placeholder; }; plot.getCanvas = function() { return surface.element; }; plot.getPlotOffset = function() { return plotOffset; }; plot.width = function () { return plotWidth; }; plot.height = function () { return plotHeight; }; plot.offset = function () { var o = eventHolder.offset(); o.left += plotOffset.left; o.top += plotOffset.top; return o; }; plot.getData = function () { return series; }; plot.getAxes = function () { var res = {}, i; $.each(xaxes.concat(yaxes), function (_, axis) { if (axis) res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis; }); return res; }; plot.getXAxes = function () { return xaxes; }; plot.getYAxes = function () { return yaxes; }; plot.c2p = canvasToAxisCoords; plot.p2c = axisToCanvasCoords; plot.getOptions = function () { return options; }; plot.highlight = highlight; plot.unhighlight = unhighlight; plot.triggerRedrawOverlay = triggerRedrawOverlay; plot.pointOffset = function(point) { return { left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10), top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10) }; }; plot.shutdown = shutdown; plot.resize = function () { var width = placeholder.width(), height = placeholder.height(); surface.resize(width, height); overlay.resize(width, height); }; // public attributes plot.hooks = hooks; // initialize initPlugins(plot); parseOptions(options_); setupCanvases(); setData(data_); setupGrid(); draw(); bindEvents(); function executeHooks(hook, args) { args = [plot].concat(args); for (var i = 0; i < hook.length; ++i) hook[i].apply(this, args); } function initPlugins() { // References to key classes, allowing plugins to modify them var classes = { Canvas: Canvas }; for (var i = 0; i < plugins.length; ++i) { var p = plugins[i]; p.init(plot, classes); if (p.options) $.extend(true, options, p.options); } } function parseOptions(opts) { $.extend(true, options, opts); // $.extend merges arrays, rather than replacing them. When less // colors are provided than the size of the default palette, we // end up with those colors plus the remaining defaults, which is // not expected behavior; avoid it by replacing them here. if (opts && opts.colors) { options.colors = opts.colors; } if (options.xaxis.color == null) options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString(); if (options.yaxis.color == null) options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString(); if (options.xaxis.tickColor == null) // grid.tickColor for back-compatibility options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color; if (options.yaxis.tickColor == null) // grid.tickColor for back-compatibility options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color; if (options.grid.borderColor == null) options.grid.borderColor = options.grid.color; if (options.grid.tickColor == null) options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString(); // Fill in defaults for axis options, including any unspecified // font-spec fields, if a font-spec was provided. // If no x/y axis options were provided, create one of each anyway, // since the rest of the code assumes that they exist. var i, axisOptions, axisCount, fontDefaults = { style: placeholder.css("font-style"), size: Math.round(0.8 * (+placeholder.css("font-size").replace("px", "") || 13)), variant: placeholder.css("font-variant"), weight: placeholder.css("font-weight"), family: placeholder.css("font-family") }; fontDefaults.lineHeight = fontDefaults.size * 1.15; axisCount = options.xaxes.length || 1; for (i = 0; i < axisCount; ++i) { axisOptions = options.xaxes[i]; if (axisOptions && !axisOptions.tickColor) { axisOptions.tickColor = axisOptions.color; } axisOptions = $.extend(true, {}, options.xaxis, axisOptions); options.xaxes[i] = axisOptions; if (axisOptions.font) { axisOptions.font = $.extend({}, fontDefaults, axisOptions.font); if (!axisOptions.font.color) { axisOptions.font.color = axisOptions.color; } } } axisCount = options.yaxes.length || 1; for (i = 0; i < axisCount; ++i) { axisOptions = options.yaxes[i]; if (axisOptions && !axisOptions.tickColor) { axisOptions.tickColor = axisOptions.color; } axisOptions = $.extend(true, {}, options.yaxis, axisOptions); options.yaxes[i] = axisOptions; if (axisOptions.font) { axisOptions.font = $.extend({}, fontDefaults, axisOptions.font); if (!axisOptions.font.color) { axisOptions.font.color = axisOptions.color; } } } // backwards compatibility, to be removed in future if (options.xaxis.noTicks && options.xaxis.ticks == null) options.xaxis.ticks = options.xaxis.noTicks; if (options.yaxis.noTicks && options.yaxis.ticks == null) options.yaxis.ticks = options.yaxis.noTicks; if (options.x2axis) { options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis); options.xaxes[1].position = "top"; } if (options.y2axis) { options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis); options.yaxes[1].position = "right"; } if (options.grid.coloredAreas) options.grid.markings = options.grid.coloredAreas; if (options.grid.coloredAreasColor) options.grid.markingsColor = options.grid.coloredAreasColor; if (options.lines) $.extend(true, options.series.lines, options.lines); if (options.points) $.extend(true, options.series.points, options.points); if (options.bars) $.extend(true, options.series.bars, options.bars); if (options.shadowSize != null) options.series.shadowSize = options.shadowSize; if (options.highlightColor != null) options.series.highlightColor = options.highlightColor; // save options on axes for future reference for (i = 0; i < options.xaxes.length; ++i) getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i]; for (i = 0; i < options.yaxes.length; ++i) getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i]; // add hooks from options for (var n in hooks) if (options.hooks[n] && options.hooks[n].length) hooks[n] = hooks[n].concat(options.hooks[n]); executeHooks(hooks.processOptions, [options]); } function setData(d) { series = parseData(d); fillInSeriesOptions(); processData(); } function parseData(d) { var res = []; for (var i = 0; i < d.length; ++i) { var s = $.extend(true, {}, options.series); if (d[i].data != null) { s.data = d[i].data; // move the data instead of deep-copy delete d[i].data; $.extend(true, s, d[i]); d[i].data = s.data; } else s.data = d[i]; res.push(s); } return res; } function axisNumber(obj, coord) { var a = obj[coord + "axis"]; if (typeof a == "object") // if we got a real axis, extract number a = a.n; if (typeof a != "number") a = 1; // default to first axis return a; } function allAxes() { // return flat array without annoying null entries return $.grep(xaxes.concat(yaxes), function (a) { return a; }); } function canvasToAxisCoords(pos) { // return an object with x/y corresponding to all used axes var res = {}, i, axis; for (i = 0; i < xaxes.length; ++i) { axis = xaxes[i]; if (axis && axis.used) res["x" + axis.n] = axis.c2p(pos.left); } for (i = 0; i < yaxes.length; ++i) { axis = yaxes[i]; if (axis && axis.used) res["y" + axis.n] = axis.c2p(pos.top); } if (res.x1 !== undefined) res.x = res.x1; if (res.y1 !== undefined) res.y = res.y1; return res; } function axisToCanvasCoords(pos) { // get canvas coords from the first pair of x/y found in pos var res = {}, i, axis, key; for (i = 0; i < xaxes.length; ++i) { axis = xaxes[i]; if (axis && axis.used) { key = "x" + axis.n; if (pos[key] == null && axis.n == 1) key = "x"; if (pos[key] != null) { res.left = axis.p2c(pos[key]); break; } } } for (i = 0; i < yaxes.length; ++i) { axis = yaxes[i]; if (axis && axis.used) { key = "y" + axis.n; if (pos[key] == null && axis.n == 1) key = "y"; if (pos[key] != null) { res.top = axis.p2c(pos[key]); break; } } } return res; } function getOrCreateAxis(axes, number) { if (!axes[number - 1]) axes[number - 1] = { n: number, // save the number for future reference direction: axes == xaxes ? "x" : "y", options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis) }; return axes[number - 1]; } function fillInSeriesOptions() { var neededColors = series.length, maxIndex = -1, i; // Subtract the number of series that already have fixed colors or // color indexes from the number that we still need to generate. for (i = 0; i < series.length; ++i) { var sc = series[i].color; if (sc != null) { neededColors--; if (typeof sc == "number" && sc > maxIndex) { maxIndex = sc; } } } // If any of the series have fixed color indexes, then we need to // generate at least as many colors as the highest index. if (neededColors <= maxIndex) { neededColors = maxIndex + 1; } // Generate all the colors, using first the option colors and then // variations on those colors once they're exhausted. var c, colors = [], colorPool = options.colors, colorPoolSize = colorPool.length, variation = 0; for (i = 0; i < neededColors; i++) { c = $.color.parse(colorPool[i % colorPoolSize] || "#666"); // Each time we exhaust the colors in the pool we adjust // a scaling factor used to produce more variations on // those colors. The factor alternates negative/positive // to produce lighter/darker colors. // Reset the variation after every few cycles, or else // it will end up producing only white or black colors. if (i % colorPoolSize == 0 && i) { if (variation >= 0) { if (variation < 0.5) { variation = -variation - 0.2; } else variation = 0; } else variation = -variation; } colors[i] = c.scale('rgb', 1 + variation); } // Finalize the series options, filling in their colors var colori = 0, s; for (i = 0; i < series.length; ++i) { s = series[i]; // assign colors if (s.color == null) { s.color = colors[colori].toString(); ++colori; } else if (typeof s.color == "number") s.color = colors[s.color].toString(); // turn on lines automatically in case nothing is set if (s.lines.show == null) { var v, show = true; for (v in s) if (s[v] && s[v].show) { show = false; break; } if (show) s.lines.show = true; } // If nothing was provided for lines.zero, default it to match // lines.fill, since areas by default should extend to zero. if (s.lines.zero == null) { s.lines.zero = !!s.lines.fill; } // setup axes s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x")); s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y")); } } function processData() { var topSentry = Number.POSITIVE_INFINITY, bottomSentry = Number.NEGATIVE_INFINITY, fakeInfinity = Number.MAX_VALUE, i, j, k, m, length, s, points, ps, x, y, axis, val, f, p, data, format; function updateAxis(axis, min, max) { if (min < axis.datamin && min != -fakeInfinity) axis.datamin = min; if (max > axis.datamax && max != fakeInfinity) axis.datamax = max; } $.each(allAxes(), function (_, axis) { // init axis axis.datamin = topSentry; axis.datamax = bottomSentry; axis.used = false; }); for (i = 0; i < series.length; ++i) { s = series[i]; s.datapoints = { points: [] }; executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]); } // first pass: clean and copy data for (i = 0; i < series.length; ++i) { s = series[i]; data = s.data; format = s.datapoints.format; if (!format) { format = []; // find out how to copy format.push({ x: true, number: true, required: true }); format.push({ y: true, number: true, required: true }); if (s.bars.show || (s.lines.show && s.lines.fill)) { var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero)); format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale }); if (s.bars.horizontal) { delete format[format.length - 1].y; format[format.length - 1].x = true; } } s.datapoints.format = format; } if (s.datapoints.pointsize != null) continue; // already filled in s.datapoints.pointsize = format.length; ps = s.datapoints.pointsize; points = s.datapoints.points; var insertSteps = s.lines.show && s.lines.steps; s.xaxis.used = s.yaxis.used = true; for (j = k = 0; j < data.length; ++j, k += ps) { p = data[j]; var nullify = p == null; if (!nullify) { for (m = 0; m < ps; ++m) { val = p[m]; f = format[m]; if (f) { if (f.number && val != null) { val = +val; // convert to number if (isNaN(val)) val = null; else if (val == Infinity) val = fakeInfinity; else if (val == -Infinity) val = -fakeInfinity; } if (val == null) { if (f.required) nullify = true; if (f.defaultValue != null) val = f.defaultValue; } } points[k + m] = val; } } if (nullify) { for (m = 0; m < ps; ++m) { val = points[k + m]; if (val != null) { f = format[m]; // extract min/max info if (f.autoscale) { if (f.x) { updateAxis(s.xaxis, val, val); } if (f.y) { updateAxis(s.yaxis, val, val); } } } points[k + m] = null; } } else { // a little bit of line specific stuff that // perhaps shouldn't be here, but lacking // better means... if (insertSteps && k > 0 && points[k - ps] != null && points[k - ps] != points[k] && points[k - ps + 1] != points[k + 1]) { // copy the point to make room for a middle point for (m = 0; m < ps; ++m) points[k + ps + m] = points[k + m]; // middle point has same y points[k + 1] = points[k - ps + 1]; // we've added a point, better reflect that k += ps; } } } } // give the hooks a chance to run for (i = 0; i < series.length; ++i) { s = series[i]; executeHooks(hooks.processDatapoints, [ s, s.datapoints]); } // second pass: find datamax/datamin for auto-scaling for (i = 0; i < series.length; ++i) { s = series[i]; points = s.datapoints.points; ps = s.datapoints.pointsize; format = s.datapoints.format; var xmin = topSentry, ymin = topSentry, xmax = bottomSentry, ymax = bottomSentry; for (j = 0; j < points.length; j += ps) { if (points[j] == null) continue; for (m = 0; m < ps; ++m) { val = points[j + m]; f = format[m]; if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity) continue; if (f.x) { if (val < xmin) xmin = val; if (val > xmax) xmax = val; } if (f.y) { if (val < ymin) ymin = val; if (val > ymax) ymax = val; } } } if (s.bars.show) { // make sure we got room for the bar on the dancing floor var delta; switch (s.bars.align) { case "left": delta = 0; break; case "right": delta = -s.bars.barWidth; break; case "center": delta = -s.bars.barWidth / 2; break; default: throw new Error("Invalid bar alignment: " + s.bars.align); } if (s.bars.horizontal) { ymin += delta; ymax += delta + s.bars.barWidth; } else { xmin += delta; xmax += delta + s.bars.barWidth; } } updateAxis(s.xaxis, xmin, xmax); updateAxis(s.yaxis, ymin, ymax); } $.each(allAxes(), function (_, axis) { if (axis.datamin == topSentry) axis.datamin = null; if (axis.datamax == bottomSentry) axis.datamax = null; }); } function setupCanvases() { // Make sure the placeholder is clear of everything except canvases // from a previous plot in this container that we'll try to re-use. placeholder.css("padding", 0) // padding messes up the positioning .children(":not(.flot-base,.flot-overlay)").remove(); if (placeholder.css("position") == 'static') placeholder.css("position", "relative"); // for positioning labels and overlay surface = new Canvas("flot-base", placeholder); overlay = new Canvas("flot-overlay", placeholder); // overlay canvas for interactive features ctx = surface.context; octx = overlay.context; // define which element we're listening for events on eventHolder = $(overlay.element).unbind(); // If we're re-using a plot object, shut down the old one var existing = placeholder.data("plot"); if (existing) { existing.shutdown(); overlay.clear(); } // save in case we get replotted placeholder.data("plot", plot); } function bindEvents() { // bind events if (options.grid.hoverable) { eventHolder.mousemove(onMouseMove); // Use bind, rather than .mouseleave, because we officially // still support jQuery 1.2.6, which doesn't define a shortcut // for mouseenter or mouseleave. This was a bug/oversight that // was fixed somewhere around 1.3.x. We can return to using // .mouseleave when we drop support for 1.2.6. eventHolder.bind("mouseleave", onMouseLeave); } if (options.grid.clickable) eventHolder.click(onClick); executeHooks(hooks.bindEvents, [eventHolder]); } function shutdown() { if (redrawTimeout) clearTimeout(redrawTimeout); eventHolder.unbind("mousemove", onMouseMove); eventHolder.unbind("mouseleave", onMouseLeave); eventHolder.unbind("click", onClick); executeHooks(hooks.shutdown, [eventHolder]); } function setTransformationHelpers(axis) { // set helper functions on the axis, assumes plot area // has been computed already function identity(x) { return x; } var s, m, t = axis.options.transform || identity, it = axis.options.inverseTransform; // precompute how much the axis is scaling a point // in canvas space if (axis.direction == "x") { s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min)); m = Math.min(t(axis.max), t(axis.min)); } else { s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min)); s = -s; m = Math.max(t(axis.max), t(axis.min)); } // data point to canvas coordinate if (t == identity) // slight optimization axis.p2c = function (p) { return (p - m) * s; }; else axis.p2c = function (p) { return (t(p) - m) * s; }; // canvas coordinate to data point if (!it) axis.c2p = function (c) { return m + c / s; }; else axis.c2p = function (c) { return it(m + c / s); }; } function measureTickLabels(axis) { var opts = axis.options, ticks = axis.ticks || [], labelWidth = opts.labelWidth || 0, labelHeight = opts.labelHeight || 0, maxWidth = labelWidth || axis.direction == "x" ? Math.floor(surface.width / (ticks.length || 1)) : null; legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis", layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles, font = opts.font || "flot-tick-label tickLabel"; for (var i = 0; i < ticks.length; ++i) { var t = ticks[i]; if (!t.label) continue; var info = surface.getTextInfo(layer, t.label, font, null, maxWidth); labelWidth = Math.max(labelWidth, info.width); labelHeight = Math.max(labelHeight, info.height); } axis.labelWidth = opts.labelWidth || labelWidth; axis.labelHeight = opts.labelHeight || labelHeight; } function allocateAxisBoxFirstPhase(axis) { // find the bounding box of the axis by looking at label // widths/heights and ticks, make room by diminishing the // plotOffset; this first phase only looks at one // dimension per axis, the other dimension depends on the // other axes so will have to wait var lw = axis.labelWidth, lh = axis.labelHeight, pos = axis.options.position, tickLength = axis.options.tickLength, axisMargin = options.grid.axisMargin, padding = options.grid.labelMargin, all = axis.direction == "x" ? xaxes : yaxes, index, innermost; // determine axis margin var samePosition = $.grep(all, function (a) { return a && a.options.position == pos && a.reserveSpace; }); if ($.inArray(axis, samePosition) == samePosition.length - 1) axisMargin = 0; // outermost // determine tick length - if we're innermost, we can use "full" if (tickLength == null) { var sameDirection = $.grep(all, function (a) { return a && a.reserveSpace; }); innermost = $.inArray(axis, sameDirection) == 0; if (innermost) tickLength = "full"; else tickLength = 5; } if (!isNaN(+tickLength)) padding += +tickLength; // compute box if (axis.direction == "x") { lh += padding; if (pos == "bottom") { plotOffset.bottom += lh + axisMargin; axis.box = { top: surface.height - plotOffset.bottom, height: lh }; } else { axis.box = { top: plotOffset.top + axisMargin, height: lh }; plotOffset.top += lh + axisMargin; } } else { lw += padding; if (pos == "left") { axis.box = { left: plotOffset.left + axisMargin, width: lw }; plotOffset.left += lw + axisMargin; } else { plotOffset.right += lw + axisMargin; axis.box = { left: surface.width - plotOffset.right, width: lw }; } } // save for future reference axis.position = pos; axis.tickLength = tickLength; axis.box.padding = padding; axis.innermost = innermost; } function allocateAxisBoxSecondPhase(axis) { // now that all axis boxes have been placed in one // dimension, we can set the remaining dimension coordinates if (axis.direction == "x") { axis.box.left = plotOffset.left - axis.labelWidth / 2; axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth; } else { axis.box.top = plotOffset.top - axis.labelHeight / 2; axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight; } } function adjustLayoutForThingsStickingOut() { // possibly adjust plot offset to ensure everything stays // inside the canvas and isn't clipped off var minMargin = options.grid.minBorderMargin, margins = { x: 0, y: 0 }, i, axis; // check stuff from the plot (FIXME: this should just read // a value from the series, otherwise it's impossible to // customize) if (minMargin == null) { minMargin = 0; for (i = 0; i < series.length; ++i) minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth/2)); } margins.x = margins.y = Math.ceil(minMargin); // check axis labels, note we don't check the actual // labels but instead use the overall width/height to not // jump as much around with replots $.each(allAxes(), function (_, axis) { var dir = axis.direction; if (axis.reserveSpace) margins[dir] = Math.ceil(Math.max(margins[dir], (dir == "x" ? axis.labelWidth : axis.labelHeight) / 2)); }); plotOffset.left = Math.max(margins.x, plotOffset.left); plotOffset.right = Math.max(margins.x, plotOffset.right); plotOffset.top = Math.max(margins.y, plotOffset.top); plotOffset.bottom = Math.max(margins.y, plotOffset.bottom); } function setupGrid() { var i, axes = allAxes(), showGrid = options.grid.show; // Initialize the plot's offset from the edge of the canvas for (var a in plotOffset) { var margin = options.grid.margin || 0; plotOffset[a] = typeof margin == "number" ? margin : margin[a] || 0; } executeHooks(hooks.processOffset, [plotOffset]); // If the grid is visible, add its border width to the offset for (var a in plotOffset) { if(typeof(options.grid.borderWidth) == "object") { plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0; } else { plotOffset[a] += showGrid ? options.grid.borderWidth : 0; } } // init axes $.each(axes, function (_, axis) { axis.show = axis.options.show; if (axis.show == null) axis.show = axis.used; // by default an axis is visible if it's got data axis.reserveSpace = axis.show || axis.options.reserveSpace; setRange(axis); }); if (showGrid) { var allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; }); $.each(allocatedAxes, function (_, axis) { // make the ticks setupTickGeneration(axis); setTicks(axis); snapRangeToTicks(axis, axis.ticks); // find labelWidth/Height for axis measureTickLabels(axis); }); // with all dimensions calculated, we can compute the // axis bounding boxes, start from the outside // (reverse order) for (i = allocatedAxes.length - 1; i >= 0; --i) allocateAxisBoxFirstPhase(allocatedAxes[i]); // make sure we've got enough space for things that // might stick out adjustLayoutForThingsStickingOut(); $.each(allocatedAxes, function (_, axis) { allocateAxisBoxSecondPhase(axis); }); } plotWidth = surface.width - plotOffset.left - plotOffset.right; plotHeight = surface.height - plotOffset.bottom - plotOffset.top; // now we got the proper plot dimensions, we can compute the scaling $.each(axes, function (_, axis) { setTransformationHelpers(axis); }); if (showGrid) { drawAxisLabels(); } insertLegend(); } function setRange(axis) { var opts = axis.options, min = +(opts.min != null ? opts.min : axis.datamin), max = +(opts.max != null ? opts.max : axis.datamax), delta = max - min; if (delta == 0.0) { // degenerate case var widen = max == 0 ? 1 : 0.01; if (opts.min == null) min -= widen; // always widen max if we couldn't widen min to ensure we // don't fall into min == max which doesn't work if (opts.max == null || opts.min != null) max += widen; } else { // consider autoscaling var margin = opts.autoscaleMargin; if (margin != null) { if (opts.min == null) { min -= delta * margin; // make sure we don't go below zero if all values // are positive if (min < 0 && axis.datamin != null && axis.datamin >= 0) min = 0; } if (opts.max == null) { max += delta * margin; if (max > 0 && axis.datamax != null && axis.datamax <= 0) max = 0; } } } axis.min = min; axis.max = max; } function setupTickGeneration(axis) { var opts = axis.options; // estimate number of ticks var noTicks; if (typeof opts.ticks == "number" && opts.ticks > 0) noTicks = opts.ticks; else // heuristic based on the model a*sqrt(x) fitted to // some data points that seemed reasonable noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? surface.width : surface.height); var delta = (axis.max - axis.min) / noTicks, dec = -Math.floor(Math.log(delta) / Math.LN10), maxDec = opts.tickDecimals; if (maxDec != null && dec > maxDec) { dec = maxDec; } var magn = Math.pow(10, -dec), norm = delta / magn, // norm is between 1.0 and 10.0 size; if (norm < 1.5) { size = 1; } else if (norm < 3) { size = 2; // special case for 2.5, requires an extra decimal if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) { size = 2.5; ++dec; } } else if (norm < 7.5) { size = 5; } else { size = 10; } size *= magn; if (opts.minTickSize != null && size < opts.minTickSize) { size = opts.minTickSize; } axis.delta = delta; axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec); axis.tickSize = opts.tickSize || size; // Time mode was moved to a plug-in in 0.8, but since so many people use this // we'll add an especially friendly make sure they remembered to include it. if (opts.mode == "time" && !axis.tickGenerator) { throw new Error("Time mode requires the flot.time plugin."); } // Flot supports base-10 axes; any other mode else is handled by a plug-in, // like flot.time.js. if (!axis.tickGenerator) { axis.tickGenerator = function (axis) { var ticks = [], start = floorInBase(axis.min, axis.tickSize), i = 0, v = Number.NaN, prev; do { prev = v; v = start + i * axis.tickSize; ticks.push(v); ++i; } while (v < axis.max && v != prev); return ticks; }; axis.tickFormatter = function (value, axis) { var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1; var formatted = "" + Math.round(value * factor) / factor; // If tickDecimals was specified, ensure that we have exactly that // much precision; otherwise default to the value's own precision. if (axis.tickDecimals != null) { var decimal = formatted.indexOf("."); var precision = decimal == -1 ? 0 : formatted.length - decimal - 1; if (precision < axis.tickDecimals) { return (precision ? formatted : formatted + ".") + ("" + factor).substr(1, axis.tickDecimals - precision); } } return formatted; }; } if ($.isFunction(opts.tickFormatter)) axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); }; if (opts.alignTicksWithAxis != null) { var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1]; if (otherAxis && otherAxis.used && otherAxis != axis) { // consider snapping min/max to outermost nice ticks var niceTicks = axis.tickGenerator(axis); if (niceTicks.length > 0) { if (opts.min == null) axis.min = Math.min(axis.min, niceTicks[0]); if (opts.max == null && niceTicks.length > 1) axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]); } axis.tickGenerator = function (axis) { // copy ticks, scaled to this axis var ticks = [], v, i; for (i = 0; i < otherAxis.ticks.length; ++i) { v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min); v = axis.min + v * (axis.max - axis.min); ticks.push(v); } return ticks; }; // we might need an extra decimal since forced // ticks don't necessarily fit naturally if (!axis.mode && opts.tickDecimals == null) { var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1), ts = axis.tickGenerator(axis); // only proceed if the tick interval rounded // with an extra decimal doesn't give us a // zero at end if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec)))) axis.tickDecimals = extraDec; } } } } function setTicks(axis) { var oticks = axis.options.ticks, ticks = []; if (oticks == null || (typeof oticks == "number" && oticks > 0)) ticks = axis.tickGenerator(axis); else if (oticks) { if ($.isFunction(oticks)) // generate the ticks ticks = oticks(axis); else ticks = oticks; } // clean up/labelify the supplied ticks, copy them over var i, v; axis.ticks = []; for (i = 0; i < ticks.length; ++i) { var label = null; var t = ticks[i]; if (typeof t == "object") { v = +t[0]; if (t.length > 1) label = t[1]; } else v = +t; if (label == null) label = axis.tickFormatter(v, axis); if (!isNaN(v)) axis.ticks.push({ v: v, label: label }); } } function snapRangeToTicks(axis, ticks) { if (axis.options.autoscaleMargin && ticks.length > 0) { // snap to ticks if (axis.options.min == null) axis.min = Math.min(axis.min, ticks[0].v); if (axis.options.max == null && ticks.length > 1) axis.max = Math.max(axis.max, ticks[ticks.length - 1].v); } } function draw() { surface.clear(); executeHooks(hooks.drawBackground, [ctx]); var grid = options.grid; // draw background, if any if (grid.show && grid.backgroundColor) drawBackground(); if (grid.show && !grid.aboveData) { drawGrid(); } for (var i = 0; i < series.length; ++i) { executeHooks(hooks.drawSeries, [ctx, series[i]]); drawSeries(series[i]); } executeHooks(hooks.draw, [ctx]); if (grid.show && grid.aboveData) { drawGrid(); } surface.render(); // A draw implies that either the axes or data have changed, so we // should probably update the overlay highlights as well. triggerRedrawOverlay(); } function extractRange(ranges, coord) { var axis, from, to, key, axes = allAxes(); for (var i = 0; i < axes.length; ++i) { axis = axes[i]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis if (ranges[key]) { from = ranges[key].from; to = ranges[key].to; break; } } } // backwards-compat stuff - to be removed in future if (!ranges[key]) { axis = coord == "x" ? xaxes[0] : yaxes[0]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) { var tmp = from; from = to; to = tmp; } return { from: from, to: to, axis: axis }; } function drawBackground() { ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)"); ctx.fillRect(0, 0, plotWidth, plotHeight); ctx.restore(); } function drawGrid() { var i, axes, bw, bc; ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); // draw markings var markings = options.grid.markings; if (markings) { if ($.isFunction(markings)) { axes = plot.getAxes(); // xmin etc. is backwards compatibility, to be // removed in the future axes.xmin = axes.xaxis.min; axes.xmax = axes.xaxis.max; axes.ymin = axes.yaxis.min; axes.ymax = axes.yaxis.max; markings = markings(axes); } for (i = 0; i < markings.length; ++i) { var m = markings[i], xrange = extractRange(m, "x"), yrange = extractRange(m, "y"); // fill in missing if (xrange.from == null) xrange.from = xrange.axis.min; if (xrange.to == null) xrange.to = xrange.axis.max; if (yrange.from == null) yrange.from = yrange.axis.min; if (yrange.to == null) yrange.to = yrange.axis.max; // clip if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max || yrange.to < yrange.axis.min || yrange.from > yrange.axis.max) continue; xrange.from = Math.max(xrange.from, xrange.axis.min); xrange.to = Math.min(xrange.to, xrange.axis.max); yrange.from = Math.max(yrange.from, yrange.axis.min); yrange.to = Math.min(yrange.to, yrange.axis.max); if (xrange.from == xrange.to && yrange.from == yrange.to) continue; // then draw xrange.from = xrange.axis.p2c(xrange.from); xrange.to = xrange.axis.p2c(xrange.to); yrange.from = yrange.axis.p2c(yrange.from); yrange.to = yrange.axis.p2c(yrange.to); if (xrange.from == xrange.to || yrange.from == yrange.to) { // draw line ctx.beginPath(); ctx.strokeStyle = m.color || options.grid.markingsColor; ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth; ctx.moveTo(xrange.from, yrange.from); ctx.lineTo(xrange.to, yrange.to); ctx.stroke(); } else { // fill area ctx.fillStyle = m.color || options.grid.markingsColor; ctx.fillRect(xrange.from, yrange.to, xrange.to - xrange.from, yrange.from - yrange.to); } } } // draw the ticks axes = allAxes(); bw = options.grid.borderWidth; for (var j = 0; j < axes.length; ++j) { var axis = axes[j], box = axis.box, t = axis.tickLength, x, y, xoff, yoff; if (!axis.show || axis.ticks.length == 0) continue; ctx.lineWidth = 1; // find the edges if (axis.direction == "x") { x = 0; if (t == "full") y = (axis.position == "top" ? 0 : plotHeight); else y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0); } else { y = 0; if (t == "full") x = (axis.position == "left" ? 0 : plotWidth); else x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0); } // draw tick bar if (!axis.innermost) { ctx.strokeStyle = axis.options.color; ctx.beginPath(); xoff = yoff = 0; if (axis.direction == "x") xoff = plotWidth + 1; else yoff = plotHeight + 1; if (ctx.lineWidth == 1) { if (axis.direction == "x") { y = Math.floor(y) + 0.5; } else { x = Math.floor(x) + 0.5; } } ctx.moveTo(x, y); ctx.lineTo(x + xoff, y + yoff); ctx.stroke(); } // draw ticks ctx.strokeStyle = axis.options.tickColor; ctx.beginPath(); for (i = 0; i < axis.ticks.length; ++i) { var v = axis.ticks[i].v; xoff = yoff = 0; if (isNaN(v) || v < axis.min || v > axis.max // skip those lying on the axes if we got a border || (t == "full" && ((typeof bw == "object" && bw[axis.position] > 0) || bw > 0) && (v == axis.min || v == axis.max))) continue; if (axis.direction == "x") { x = axis.p2c(v); yoff = t == "full" ? -plotHeight : t; if (axis.position == "top") yoff = -yoff; } else { y = axis.p2c(v); xoff = t == "full" ? -plotWidth : t; if (axis.position == "left") xoff = -xoff; } if (ctx.lineWidth == 1) { if (axis.direction == "x") x = Math.floor(x) + 0.5; else y = Math.floor(y) + 0.5; } ctx.moveTo(x, y); ctx.lineTo(x + xoff, y + yoff); } ctx.stroke(); } // draw border if (bw) { // If either borderWidth or borderColor is an object, then draw the border // line by line instead of as one rectangle bc = options.grid.borderColor; if(typeof bw == "object" || typeof bc == "object") { if (typeof bw !== "object") { bw = {top: bw, right: bw, bottom: bw, left: bw}; } if (typeof bc !== "object") { bc = {top: bc, right: bc, bottom: bc, left: bc}; } if (bw.top > 0) { ctx.strokeStyle = bc.top; ctx.lineWidth = bw.top; ctx.beginPath(); ctx.moveTo(0 - bw.left, 0 - bw.top/2); ctx.lineTo(plotWidth, 0 - bw.top/2); ctx.stroke(); } if (bw.right > 0) { ctx.strokeStyle = bc.right; ctx.lineWidth = bw.right; ctx.beginPath(); ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top); ctx.lineTo(plotWidth + bw.right / 2, plotHeight); ctx.stroke(); } if (bw.bottom > 0) { ctx.strokeStyle = bc.bottom; ctx.lineWidth = bw.bottom; ctx.beginPath(); ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2); ctx.lineTo(0, plotHeight + bw.bottom / 2); ctx.stroke(); } if (bw.left > 0) { ctx.strokeStyle = bc.left; ctx.lineWidth = bw.left; ctx.beginPath(); ctx.moveTo(0 - bw.left/2, plotHeight + bw.bottom); ctx.lineTo(0- bw.left/2, 0); ctx.stroke(); } } else { ctx.lineWidth = bw; ctx.strokeStyle = options.grid.borderColor; ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw); } } ctx.restore(); } function drawAxisLabels() { $.each(allAxes(), function (_, axis) { if (!axis.show || axis.ticks.length == 0) return; var box = axis.box, legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis", layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles, font = axis.options.font || "flot-tick-label tickLabel", tick, x, y, halign, valign; surface.removeText(layer); for (var i = 0; i < axis.ticks.length; ++i) { tick = axis.ticks[i]; if (!tick.label || tick.v < axis.min || tick.v > axis.max) continue; if (axis.direction == "x") { halign = "center"; x = plotOffset.left + axis.p2c(tick.v); if (axis.position == "bottom") { y = box.top + box.padding; } else { y = box.top + box.height - box.padding; valign = "bottom"; } } else { valign = "middle"; y = plotOffset.top + axis.p2c(tick.v); if (axis.position == "left") { x = box.left + box.width - box.padding; halign = "right"; } else { x = box.left + box.padding; } } surface.addText(layer, x, y, tick.label, font, null, null, halign, valign); } }); } function drawSeries(series) { if (series.lines.show) drawSeriesLines(series); if (series.bars.show) drawSeriesBars(series); if (series.points.show) drawSeriesPoints(series); } function drawSeriesLines(series) { function plotLine(datapoints, xoffset, yoffset, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, prevx = null, prevy = null; ctx.beginPath(); for (var i = ps; i < points.length; i += ps) { var x1 = points[i - ps], y1 = points[i - ps + 1], x2 = points[i], y2 = points[i + 1]; if (x1 == null || x2 == null) continue; // clip with ymin if (y1 <= y2 && y1 < axisy.min) { if (y2 < axisy.min) continue; // line segment is outside // compute new intersection point x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min) { if (y1 < axisy.min) continue; x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max) { if (y2 > axisy.max) continue; x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max) { if (y1 > axisy.max) continue; x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (x1 != prevx || y1 != prevy) ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset); prevx = x2; prevy = y2; ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset); } ctx.stroke(); } function plotLineArea(datapoints, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, bottom = Math.min(Math.max(0, axisy.min), axisy.max), i = 0, top, areaOpen = false, ypos = 1, segmentStart = 0, segmentEnd = 0; // we process each segment in two turns, first forward // direction to sketch out top, then once we hit the // end we go backwards to sketch the bottom while (true) { if (ps > 0 && i > points.length + ps) break; i += ps; // ps is negative if going backwards var x1 = points[i - ps], y1 = points[i - ps + ypos], x2 = points[i], y2 = points[i + ypos]; if (areaOpen) { if (ps > 0 && x1 != null && x2 == null) { // at turning point segmentEnd = i; ps = -ps; ypos = 2; continue; } if (ps < 0 && i == segmentStart + ps) { // done with the reverse sweep ctx.fill(); areaOpen = false; ps = -ps; ypos = 1; i = segmentStart = segmentEnd + ps; continue; } } if (x1 == null || x2 == null) continue; // clip x values // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (!areaOpen) { // open area ctx.beginPath(); ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom)); areaOpen = true; } // now first check the case where both is outside if (y1 >= axisy.max && y2 >= axisy.max) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max)); continue; } else if (y1 <= axisy.min && y2 <= axisy.min) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min)); continue; } // else it's a bit more complicated, there might // be a flat maxed out rectangle first, then a // triangular cutout or reverse; to find these // keep track of the current x values var x1old = x1, x2old = x2; // clip the y values, without shortcutting, we // go through all cases in turn // clip with ymin if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) { x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) { x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) { x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) { x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // if the x value was changed we got a rectangle // to fill if (x1 != x1old) { ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1)); // it goes to (x1, y1), but we fill that below } // fill triangular section, this sometimes result // in redundant points if (x1, y1) hasn't changed // from previous line to, but we just ignore that ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); // fill the other rectangle if it's there if (x2 != x2old) { ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2)); } } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.lineJoin = "round"; var lw = series.lines.lineWidth, sw = series.shadowSize; // FIXME: consider another form of shadow when filling is turned on if (lw > 0 && sw > 0) { // draw shadow as a thick and thin line with transparency ctx.lineWidth = sw; ctx.strokeStyle = "rgba(0,0,0,0.1)"; // position shadow at angle from the mid of line var angle = Math.PI/18; plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis); ctx.lineWidth = sw/2; plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight); if (fillStyle) { ctx.fillStyle = fillStyle; plotLineArea(series.datapoints, series.xaxis, series.yaxis); } if (lw > 0) plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis); ctx.restore(); } function drawSeriesPoints(series) { function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { var x = points[i], y = points[i + 1]; if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) continue; ctx.beginPath(); x = axisx.p2c(x); y = axisy.p2c(y) + offset; if (symbol == "circle") ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false); else symbol(ctx, x, y, radius, shadow); ctx.closePath(); if (fillStyle) { ctx.fillStyle = fillStyle; ctx.fill(); } ctx.stroke(); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); var lw = series.points.lineWidth, sw = series.shadowSize, radius = series.points.radius, symbol = series.points.symbol; // If the user sets the line width to 0, we change it to a very // small value. A line width of 0 seems to force the default of 1. // Doing the conditional here allows the shadow setting to still be // optional even with a lineWidth of 0. if( lw == 0 ) lw = 0.0001; if (lw > 0 && sw > 0) { // draw shadow in two steps var w = sw / 2; ctx.lineWidth = w; ctx.strokeStyle = "rgba(0,0,0,0.1)"; plotPoints(series.datapoints, radius, null, w + w/2, true, series.xaxis, series.yaxis, symbol); ctx.strokeStyle = "rgba(0,0,0,0.2)"; plotPoints(series.datapoints, radius, null, w/2, true, series.xaxis, series.yaxis, symbol); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; plotPoints(series.datapoints, radius, getFillStyle(series.points, series.color), 0, false, series.xaxis, series.yaxis, symbol); ctx.restore(); } function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) { var left, right, bottom, top, drawLeft, drawRight, drawTop, drawBottom, tmp; // in horizontal mode, we start the bar from the left // instead of from the bottom so it appears to be // horizontal rather than vertical if (horizontal) { drawBottom = drawRight = drawTop = true; drawLeft = false; left = b; right = x; top = y + barLeft; bottom = y + barRight; // account for negative bars if (right < left) { tmp = right; right = left; left = tmp; drawLeft = true; drawRight = false; } } else { drawLeft = drawRight = drawTop = true; drawBottom = false; left = x + barLeft; right = x + barRight; bottom = b; top = y; // account for negative bars if (top < bottom) { tmp = top; top = bottom; bottom = tmp; drawBottom = true; drawTop = false; } } // clip if (right < axisx.min || left > axisx.max || top < axisy.min || bottom > axisy.max) return; if (left < axisx.min) { left = axisx.min; drawLeft = false; } if (right > axisx.max) { right = axisx.max; drawRight = false; } if (bottom < axisy.min) { bottom = axisy.min; drawBottom = false; } if (top > axisy.max) { top = axisy.max; drawTop = false; } left = axisx.p2c(left); bottom = axisy.p2c(bottom); right = axisx.p2c(right); top = axisy.p2c(top); // fill the bar if (fillStyleCallback) { c.beginPath(); c.moveTo(left, bottom); c.lineTo(left, top); c.lineTo(right, top); c.lineTo(right, bottom); c.fillStyle = fillStyleCallback(bottom, top); c.fill(); } // draw outline if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) { c.beginPath(); // FIXME: inline moveTo is buggy with excanvas c.moveTo(left, bottom + offset); if (drawLeft) c.lineTo(left, top + offset); else c.moveTo(left, top + offset); if (drawTop) c.lineTo(right, top + offset); else c.moveTo(right, top + offset); if (drawRight) c.lineTo(right, bottom + offset); else c.moveTo(right, bottom + offset); if (drawBottom) c.lineTo(left, bottom + offset); else c.moveTo(left, bottom + offset); c.stroke(); } } function drawSeriesBars(series) { function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { if (points[i] == null) continue; drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); // FIXME: figure out a way to add shadows (for instance along the right edge) ctx.lineWidth = series.bars.lineWidth; ctx.strokeStyle = series.color; var barLeft; switch (series.bars.align) { case "left": barLeft = 0; break; case "right": barLeft = -series.bars.barWidth; break; case "center": barLeft = -series.bars.barWidth / 2; break; default: throw new Error("Invalid bar alignment: " + series.bars.align); } var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null; plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis); ctx.restore(); } function getFillStyle(filloptions, seriesColor, bottom, top) { var fill = filloptions.fill; if (!fill) return null; if (filloptions.fillColor) return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor); var c = $.color.parse(seriesColor); c.a = typeof fill == "number" ? fill : 0.4; c.normalize(); return c.toString(); } function insertLegend() { placeholder.find(".legend").remove(); if (!options.legend.show) return; var fragments = [], entries = [], rowStarted = false, lf = options.legend.labelFormatter, s, label; // Build a list of legend entries, with each having a label and a color for (var i = 0; i < series.length; ++i) { s = series[i]; if (s.label) { label = lf ? lf(s.label, s) : s.label; if (label) { entries.push({ label: label, color: s.color }); } } } // Sort the legend using either the default or a custom comparator if (options.legend.sorted) { if ($.isFunction(options.legend.sorted)) { entries.sort(options.legend.sorted); } else if (options.legend.sorted == "reverse") { entries.reverse(); } else { var ascending = options.legend.sorted != "descending"; entries.sort(function(a, b) { return a.label == b.label ? 0 : ( (a.label < b.label) != ascending ? 1 : -1 // Logical XOR ); }); } } // Generate markup for the list of entries, in their final order for (var i = 0; i < entries.length; ++i) { var entry = entries[i]; if (i % options.legend.noColumns == 0) { if (rowStarted) fragments.push('</tr>'); fragments.push('<tr>'); rowStarted = true; } fragments.push( '<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + entry.color + ';overflow:hidden"></div></div></td>' + '<td class="legendLabel">' + entry.label + '</td>' ); } if (rowStarted) fragments.push('</tr>'); if (fragments.length == 0) return; var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>'; if (options.legend.container != null) $(options.legend.container).html(table); else { var pos = "", p = options.legend.position, m = options.legend.margin; if (m[0] == null) m = [m, m]; if (p.charAt(0) == "n") pos += 'top:' + (m[1] + plotOffset.top) + 'px;'; else if (p.charAt(0) == "s") pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;'; if (p.charAt(1) == "e") pos += 'right:' + (m[0] + plotOffset.right) + 'px;'; else if (p.charAt(1) == "w") pos += 'left:' + (m[0] + plotOffset.left) + 'px;'; var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder); if (options.legend.backgroundOpacity != 0.0) { // put in the transparent background // separately to avoid blended labels and // label boxes var c = options.legend.backgroundColor; if (c == null) { c = options.grid.backgroundColor; if (c && typeof c == "string") c = $.color.parse(c); else c = $.color.extract(legend, 'background-color'); c.a = 1; c = c.toString(); } var div = legend.children(); $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity); } } } // interactive features var highlights = [], redrawTimeout = null; // returns the data item the mouse is over, or null if none is found function findNearbyItem(mouseX, mouseY, seriesFilter) { var maxDistance = options.grid.mouseActiveRadius, smallestDistance = maxDistance * maxDistance + 1, item = null, foundPoint = false, i, j, ps; for (i = series.length - 1; i >= 0; --i) { if (!seriesFilter(series[i])) continue; var s = series[i], axisx = s.xaxis, axisy = s.yaxis, points = s.datapoints.points, mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster my = axisy.c2p(mouseY), maxx = maxDistance / axisx.scale, maxy = maxDistance / axisy.scale; ps = s.datapoints.pointsize; // with inverse transforms, we can't use the maxx/maxy // optimization, sadly if (axisx.options.inverseTransform) maxx = Number.MAX_VALUE; if (axisy.options.inverseTransform) maxy = Number.MAX_VALUE; if (s.lines.show || s.points.show) { for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1]; if (x == null) continue; // For points and lines, the cursor must be within a // certain distance to the data point if (x - mx > maxx || x - mx < -maxx || y - my > maxy || y - my < -maxy) continue; // We have to calculate distances in pixels, not in // data units, because the scales of the axes may be different var dx = Math.abs(axisx.p2c(x) - mouseX), dy = Math.abs(axisy.p2c(y) - mouseY), dist = dx * dx + dy * dy; // we save the sqrt // use <= to ensure last point takes precedence // (last generally means on top of) if (dist < smallestDistance) { smallestDistance = dist; item = [i, j / ps]; } } } if (s.bars.show && !item) { // no other point can be nearby var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2, barRight = barLeft + s.bars.barWidth; for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1], b = points[j + 2]; if (x == null) continue; // for a bar graph, the cursor must be inside the bar if (series[i].bars.horizontal ? (mx <= Math.max(b, x) && mx >= Math.min(b, x) && my >= y + barLeft && my <= y + barRight) : (mx >= x + barLeft && mx <= x + barRight && my >= Math.min(b, y) && my <= Math.max(b, y))) item = [i, j / ps]; } } } if (item) { i = item[0]; j = item[1]; ps = series[i].datapoints.pointsize; return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps), dataIndex: j, series: series[i], seriesIndex: i }; } return null; } function onMouseMove(e) { if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) { return s["hoverable"] != false; }); } function onMouseLeave(e) { if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) { return false; }); } function onClick(e) { triggerClickHoverEvent("plotclick", e, function (s) { return s["clickable"] != false; }); } // trigger click or hover event (they send the same parameters // so we share their code) function triggerClickHoverEvent(eventname, event, seriesFilter) { var offset = eventHolder.offset(), canvasX = event.pageX - offset.left - plotOffset.left, canvasY = event.pageY - offset.top - plotOffset.top, pos = canvasToAxisCoords({ left: canvasX, top: canvasY }); pos.pageX = event.pageX; pos.pageY = event.pageY; var item = findNearbyItem(canvasX, canvasY, seriesFilter); if (item) { // fill in mouse pos for any listeners out there item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left, 10); item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top, 10); } if (options.grid.autoHighlight) { // clear auto-highlights for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.auto == eventname && !(item && h.series == item.series && h.point[0] == item.datapoint[0] && h.point[1] == item.datapoint[1])) unhighlight(h.series, h.point); } if (item) highlight(item.series, item.datapoint, eventname); } placeholder.trigger(eventname, [ pos, item ]); } function triggerRedrawOverlay() { var t = options.interaction.redrawOverlayInterval; if (t == -1) { // skip event queue drawOverlay(); return; } if (!redrawTimeout) redrawTimeout = setTimeout(drawOverlay, t); } function drawOverlay() { redrawTimeout = null; // draw highlights octx.save(); overlay.clear(); octx.translate(plotOffset.left, plotOffset.top); var i, hi; for (i = 0; i < highlights.length; ++i) { hi = highlights[i]; if (hi.series.bars.show) drawBarHighlight(hi.series, hi.point); else drawPointHighlight(hi.series, hi.point); } octx.restore(); executeHooks(hooks.drawOverlay, [octx]); } function highlight(s, point, auto) { if (typeof s == "number") s = series[s]; if (typeof point == "number") { var ps = s.datapoints.pointsize; point = s.datapoints.points.slice(ps * point, ps * (point + 1)); } var i = indexOfHighlight(s, point); if (i == -1) { highlights.push({ series: s, point: point, auto: auto }); triggerRedrawOverlay(); } else if (!auto) highlights[i].auto = false; } function unhighlight(s, point) { if (s == null && point == null) { highlights = []; triggerRedrawOverlay(); return; } if (typeof s == "number") s = series[s]; if (typeof point == "number") { var ps = s.datapoints.pointsize; point = s.datapoints.points.slice(ps * point, ps * (point + 1)); } var i = indexOfHighlight(s, point); if (i != -1) { highlights.splice(i, 1); triggerRedrawOverlay(); } } function indexOfHighlight(s, p) { for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.series == s && h.point[0] == p[0] && h.point[1] == p[1]) return i; } return -1; } function drawPointHighlight(series, point) { var x = point[0], y = point[1], axisx = series.xaxis, axisy = series.yaxis, highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(); if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) return; var pointRadius = series.points.radius + series.points.lineWidth / 2; octx.lineWidth = pointRadius; octx.strokeStyle = highlightColor; var radius = 1.5 * pointRadius; x = axisx.p2c(x); y = axisy.p2c(y); octx.beginPath(); if (series.points.symbol == "circle") octx.arc(x, y, radius, 0, 2 * Math.PI, false); else series.points.symbol(octx, x, y, radius, false); octx.closePath(); octx.stroke(); } function drawBarHighlight(series, point) { var highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(), fillStyle = highlightColor, barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; octx.lineWidth = series.bars.lineWidth; octx.strokeStyle = highlightColor; drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth, 0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth); } function getColorOrGradient(spec, bottom, top, defaultColor) { if (typeof spec == "string") return spec; else { // assume this is a gradient spec; IE currently only // supports a simple vertical gradient properly, so that's // what we support too var gradient = ctx.createLinearGradient(0, top, 0, bottom); for (var i = 0, l = spec.colors.length; i < l; ++i) { var c = spec.colors[i]; if (typeof c != "string") { var co = $.color.parse(defaultColor); if (c.brightness != null) co = co.scale('rgb', c.brightness); if (c.opacity != null) co.a *= c.opacity; c = co.toString(); } gradient.addColorStop(i / (l - 1), c); } return gradient; } } } // Add the plot function to the top level of the jQuery object $.plot = function(placeholder, data, options) { //var t0 = new Date(); var plot = new Plot($(placeholder), data, options, $.plot.plugins); //(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime())); return plot; }; $.plot.version = "0.8.1"; $.plot.plugins = []; // Also add the plot function as a chainable property $.fn.plot = function(data, options) { return this.each(function() { $.plot(this, data, options); }); }; // round to nearby lower multiple of base function floorInBase(n, base) { return base * Math.floor(n / base); } })(jQuery);
JavaScript
/* Flot plugin for showing crosshairs when the mouse hovers over the plot. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The plugin supports these options: crosshair: { mode: null or "x" or "y" or "xy" color: color lineWidth: number } Set the mode to one of "x", "y" or "xy". The "x" mode enables a vertical crosshair that lets you trace the values on the x axis, "y" enables a horizontal crosshair and "xy" enables them both. "color" is the color of the crosshair (default is "rgba(170, 0, 0, 0.80)"), "lineWidth" is the width of the drawn lines (default is 1). The plugin also adds four public methods: - setCrosshair( pos ) Set the position of the crosshair. Note that this is cleared if the user moves the mouse. "pos" is in coordinates of the plot and should be on the form { x: xpos, y: ypos } (you can use x2/x3/... if you're using multiple axes), which is coincidentally the same format as what you get from a "plothover" event. If "pos" is null, the crosshair is cleared. - clearCrosshair() Clear the crosshair. - lockCrosshair(pos) Cause the crosshair to lock to the current location, no longer updating if the user moves the mouse. Optionally supply a position (passed on to setCrosshair()) to move it to. Example usage: var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } }; $("#graph").bind( "plothover", function ( evt, position, item ) { if ( item ) { // Lock the crosshair to the data point being hovered myFlot.lockCrosshair({ x: item.datapoint[ 0 ], y: item.datapoint[ 1 ] }); } else { // Return normal crosshair operation myFlot.unlockCrosshair(); } }); - unlockCrosshair() Free the crosshair to move again after locking it. */ (function ($) { var options = { crosshair: { mode: null, // one of null, "x", "y" or "xy", color: "rgba(170, 0, 0, 0.80)", lineWidth: 1 } }; function init(plot) { // position of crosshair in pixels var crosshair = { x: -1, y: -1, locked: false }; plot.setCrosshair = function setCrosshair(pos) { if (!pos) crosshair.x = -1; else { var o = plot.p2c(pos); crosshair.x = Math.max(0, Math.min(o.left, plot.width())); crosshair.y = Math.max(0, Math.min(o.top, plot.height())); } plot.triggerRedrawOverlay(); }; plot.clearCrosshair = plot.setCrosshair; // passes null for pos plot.lockCrosshair = function lockCrosshair(pos) { if (pos) plot.setCrosshair(pos); crosshair.locked = true; }; plot.unlockCrosshair = function unlockCrosshair() { crosshair.locked = false; }; function onMouseOut(e) { if (crosshair.locked) return; if (crosshair.x != -1) { crosshair.x = -1; plot.triggerRedrawOverlay(); } } function onMouseMove(e) { if (crosshair.locked) return; if (plot.getSelection && plot.getSelection()) { crosshair.x = -1; // hide the crosshair while selecting return; } var offset = plot.offset(); crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width())); crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height())); plot.triggerRedrawOverlay(); } plot.hooks.bindEvents.push(function (plot, eventHolder) { if (!plot.getOptions().crosshair.mode) return; eventHolder.mouseout(onMouseOut); eventHolder.mousemove(onMouseMove); }); plot.hooks.drawOverlay.push(function (plot, ctx) { var c = plot.getOptions().crosshair; if (!c.mode) return; var plotOffset = plot.getPlotOffset(); ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); if (crosshair.x != -1) { var adj = plot.getOptions().crosshair.lineWidth % 2 === 0 ? 0 : 0.5; ctx.strokeStyle = c.color; ctx.lineWidth = c.lineWidth; ctx.lineJoin = "round"; ctx.beginPath(); if (c.mode.indexOf("x") != -1) { var drawX = Math.round(crosshair.x) + adj; ctx.moveTo(drawX, 0); ctx.lineTo(drawX, plot.height()); } if (c.mode.indexOf("y") != -1) { var drawY = Math.round(crosshair.y) + adj; ctx.moveTo(0, drawY); ctx.lineTo(plot.width(), drawY); } ctx.stroke(); } ctx.restore(); }); plot.hooks.shutdown.push(function (plot, eventHolder) { eventHolder.unbind("mouseout", onMouseOut); eventHolder.unbind("mousemove", onMouseMove); }); } $.plot.plugins.push({ init: init, options: options, name: 'crosshair', version: '1.0' }); })(jQuery);
JavaScript
/* Flot plugin for drawing all elements of a plot on the canvas. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. Flot normally produces certain elements, like axis labels and the legend, using HTML elements. This permits greater interactivity and customization, and often looks better, due to cross-browser canvas text inconsistencies and limitations. It can also be desirable to render the plot entirely in canvas, particularly if the goal is to save it as an image, or if Flot is being used in a context where the HTML DOM does not exist, as is the case within Node.js. This plugin switches out Flot's standard drawing operations for canvas-only replacements. Currently the plugin supports only axis labels, but it will eventually allow every element of the plot to be rendered directly to canvas. The plugin supports these options: { canvas: boolean } The "canvas" option controls whether full canvas drawing is enabled, making it possible to toggle on and off. This is useful when a plot uses HTML text in the browser, but needs to redraw with canvas text when exporting as an image. */ (function($) { var options = { canvas: true }; var render, getTextInfo, addText; // Cache the prototype hasOwnProperty for faster access var hasOwnProperty = Object.prototype.hasOwnProperty; function init(plot, classes) { var Canvas = classes.Canvas; // We only want to replace the functions once; the second time around // we would just get our new function back. This whole replacing of // prototype functions is a disaster, and needs to be changed ASAP. if (render == null) { getTextInfo = Canvas.prototype.getTextInfo, addText = Canvas.prototype.addText, render = Canvas.prototype.render; } // Finishes rendering the canvas, including overlaid text Canvas.prototype.render = function() { if (!plot.getOptions().canvas) { return render.call(this); } var context = this.context, cache = this._textCache; // For each text layer, render elements marked as active context.save(); context.textBaseline = "middle"; for (var layerKey in cache) { if (hasOwnProperty.call(cache, layerKey)) { var layerCache = cache[layerKey]; for (var styleKey in layerCache) { if (hasOwnProperty.call(layerCache, styleKey)) { var styleCache = layerCache[styleKey], updateStyles = true; for (var key in styleCache) { if (hasOwnProperty.call(styleCache, key)) { var info = styleCache[key], positions = info.positions, lines = info.lines; // Since every element at this level of the cache have the // same font and fill styles, we can just change them once // using the values from the first element. if (updateStyles) { context.fillStyle = info.font.color; context.font = info.font.definition; updateStyles = false; } for (var i = 0, position; position = positions[i]; i++) { if (position.active) { for (var j = 0, line; line = position.lines[j]; j++) { context.fillText(lines[j].text, line[0], line[1]); } } else { positions.splice(i--, 1); } } if (positions.length == 0) { delete styleCache[key]; } } } } } } } context.restore(); }; // Creates (if necessary) and returns a text info object. // // When the canvas option is set, the object looks like this: // // { // width: Width of the text's bounding box. // height: Height of the text's bounding box. // positions: Array of positions at which this text is drawn. // lines: [{ // height: Height of this line. // widths: Width of this line. // text: Text on this line. // }], // font: { // definition: Canvas font property string. // color: Color of the text. // }, // } // // The positions array contains objects that look like this: // // { // active: Flag indicating whether the text should be visible. // lines: Array of [x, y] coordinates at which to draw the line. // x: X coordinate at which to draw the text. // y: Y coordinate at which to draw the text. // } Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) { if (!plot.getOptions().canvas) { return getTextInfo.call(this, layer, text, font, angle, width); } var textStyle, layerCache, styleCache, info; // Cast the value to a string, in case we were given a number text = "" + text; // If the font is a font-spec object, generate a CSS definition if (typeof font === "object") { textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px " + font.family; } else { textStyle = font; } // Retrieve (or create) the cache for the text's layer and styles layerCache = this._textCache[layer]; if (layerCache == null) { layerCache = this._textCache[layer] = {}; } styleCache = layerCache[textStyle]; if (styleCache == null) { styleCache = layerCache[textStyle] = {}; } info = styleCache[text]; if (info == null) { var context = this.context; // If the font was provided as CSS, create a div with those // classes and examine it to generate a canvas font spec. if (typeof font !== "object") { var element = $("<div>&nbsp;</div>") .css("position", "absolute") .addClass(typeof font === "string" ? font : null) .appendTo(this.getTextLayer(layer)); font = { lineHeight: element.height(), style: element.css("font-style"), variant: element.css("font-variant"), weight: element.css("font-weight"), family: element.css("font-family"), color: element.css("color") }; // Setting line-height to 1, without units, sets it equal // to the font-size, even if the font-size is abstract, // like 'smaller'. This enables us to read the real size // via the element's height, working around browsers that // return the literal 'smaller' value. font.size = element.css("line-height", 1).height(); element.remove(); } textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px " + font.family; // Create a new info object, initializing the dimensions to // zero so we can count them up line-by-line. info = styleCache[text] = { width: 0, height: 0, positions: [], lines: [], font: { definition: textStyle, color: font.color } }; context.save(); context.font = textStyle; // Canvas can't handle multi-line strings; break on various // newlines, including HTML brs, to build a list of lines. // Note that we could split directly on regexps, but IE < 9 is // broken; revisit when we drop IE 7/8 support. var lines = (text + "").replace(/<br ?\/?>|\r\n|\r/g, "\n").split("\n"); for (var i = 0; i < lines.length; ++i) { var lineText = lines[i], measured = context.measureText(lineText); info.width = Math.max(measured.width, info.width); info.height += font.lineHeight; info.lines.push({ text: lineText, width: measured.width, height: font.lineHeight }); } context.restore(); } return info; }; // Adds a text string to the canvas text overlay. Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) { if (!plot.getOptions().canvas) { return addText.call(this, layer, x, y, text, font, angle, width, halign, valign); } var info = this.getTextInfo(layer, text, font, angle, width), positions = info.positions, lines = info.lines; // Text is drawn with baseline 'middle', which we need to account // for by adding half a line's height to the y position. y += info.height / lines.length / 2; // Tweak the initial y-position to match vertical alignment if (valign == "middle") { y = Math.round(y - info.height / 2); } else if (valign == "bottom") { y = Math.round(y - info.height); } else { y = Math.round(y); } // FIXME: LEGACY BROWSER FIX // AFFECTS: Opera < 12.00 // Offset the y coordinate, since Opera is off pretty // consistently compared to the other browsers. if (!!(window.opera && window.opera.version().split(".")[0] < 12)) { y -= 2; } // Determine whether this text already exists at this position. // If so, mark it for inclusion in the next render pass. for (var i = 0, position; position = positions[i]; i++) { if (position.x == x && position.y == y) { position.active = true; return; } } // If the text doesn't exist at this position, create a new entry position = { active: true, lines: [], x: x, y: y }; positions.push(position); // Fill in the x & y positions of each line, adjusting them // individually for horizontal alignment. for (var i = 0, line; line = lines[i]; i++) { if (halign == "center") { position.lines.push([Math.round(x - line.width / 2), y]); } else if (halign == "right") { position.lines.push([Math.round(x - line.width), y]); } else { position.lines.push([Math.round(x), y]); } y += line.height; } }; } $.plot.plugins.push({ init: init, options: options, name: "canvas", version: "1.0" }); })(jQuery);
JavaScript
/* Flot plugin for adding the ability to pan and zoom the plot. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The default behaviour is double click and scrollwheel up/down to zoom in, drag to pan. The plugin defines plot.zoom({ center }), plot.zoomOut() and plot.pan( offset ) so you easily can add custom controls. It also fires "plotpan" and "plotzoom" events, useful for synchronizing plots. The plugin supports these options: zoom: { interactive: false trigger: "dblclick" // or "click" for single click amount: 1.5 // 2 = 200% (zoom in), 0.5 = 50% (zoom out) } pan: { interactive: false cursor: "move" // CSS mouse cursor value used when dragging, e.g. "pointer" frameRate: 20 } xaxis, yaxis, x2axis, y2axis: { zoomRange: null // or [ number, number ] (min range, max range) or false panRange: null // or [ number, number ] (min, max) or false } "interactive" enables the built-in drag/click behaviour. If you enable interactive for pan, then you'll have a basic plot that supports moving around; the same for zoom. "amount" specifies the default amount to zoom in (so 1.5 = 150%) relative to the current viewport. "cursor" is a standard CSS mouse cursor string used for visual feedback to the user when dragging. "frameRate" specifies the maximum number of times per second the plot will update itself while the user is panning around on it (set to null to disable intermediate pans, the plot will then not update until the mouse button is released). "zoomRange" is the interval in which zooming can happen, e.g. with zoomRange: [1, 100] the zoom will never scale the axis so that the difference between min and max is smaller than 1 or larger than 100. You can set either end to null to ignore, e.g. [1, null]. If you set zoomRange to false, zooming on that axis will be disabled. "panRange" confines the panning to stay within a range, e.g. with panRange: [-10, 20] panning stops at -10 in one end and at 20 in the other. Either can be null, e.g. [-10, null]. If you set panRange to false, panning on that axis will be disabled. Example API usage: plot = $.plot(...); // zoom default amount in on the pixel ( 10, 20 ) plot.zoom({ center: { left: 10, top: 20 } }); // zoom out again plot.zoomOut({ center: { left: 10, top: 20 } }); // zoom 200% in on the pixel (10, 20) plot.zoom({ amount: 2, center: { left: 10, top: 20 } }); // pan 100 pixels to the left and 20 down plot.pan({ left: -100, top: 20 }) Here, "center" specifies where the center of the zooming should happen. Note that this is defined in pixel space, not the space of the data points (you can use the p2c helpers on the axes in Flot to help you convert between these). "amount" is the amount to zoom the viewport relative to the current range, so 1 is 100% (i.e. no change), 1.5 is 150% (zoom in), 0.7 is 70% (zoom out). You can set the default in the options. */ // First two dependencies, jquery.event.drag.js and // jquery.mousewheel.js, we put them inline here to save people the // effort of downloading them. /* jquery.event.drag.js ~ v1.5 ~ Copyright (c) 2008, Three Dub Media (http://threedubmedia.com) Licensed under the MIT License ~ http://threedubmedia.googlecode.com/files/MIT-LICENSE.txt */ (function(a){function e(h){var k,j=this,l=h.data||{};if(l.elem)j=h.dragTarget=l.elem,h.dragProxy=d.proxy||j,h.cursorOffsetX=l.pageX-l.left,h.cursorOffsetY=l.pageY-l.top,h.offsetX=h.pageX-h.cursorOffsetX,h.offsetY=h.pageY-h.cursorOffsetY;else if(d.dragging||l.which>0&&h.which!=l.which||a(h.target).is(l.not))return;switch(h.type){case"mousedown":return a.extend(l,a(j).offset(),{elem:j,target:h.target,pageX:h.pageX,pageY:h.pageY}),b.add(document,"mousemove mouseup",e,l),i(j,!1),d.dragging=null,!1;case!d.dragging&&"mousemove":if(g(h.pageX-l.pageX)+g(h.pageY-l.pageY)<l.distance)break;h.target=l.target,k=f(h,"dragstart",j),k!==!1&&(d.dragging=j,d.proxy=h.dragProxy=a(k||j)[0]);case"mousemove":if(d.dragging){if(k=f(h,"drag",j),c.drop&&(c.drop.allowed=k!==!1,c.drop.handler(h)),k!==!1)break;h.type="mouseup"}case"mouseup":b.remove(document,"mousemove mouseup",e),d.dragging&&(c.drop&&c.drop.handler(h),f(h,"dragend",j)),i(j,!0),d.dragging=d.proxy=l.elem=!1}return!0}function f(b,c,d){b.type=c;var e=a.event.dispatch.call(d,b);return e===!1?!1:e||b.result}function g(a){return Math.pow(a,2)}function h(){return d.dragging===!1}function i(a,b){a&&(a.unselectable=b?"off":"on",a.onselectstart=function(){return b},a.style&&(a.style.MozUserSelect=b?"":"none"))}a.fn.drag=function(a,b,c){return b&&this.bind("dragstart",a),c&&this.bind("dragend",c),a?this.bind("drag",b?b:a):this.trigger("drag")};var b=a.event,c=b.special,d=c.drag={not:":input",distance:0,which:1,dragging:!1,setup:function(c){c=a.extend({distance:d.distance,which:d.which,not:d.not},c||{}),c.distance=g(c.distance),b.add(this,"mousedown",e,c),this.attachEvent&&this.attachEvent("ondragstart",h)},teardown:function(){b.remove(this,"mousedown",e),this===d.dragging&&(d.dragging=d.proxy=!1),i(this,!0),this.detachEvent&&this.detachEvent("ondragstart",h)}};c.dragstart=c.dragend={setup:function(){},teardown:function(){}}})(jQuery); /* jquery.mousewheel.min.js * Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.6 * * Requires: 1.2.2+ */ (function(d){function e(a){var b=a||window.event,c=[].slice.call(arguments,1),f=0,e=0,g=0,a=d.event.fix(b);a.type="mousewheel";b.wheelDelta&&(f=b.wheelDelta/120);b.detail&&(f=-b.detail/3);g=f;void 0!==b.axis&&b.axis===b.HORIZONTAL_AXIS&&(g=0,e=-1*f);void 0!==b.wheelDeltaY&&(g=b.wheelDeltaY/120);void 0!==b.wheelDeltaX&&(e=-1*b.wheelDeltaX/120);c.unshift(a,f,e,g);return(d.event.dispatch||d.event.handle).apply(this,c)}var c=["DOMMouseScroll","mousewheel"];if(d.event.fixHooks)for(var h=c.length;h;)d.event.fixHooks[c[--h]]=d.event.mouseHooks;d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],e,!1);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],e,!1);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery); (function ($) { var options = { xaxis: { zoomRange: null, // or [number, number] (min range, max range) panRange: null // or [number, number] (min, max) }, zoom: { interactive: false, trigger: "dblclick", // or "click" for single click amount: 1.5 // how much to zoom relative to current position, 2 = 200% (zoom in), 0.5 = 50% (zoom out) }, pan: { interactive: false, cursor: "move", frameRate: 20 } }; function init(plot) { function onZoomClick(e, zoomOut) { var c = plot.offset(); c.left = e.pageX - c.left; c.top = e.pageY - c.top; if (zoomOut) plot.zoomOut({ center: c }); else plot.zoom({ center: c }); } function onMouseWheel(e, delta) { e.preventDefault(); onZoomClick(e, delta < 0); return false; } var prevCursor = 'default', prevPageX = 0, prevPageY = 0, panTimeout = null; function onDragStart(e) { if (e.which != 1) // only accept left-click return false; var c = plot.getPlaceholder().css('cursor'); if (c) prevCursor = c; plot.getPlaceholder().css('cursor', plot.getOptions().pan.cursor); prevPageX = e.pageX; prevPageY = e.pageY; } function onDrag(e) { var frameRate = plot.getOptions().pan.frameRate; if (panTimeout || !frameRate) return; panTimeout = setTimeout(function () { plot.pan({ left: prevPageX - e.pageX, top: prevPageY - e.pageY }); prevPageX = e.pageX; prevPageY = e.pageY; panTimeout = null; }, 1 / frameRate * 1000); } function onDragEnd(e) { if (panTimeout) { clearTimeout(panTimeout); panTimeout = null; } plot.getPlaceholder().css('cursor', prevCursor); plot.pan({ left: prevPageX - e.pageX, top: prevPageY - e.pageY }); } function bindEvents(plot, eventHolder) { var o = plot.getOptions(); if (o.zoom.interactive) { eventHolder[o.zoom.trigger](onZoomClick); eventHolder.mousewheel(onMouseWheel); } if (o.pan.interactive) { eventHolder.bind("dragstart", { distance: 10 }, onDragStart); eventHolder.bind("drag", onDrag); eventHolder.bind("dragend", onDragEnd); } } plot.zoomOut = function (args) { if (!args) args = {}; if (!args.amount) args.amount = plot.getOptions().zoom.amount; args.amount = 1 / args.amount; plot.zoom(args); }; plot.zoom = function (args) { if (!args) args = {}; var c = args.center, amount = args.amount || plot.getOptions().zoom.amount, w = plot.width(), h = plot.height(); if (!c) c = { left: w / 2, top: h / 2 }; var xf = c.left / w, yf = c.top / h, minmax = { x: { min: c.left - xf * w / amount, max: c.left + (1 - xf) * w / amount }, y: { min: c.top - yf * h / amount, max: c.top + (1 - yf) * h / amount } }; $.each(plot.getAxes(), function(_, axis) { var opts = axis.options, min = minmax[axis.direction].min, max = minmax[axis.direction].max, zr = opts.zoomRange, pr = opts.panRange; if (zr === false) // no zooming on this axis return; min = axis.c2p(min); max = axis.c2p(max); if (min > max) { // make sure min < max var tmp = min; min = max; max = tmp; } //Check that we are in panRange if (pr) { if (pr[0] != null && min < pr[0]) { min = pr[0]; } if (pr[1] != null && max > pr[1]) { max = pr[1]; } } var range = max - min; if (zr && ((zr[0] != null && range < zr[0]) || (zr[1] != null && range > zr[1]))) return; opts.min = min; opts.max = max; }); plot.setupGrid(); plot.draw(); if (!args.preventEvent) plot.getPlaceholder().trigger("plotzoom", [ plot, args ]); }; plot.pan = function (args) { var delta = { x: +args.left, y: +args.top }; if (isNaN(delta.x)) delta.x = 0; if (isNaN(delta.y)) delta.y = 0; $.each(plot.getAxes(), function (_, axis) { var opts = axis.options, min, max, d = delta[axis.direction]; min = axis.c2p(axis.p2c(axis.min) + d), max = axis.c2p(axis.p2c(axis.max) + d); var pr = opts.panRange; if (pr === false) // no panning on this axis return; if (pr) { // check whether we hit the wall if (pr[0] != null && pr[0] > min) { d = pr[0] - min; min += d; max += d; } if (pr[1] != null && pr[1] < max) { d = pr[1] - max; min += d; max += d; } } opts.min = min; opts.max = max; }); plot.setupGrid(); plot.draw(); if (!args.preventEvent) plot.getPlaceholder().trigger("plotpan", [ plot, args ]); }; function shutdown(plot, eventHolder) { eventHolder.unbind(plot.getOptions().zoom.trigger, onZoomClick); eventHolder.unbind("mousewheel", onMouseWheel); eventHolder.unbind("dragstart", onDragStart); eventHolder.unbind("drag", onDrag); eventHolder.unbind("dragend", onDragEnd); if (panTimeout) clearTimeout(panTimeout); } plot.hooks.bindEvents.push(bindEvents); plot.hooks.shutdown.push(shutdown); } $.plot.plugins.push({ init: init, options: options, name: 'navigate', version: '1.3' }); })(jQuery);
JavaScript
/* Pretty handling of time axes. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. Set axis.mode to "time" to enable. See the section "Time series data" in API.txt for details. */ (function($) { var options = { xaxis: { timezone: null, // "browser" for local to the client or timezone for timezone-js timeformat: null, // format string to use twelveHourClock: false, // 12 or 24 time in time mode monthNames: null // list of names of months } }; // round to nearby lower multiple of base function floorInBase(n, base) { return base * Math.floor(n / base); } // Returns a string with the date d formatted according to fmt. // A subset of the Open Group's strftime format is supported. function formatDate(d, fmt, monthNames, dayNames) { if (typeof d.strftime == "function") { return d.strftime(fmt); } var leftPad = function(n, pad) { n = "" + n; pad = "" + (pad == null ? "0" : pad); return n.length == 1 ? pad + n : n; }; var r = []; var escape = false; var hours = d.getHours(); var isAM = hours < 12; if (monthNames == null) { monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; } if (dayNames == null) { dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; } var hours12; if (hours > 12) { hours12 = hours - 12; } else if (hours == 0) { hours12 = 12; } else { hours12 = hours; } for (var i = 0; i < fmt.length; ++i) { var c = fmt.charAt(i); if (escape) { switch (c) { case 'a': c = "" + dayNames[d.getDay()]; break; case 'b': c = "" + monthNames[d.getMonth()]; break; case 'd': c = leftPad(d.getDate()); break; case 'e': c = leftPad(d.getDate(), " "); break; case 'h': // For back-compat with 0.7; remove in 1.0 case 'H': c = leftPad(hours); break; case 'I': c = leftPad(hours12); break; case 'l': c = leftPad(hours12, " "); break; case 'm': c = leftPad(d.getMonth() + 1); break; case 'M': c = leftPad(d.getMinutes()); break; // quarters not in Open Group's strftime specification case 'q': c = "" + (Math.floor(d.getMonth() / 3) + 1); break; case 'S': c = leftPad(d.getSeconds()); break; case 'y': c = leftPad(d.getFullYear() % 100); break; case 'Y': c = "" + d.getFullYear(); break; case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break; case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break; case 'w': c = "" + d.getDay(); break; } r.push(c); escape = false; } else { if (c == "%") { escape = true; } else { r.push(c); } } } return r.join(""); } // To have a consistent view of time-based data independent of which time // zone the client happens to be in we need a date-like object independent // of time zones. This is done through a wrapper that only calls the UTC // versions of the accessor methods. function makeUtcWrapper(d) { function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) { sourceObj[sourceMethod] = function() { return targetObj[targetMethod].apply(targetObj, arguments); }; }; var utc = { date: d }; // support strftime, if found if (d.strftime != undefined) { addProxyMethod(utc, "strftime", d, "strftime"); } addProxyMethod(utc, "getTime", d, "getTime"); addProxyMethod(utc, "setTime", d, "setTime"); var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"]; for (var p = 0; p < props.length; p++) { addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]); addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]); } return utc; }; // select time zone strategy. This returns a date-like object tied to the // desired timezone function dateGenerator(ts, opts) { if (opts.timezone == "browser") { return new Date(ts); } else if (!opts.timezone || opts.timezone == "utc") { return makeUtcWrapper(new Date(ts)); } else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") { var d = new timezoneJS.Date(); // timezone-js is fickle, so be sure to set the time zone before // setting the time. d.setTimezone(opts.timezone); d.setTime(ts); return d; } else { return makeUtcWrapper(new Date(ts)); } } // map of app. size of time units in milliseconds var timeUnitSize = { "second": 1000, "minute": 60 * 1000, "hour": 60 * 60 * 1000, "day": 24 * 60 * 60 * 1000, "month": 30 * 24 * 60 * 60 * 1000, "quarter": 3 * 30 * 24 * 60 * 60 * 1000, "year": 365.2425 * 24 * 60 * 60 * 1000 }; // the allowed tick sizes, after 1 year we use // an integer algorithm var baseSpec = [ [1, "second"], [2, "second"], [5, "second"], [10, "second"], [30, "second"], [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], [30, "minute"], [1, "hour"], [2, "hour"], [4, "hour"], [8, "hour"], [12, "hour"], [1, "day"], [2, "day"], [3, "day"], [0.25, "month"], [0.5, "month"], [1, "month"], [2, "month"] ]; // we don't know which variant(s) we'll need yet, but generating both is // cheap var specMonths = baseSpec.concat([[3, "month"], [6, "month"], [1, "year"]]); var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"], [1, "year"]]); function init(plot) { plot.hooks.processOptions.push(function (plot, options) { $.each(plot.getAxes(), function(axisName, axis) { var opts = axis.options; if (opts.mode == "time") { axis.tickGenerator = function(axis) { var ticks = []; var d = dateGenerator(axis.min, opts); var minSize = 0; // make quarter use a possibility if quarters are // mentioned in either of these options var spec = (opts.tickSize && opts.tickSize[1] === "quarter") || (opts.minTickSize && opts.minTickSize[1] === "quarter") ? specQuarters : specMonths; if (opts.minTickSize != null) { if (typeof opts.tickSize == "number") { minSize = opts.tickSize; } else { minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]]; } } for (var i = 0; i < spec.length - 1; ++i) { if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]] + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2 && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) { break; } } var size = spec[i][0]; var unit = spec[i][1]; // special-case the possibility of several years if (unit == "year") { // if given a minTickSize in years, just use it, // ensuring that it's an integer if (opts.minTickSize != null && opts.minTickSize[1] == "year") { size = Math.floor(opts.minTickSize[0]); } else { var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10)); var norm = (axis.delta / timeUnitSize.year) / magn; if (norm < 1.5) { size = 1; } else if (norm < 3) { size = 2; } else if (norm < 7.5) { size = 5; } else { size = 10; } size *= magn; } // minimum size for years is 1 if (size < 1) { size = 1; } } axis.tickSize = opts.tickSize || [size, unit]; var tickSize = axis.tickSize[0]; unit = axis.tickSize[1]; var step = tickSize * timeUnitSize[unit]; if (unit == "second") { d.setSeconds(floorInBase(d.getSeconds(), tickSize)); } else if (unit == "minute") { d.setMinutes(floorInBase(d.getMinutes(), tickSize)); } else if (unit == "hour") { d.setHours(floorInBase(d.getHours(), tickSize)); } else if (unit == "month") { d.setMonth(floorInBase(d.getMonth(), tickSize)); } else if (unit == "quarter") { d.setMonth(3 * floorInBase(d.getMonth() / 3, tickSize)); } else if (unit == "year") { d.setFullYear(floorInBase(d.getFullYear(), tickSize)); } // reset smaller components d.setMilliseconds(0); if (step >= timeUnitSize.minute) { d.setSeconds(0); } if (step >= timeUnitSize.hour) { d.setMinutes(0); } if (step >= timeUnitSize.day) { d.setHours(0); } if (step >= timeUnitSize.day * 4) { d.setDate(1); } if (step >= timeUnitSize.month * 2) { d.setMonth(floorInBase(d.getMonth(), 3)); } if (step >= timeUnitSize.quarter * 2) { d.setMonth(floorInBase(d.getMonth(), 6)); } if (step >= timeUnitSize.year) { d.setMonth(0); } var carry = 0; var v = Number.NaN; var prev; do { prev = v; v = d.getTime(); ticks.push(v); if (unit == "month" || unit == "quarter") { if (tickSize < 1) { // a bit complicated - we'll divide the // month/quarter up but we need to take // care of fractions so we don't end up in // the middle of a day d.setDate(1); var start = d.getTime(); d.setMonth(d.getMonth() + (unit == "quarter" ? 3 : 1)); var end = d.getTime(); d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize); carry = d.getHours(); d.setHours(0); } else { d.setMonth(d.getMonth() + tickSize * (unit == "quarter" ? 3 : 1)); } } else if (unit == "year") { d.setFullYear(d.getFullYear() + tickSize); } else { d.setTime(v + step); } } while (v < axis.max && v != prev); return ticks; }; axis.tickFormatter = function (v, axis) { var d = dateGenerator(v, axis.options); // first check global format if (opts.timeformat != null) { return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames); } // possibly use quarters if quarters are mentioned in // any of these places var useQuarters = (axis.options.tickSize && axis.options.tickSize[1] == "quarter") || (axis.options.minTickSize && axis.options.minTickSize[1] == "quarter"); var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]]; var span = axis.max - axis.min; var suffix = (opts.twelveHourClock) ? " %p" : ""; var hourCode = (opts.twelveHourClock) ? "%I" : "%H"; var fmt; if (t < timeUnitSize.minute) { fmt = hourCode + ":%M:%S" + suffix; } else if (t < timeUnitSize.day) { if (span < 2 * timeUnitSize.day) { fmt = hourCode + ":%M" + suffix; } else { fmt = "%b %d " + hourCode + ":%M" + suffix; } } else if (t < timeUnitSize.month) { fmt = "%b %d"; } else if ((useQuarters && t < timeUnitSize.quarter) || (!useQuarters && t < timeUnitSize.year)) { if (span < timeUnitSize.year) { fmt = "%b"; } else { fmt = "%b %Y"; } } else if (useQuarters && t < timeUnitSize.year) { if (span < timeUnitSize.year) { fmt = "Q%q"; } else { fmt = "Q%q %Y"; } } else { fmt = "%Y"; } var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames); return rt; }; } }); }); } $.plot.plugins.push({ init: init, options: options, name: 'time', version: '1.0' }); // Time-axis support used to be in Flot core, which exposed the // formatDate function on the plot object. Various plugins depend // on the function, so we need to re-expose it here. $.plot.formatDate = formatDate; })(jQuery);
JavaScript
/* * Flot plugin to order bars side by side. * * Released under the MIT license by Benjamin BUFFET, 20-Sep-2010. * * This plugin is an alpha version. * * To activate the plugin you must specify the parameter "order" for the specific serie : * * $.plot($("#placeholder"), [{ data: [ ... ], bars :{ order = null or integer }]) * * If 2 series have the same order param, they are ordered by the position in the array; * * The plugin adjust the point by adding a value depanding of the barwidth * Exemple for 3 series (barwidth : 0.1) : * * first bar décalage : -0.15 * second bar décalage : -0.05 * third bar décalage : 0.05 * */ (function($){ function init(plot){ var orderedBarSeries; var nbOfBarsToOrder; var borderWidth; var borderWidthInXabsWidth; var pixelInXWidthEquivalent = 1; var isHorizontal = false; /* * This method add shift to x values */ function reOrderBars(plot, serie, datapoints){ var shiftedPoints = null; if(serieNeedToBeReordered(serie)){ checkIfGraphIsHorizontal(serie); calculPixel2XWidthConvert(plot); retrieveBarSeries(plot); calculBorderAndBarWidth(serie); if(nbOfBarsToOrder >= 2){ var position = findPosition(serie); var decallage = -1; var centerBarShift = calculCenterBarShift(); if (isBarAtLeftOfCenter(position)){ decallage = -1*(sumWidth(orderedBarSeries,position-1,Math.floor(nbOfBarsToOrder / 2)-1)) - centerBarShift; }else{ decallage = sumWidth(orderedBarSeries,Math.ceil(nbOfBarsToOrder / 2),position-2) + centerBarShift + borderWidthInXabsWidth*2; } shiftedPoints = shiftPoints(datapoints,serie,decallage); datapoints.points = shiftedPoints; } } return shiftedPoints; } function serieNeedToBeReordered(serie){ return serie.bars != null && serie.bars.show && serie.bars.order != null; } function calculPixel2XWidthConvert(plot){ var gridDimSize = isHorizontal ? plot.getPlaceholder().innerHeight() : plot.getPlaceholder().innerWidth(); var minMaxValues = isHorizontal ? getAxeMinMaxValues(plot.getData(),1) : getAxeMinMaxValues(plot.getData(),0); var AxeSize = minMaxValues[1] - minMaxValues[0]; pixelInXWidthEquivalent = AxeSize / gridDimSize; } function getAxeMinMaxValues(series,AxeIdx){ var minMaxValues = new Array(); for(var i = 0; i < series.length; i++){ minMaxValues[0] = series[i].data[0][AxeIdx]; minMaxValues[1] = series[i].data[series[i].data.length - 1][AxeIdx]; } return minMaxValues; } function retrieveBarSeries(plot){ orderedBarSeries = findOthersBarsToReOrders(plot.getData()); nbOfBarsToOrder = orderedBarSeries.length; } function findOthersBarsToReOrders(series){ var retSeries = new Array(); for(var i = 0; i < series.length; i++){ if(series[i].bars.order != null && series[i].bars.show){ retSeries.push(series[i]); } } return retSeries.sort(sortByOrder); } function sortByOrder(serie1,serie2){ var x = serie1.bars.order; var y = serie2.bars.order; return ((x < y) ? -1 : ((x > y) ? 1 : 0)); } function calculBorderAndBarWidth(serie){ borderWidth = serie.bars.lineWidth ? serie.bars.lineWidth : 2; borderWidthInXabsWidth = borderWidth * pixelInXWidthEquivalent; } function checkIfGraphIsHorizontal(serie){ if(serie.bars.horizontal){ isHorizontal = true; } } function findPosition(serie){ var pos = 0 for (var i = 0; i < orderedBarSeries.length; ++i) { if (serie == orderedBarSeries[i]){ pos = i; break; } } return pos+1; } function calculCenterBarShift(){ var width = 0; if(nbOfBarsToOrder%2 != 0) width = (orderedBarSeries[Math.ceil(nbOfBarsToOrder / 2)].bars.barWidth)/2; return width; } function isBarAtLeftOfCenter(position){ return position <= Math.ceil(nbOfBarsToOrder / 2); } function sumWidth(series,start,end){ var totalWidth = 0; for(var i = start; i <= end; i++){ totalWidth += series[i].bars.barWidth+borderWidthInXabsWidth*2; } return totalWidth; } function shiftPoints(datapoints,serie,dx){ var ps = datapoints.pointsize; var points = datapoints.points; var j = 0; for(var i = isHorizontal ? 1 : 0;i < points.length; i += ps){ points[i] += dx; //Adding the new x value in the serie to be abble to display the right tooltip value, //using the index 3 to not overide the third index. serie.data[j][3] = points[i]; j++; } return points; } plot.hooks.processDatapoints.push(reOrderBars); } var options = { series : { bars: {order: null} // or number/string } }; $.plot.plugins.push({ init: init, options: options, name: "orderBars", version: "0.2" }); })(jQuery)
JavaScript
/* Flot plugin that adds some extra symbols for plotting points. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The symbols are accessed as strings through the standard symbol options: series: { points: { symbol: "square" // or "diamond", "triangle", "cross" } } */ (function ($) { function processRawData(plot, series, datapoints) { // we normalize the area of each symbol so it is approximately the // same as a circle of the given radius var handlers = { square: function (ctx, x, y, radius, shadow) { // pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2 var size = radius * Math.sqrt(Math.PI) / 2; ctx.rect(x - size, y - size, size + size, size + size); }, diamond: function (ctx, x, y, radius, shadow) { // pi * r^2 = 2s^2 => s = r * sqrt(pi/2) var size = radius * Math.sqrt(Math.PI / 2); ctx.moveTo(x - size, y); ctx.lineTo(x, y - size); ctx.lineTo(x + size, y); ctx.lineTo(x, y + size); ctx.lineTo(x - size, y); }, triangle: function (ctx, x, y, radius, shadow) { // pi * r^2 = 1/2 * s^2 * sin (pi / 3) => s = r * sqrt(2 * pi / sin(pi / 3)) var size = radius * Math.sqrt(2 * Math.PI / Math.sin(Math.PI / 3)); var height = size * Math.sin(Math.PI / 3); ctx.moveTo(x - size/2, y + height/2); ctx.lineTo(x + size/2, y + height/2); if (!shadow) { ctx.lineTo(x, y - height/2); ctx.lineTo(x - size/2, y + height/2); } }, cross: function (ctx, x, y, radius, shadow) { // pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2 var size = radius * Math.sqrt(Math.PI) / 2; ctx.moveTo(x - size, y - size); ctx.lineTo(x + size, y + size); ctx.moveTo(x - size, y + size); ctx.lineTo(x + size, y - size); } }; var s = series.points.symbol; if (handlers[s]) series.points.symbol = handlers[s]; } function init(plot) { plot.hooks.processDatapoints.push(processRawData); } $.plot.plugins.push({ init: init, name: 'symbols', version: '1.0' }); })(jQuery);
JavaScript
/* Flot plugin for plotting textual data or categories. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. Consider a dataset like [["February", 34], ["March", 20], ...]. This plugin allows you to plot such a dataset directly. To enable it, you must specify mode: "categories" on the axis with the textual labels, e.g. $.plot("#placeholder", data, { xaxis: { mode: "categories" } }); By default, the labels are ordered as they are met in the data series. If you need a different ordering, you can specify "categories" on the axis options and list the categories there: xaxis: { mode: "categories", categories: ["February", "March", "April"] } If you need to customize the distances between the categories, you can specify "categories" as an object mapping labels to values xaxis: { mode: "categories", categories: { "February": 1, "March": 3, "April": 4 } } If you don't specify all categories, the remaining categories will be numbered from the max value plus 1 (with a spacing of 1 between each). Internally, the plugin works by transforming the input data through an auto- generated mapping where the first category becomes 0, the second 1, etc. Hence, a point like ["February", 34] becomes [0, 34] internally in Flot (this is visible in hover and click events that return numbers rather than the category labels). The plugin also overrides the tick generator to spit out the categories as ticks instead of the values. If you need to map a value back to its label, the mapping is always accessible as "categories" on the axis object, e.g. plot.getAxes().xaxis.categories. */ (function ($) { var options = { xaxis: { categories: null }, yaxis: { categories: null } }; function processRawData(plot, series, data, datapoints) { // if categories are enabled, we need to disable // auto-transformation to numbers so the strings are intact // for later processing var xCategories = series.xaxis.options.mode == "categories", yCategories = series.yaxis.options.mode == "categories"; if (!(xCategories || yCategories)) return; var format = datapoints.format; if (!format) { // FIXME: auto-detection should really not be defined here var s = series; format = []; format.push({ x: true, number: true, required: true }); format.push({ y: true, number: true, required: true }); if (s.bars.show || (s.lines.show && s.lines.fill)) { var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero)); format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale }); if (s.bars.horizontal) { delete format[format.length - 1].y; format[format.length - 1].x = true; } } datapoints.format = format; } for (var m = 0; m < format.length; ++m) { if (format[m].x && xCategories) format[m].number = false; if (format[m].y && yCategories) format[m].number = false; } } function getNextIndex(categories) { var index = -1; for (var v in categories) if (categories[v] > index) index = categories[v]; return index + 1; } function categoriesTickGenerator(axis) { var res = []; for (var label in axis.categories) { var v = axis.categories[label]; if (v >= axis.min && v <= axis.max) res.push([v, label]); } res.sort(function (a, b) { return a[0] - b[0]; }); return res; } function setupCategoriesForAxis(series, axis, datapoints) { if (series[axis].options.mode != "categories") return; if (!series[axis].categories) { // parse options var c = {}, o = series[axis].options.categories || {}; if ($.isArray(o)) { for (var i = 0; i < o.length; ++i) c[o[i]] = i; } else { for (var v in o) c[v] = o[v]; } series[axis].categories = c; } // fix ticks if (!series[axis].options.ticks) series[axis].options.ticks = categoriesTickGenerator; transformPointsOnAxis(datapoints, axis, series[axis].categories); } function transformPointsOnAxis(datapoints, axis, categories) { // go through the points, transforming them var points = datapoints.points, ps = datapoints.pointsize, format = datapoints.format, formatColumn = axis.charAt(0), index = getNextIndex(categories); for (var i = 0; i < points.length; i += ps) { if (points[i] == null) continue; for (var m = 0; m < ps; ++m) { var val = points[i + m]; if (val == null || !format[m][formatColumn]) continue; if (!(val in categories)) { categories[val] = index; ++index; } points[i + m] = categories[val]; } } } function processDatapoints(plot, series, datapoints) { setupCategoriesForAxis(series, "xaxis", datapoints); setupCategoriesForAxis(series, "yaxis", datapoints); } function init(plot) { plot.hooks.processRawData.push(processRawData); plot.hooks.processDatapoints.push(processDatapoints); } $.plot.plugins.push({ init: init, options: options, name: 'categories', version: '1.0' }); })(jQuery);
JavaScript
/* Flot plugin for automatically redrawing plots as the placeholder resizes. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. It works by listening for changes on the placeholder div (through the jQuery resize event plugin) - if the size changes, it will redraw the plot. There are no options. If you need to disable the plugin for some plots, you can just fix the size of their placeholders. */ /* Inline dependency: * jQuery resize event - v1.1 - 3/14/2010 * http://benalman.com/projects/jquery-resize-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function($,h,c){var a=$([]),e=$.resize=$.extend($.resize,{}),i,k="setTimeout",j="resize",d=j+"-special-event",b="delay",f="throttleWindow";e[b]=250;e[f]=true;$.event.special[j]={setup:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.add(l);$.data(this,d,{w:l.width(),h:l.height()});if(a.length===1){g()}},teardown:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.not(l);l.removeData(d);if(!a.length){clearTimeout(i)}},add:function(l){if(!e[f]&&this[k]){return false}var n;function m(s,o,p){var q=$(this),r=$.data(this,d);r.w=o!==c?o:q.width();r.h=p!==c?p:q.height();n.apply(this,arguments)}if($.isFunction(l)){n=l;return m}else{n=l.handler;l.handler=m}}};function g(){i=h[k](function(){a.each(function(){var n=$(this),m=n.width(),l=n.height(),o=$.data(this,d);if(m!==o.w||l!==o.h){n.trigger(j,[o.w=m,o.h=l])}});g()},e[b])}})(jQuery,this); (function ($) { var options = { }; // no options function init(plot) { function onResize() { var placeholder = plot.getPlaceholder(); // somebody might have hidden us and we can't plot // when we don't have the dimensions if (placeholder.width() == 0 || placeholder.height() == 0) return; plot.resize(); plot.setupGrid(); plot.draw(); } function bindEvents(plot, eventHolder) { plot.getPlaceholder().resize(onResize); } function shutdown(plot, eventHolder) { plot.getPlaceholder().unbind("resize", onResize); } plot.hooks.bindEvents.push(bindEvents); plot.hooks.shutdown.push(shutdown); } $.plot.plugins.push({ init: init, options: options, name: 'resize', version: '1.0' }); })(jQuery);
JavaScript
/* Flot plugin for thresholding data. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The plugin supports these options: series: { threshold: { below: number color: colorspec } } It can also be applied to a single series, like this: $.plot( $("#placeholder"), [{ data: [ ... ], threshold: { ... } }]) An array can be passed for multiple thresholding, like this: threshold: [{ below: number1 color: color1 },{ below: number2 color: color2 }] These multiple threshold objects can be passed in any order since they are sorted by the processing function. The data points below "below" are drawn with the specified color. This makes it easy to mark points below 0, e.g. for budget data. Internally, the plugin works by splitting the data into two series, above and below the threshold. The extra series below the threshold will have its label cleared and the special "originSeries" attribute set to the original series. You may need to check for this in hover events. */ (function ($) { var options = { series: { threshold: null } // or { below: number, color: color spec} }; function init(plot) { function thresholdData(plot, s, datapoints, below, color) { var ps = datapoints.pointsize, i, x, y, p, prevp, thresholded = $.extend({}, s); // note: shallow copy thresholded.datapoints = { points: [], pointsize: ps, format: datapoints.format }; thresholded.label = null; thresholded.color = color; thresholded.threshold = null; thresholded.originSeries = s; thresholded.data = []; var origpoints = datapoints.points, addCrossingPoints = s.lines.show; var threspoints = []; var newpoints = []; var m; for (i = 0; i < origpoints.length; i += ps) { x = origpoints[i]; y = origpoints[i + 1]; prevp = p; if (y < below) p = threspoints; else p = newpoints; if (addCrossingPoints && prevp != p && x != null && i > 0 && origpoints[i - ps] != null) { var interx = x + (below - y) * (x - origpoints[i - ps]) / (y - origpoints[i - ps + 1]); prevp.push(interx); prevp.push(below); for (m = 2; m < ps; ++m) prevp.push(origpoints[i + m]); p.push(null); // start new segment p.push(null); for (m = 2; m < ps; ++m) p.push(origpoints[i + m]); p.push(interx); p.push(below); for (m = 2; m < ps; ++m) p.push(origpoints[i + m]); } p.push(x); p.push(y); for (m = 2; m < ps; ++m) p.push(origpoints[i + m]); } datapoints.points = newpoints; thresholded.datapoints.points = threspoints; if (thresholded.datapoints.points.length > 0) { var origIndex = $.inArray(s, plot.getData()); // Insert newly-generated series right after original one (to prevent it from becoming top-most) plot.getData().splice(origIndex + 1, 0, thresholded); } // FIXME: there are probably some edge cases left in bars } function processThresholds(plot, s, datapoints) { if (!s.threshold) return; if (s.threshold instanceof Array) { s.threshold.sort(function(a, b) { return a.below - b.below; }); $(s.threshold).each(function(i, th) { thresholdData(plot, s, datapoints, th.below, th.color); }); } else { thresholdData(plot, s, datapoints, s.threshold.below, s.threshold.color); } } plot.hooks.processDatapoints.push(processThresholds); } $.plot.plugins.push({ init: init, options: options, name: 'threshold', version: '1.2' }); })(jQuery);
JavaScript
/* Flot plugin for selecting regions of a plot. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The plugin supports these options: selection: { mode: null or "x" or "y" or "xy", color: color, shape: "round" or "miter" or "bevel", minSize: number of pixels } Selection support is enabled by setting the mode to one of "x", "y" or "xy". In "x" mode, the user will only be able to specify the x range, similarly for "y" mode. For "xy", the selection becomes a rectangle where both ranges can be specified. "color" is color of the selection (if you need to change the color later on, you can get to it with plot.getOptions().selection.color). "shape" is the shape of the corners of the selection. "minSize" is the minimum size a selection can be in pixels. This value can be customized to determine the smallest size a selection can be and still have the selection rectangle be displayed. When customizing this value, the fact that it refers to pixels, not axis units must be taken into account. Thus, for example, if there is a bar graph in time mode with BarWidth set to 1 minute, setting "minSize" to 1 will not make the minimum selection size 1 minute, but rather 1 pixel. Note also that setting "minSize" to 0 will prevent "plotunselected" events from being fired when the user clicks the mouse without dragging. When selection support is enabled, a "plotselected" event will be emitted on the DOM element you passed into the plot function. The event handler gets a parameter with the ranges selected on the axes, like this: placeholder.bind( "plotselected", function( event, ranges ) { alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to) // similar for yaxis - with multiple axes, the extra ones are in // x2axis, x3axis, ... }); The "plotselected" event is only fired when the user has finished making the selection. A "plotselecting" event is fired during the process with the same parameters as the "plotselected" event, in case you want to know what's happening while it's happening, A "plotunselected" event with no arguments is emitted when the user clicks the mouse to remove the selection. As stated above, setting "minSize" to 0 will destroy this behavior. The plugin allso adds the following methods to the plot object: - setSelection( ranges, preventEvent ) Set the selection rectangle. The passed in ranges is on the same form as returned in the "plotselected" event. If the selection mode is "x", you should put in either an xaxis range, if the mode is "y" you need to put in an yaxis range and both xaxis and yaxis if the selection mode is "xy", like this: setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } }); setSelection will trigger the "plotselected" event when called. If you don't want that to happen, e.g. if you're inside a "plotselected" handler, pass true as the second parameter. If you are using multiple axes, you can specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of xaxis, the plugin picks the first one it sees. - clearSelection( preventEvent ) Clear the selection rectangle. Pass in true to avoid getting a "plotunselected" event. - getSelection() Returns the current selection in the same format as the "plotselected" event. If there's currently no selection, the function returns null. */ (function ($) { function init(plot) { var selection = { first: { x: -1, y: -1}, second: { x: -1, y: -1}, show: false, active: false }; // FIXME: The drag handling implemented here should be // abstracted out, there's some similar code from a library in // the navigation plugin, this should be massaged a bit to fit // the Flot cases here better and reused. Doing this would // make this plugin much slimmer. var savedhandlers = {}; var mouseUpHandler = null; function onMouseMove(e) { if (selection.active) { updateSelection(e); plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]); } } function onMouseDown(e) { if (e.which != 1) // only accept left-click return; // cancel out any text selections document.body.focus(); // prevent text selection and drag in old-school browsers if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) { savedhandlers.onselectstart = document.onselectstart; document.onselectstart = function () { return false; }; } if (document.ondrag !== undefined && savedhandlers.ondrag == null) { savedhandlers.ondrag = document.ondrag; document.ondrag = function () { return false; }; } setSelectionPos(selection.first, e); selection.active = true; // this is a bit silly, but we have to use a closure to be // able to whack the same handler again mouseUpHandler = function (e) { onMouseUp(e); }; $(document).one("mouseup", mouseUpHandler); } function onMouseUp(e) { mouseUpHandler = null; // revert drag stuff for old-school browsers if (document.onselectstart !== undefined) document.onselectstart = savedhandlers.onselectstart; if (document.ondrag !== undefined) document.ondrag = savedhandlers.ondrag; // no more dragging selection.active = false; updateSelection(e); if (selectionIsSane()) triggerSelectedEvent(); else { // this counts as a clear plot.getPlaceholder().trigger("plotunselected", [ ]); plot.getPlaceholder().trigger("plotselecting", [ null ]); } return false; } function getSelection() { if (!selectionIsSane()) return null; if (!selection.show) return null; var r = {}, c1 = selection.first, c2 = selection.second; $.each(plot.getAxes(), function (name, axis) { if (axis.used) { var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]); r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) }; } }); return r; } function triggerSelectedEvent() { var r = getSelection(); plot.getPlaceholder().trigger("plotselected", [ r ]); // backwards-compat stuff, to be removed in future if (r.xaxis && r.yaxis) plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]); } function clamp(min, value, max) { return value < min ? min: (value > max ? max: value); } function setSelectionPos(pos, e) { var o = plot.getOptions(); var offset = plot.getPlaceholder().offset(); var plotOffset = plot.getPlotOffset(); pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width()); pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height()); if (o.selection.mode == "y") pos.x = pos == selection.first ? 0 : plot.width(); if (o.selection.mode == "x") pos.y = pos == selection.first ? 0 : plot.height(); } function updateSelection(pos) { if (pos.pageX == null) return; setSelectionPos(selection.second, pos); if (selectionIsSane()) { selection.show = true; plot.triggerRedrawOverlay(); } else clearSelection(true); } function clearSelection(preventEvent) { if (selection.show) { selection.show = false; plot.triggerRedrawOverlay(); if (!preventEvent) plot.getPlaceholder().trigger("plotunselected", [ ]); } } // function taken from markings support in Flot function extractRange(ranges, coord) { var axis, from, to, key, axes = plot.getAxes(); for (var k in axes) { axis = axes[k]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis if (ranges[key]) { from = ranges[key].from; to = ranges[key].to; break; } } } // backwards-compat stuff - to be removed in future if (!ranges[key]) { axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) { var tmp = from; from = to; to = tmp; } return { from: from, to: to, axis: axis }; } function setSelection(ranges, preventEvent) { var axis, range, o = plot.getOptions(); if (o.selection.mode == "y") { selection.first.x = 0; selection.second.x = plot.width(); } else { range = extractRange(ranges, "x"); selection.first.x = range.axis.p2c(range.from); selection.second.x = range.axis.p2c(range.to); } if (o.selection.mode == "x") { selection.first.y = 0; selection.second.y = plot.height(); } else { range = extractRange(ranges, "y"); selection.first.y = range.axis.p2c(range.from); selection.second.y = range.axis.p2c(range.to); } selection.show = true; plot.triggerRedrawOverlay(); if (!preventEvent && selectionIsSane()) triggerSelectedEvent(); } function selectionIsSane() { var minSize = plot.getOptions().selection.minSize; return Math.abs(selection.second.x - selection.first.x) >= minSize && Math.abs(selection.second.y - selection.first.y) >= minSize; } plot.clearSelection = clearSelection; plot.setSelection = setSelection; plot.getSelection = getSelection; plot.hooks.bindEvents.push(function(plot, eventHolder) { var o = plot.getOptions(); if (o.selection.mode != null) { eventHolder.mousemove(onMouseMove); eventHolder.mousedown(onMouseDown); } }); plot.hooks.drawOverlay.push(function (plot, ctx) { // draw selection if (selection.show && selectionIsSane()) { var plotOffset = plot.getPlotOffset(); var o = plot.getOptions(); ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); var c = $.color.parse(o.selection.color); ctx.strokeStyle = c.scale('a', 0.8).toString(); ctx.lineWidth = 1; ctx.lineJoin = o.selection.shape; ctx.fillStyle = c.scale('a', 0.4).toString(); var x = Math.min(selection.first.x, selection.second.x) + 0.5, y = Math.min(selection.first.y, selection.second.y) + 0.5, w = Math.abs(selection.second.x - selection.first.x) - 1, h = Math.abs(selection.second.y - selection.first.y) - 1; ctx.fillRect(x, y, w, h); ctx.strokeRect(x, y, w, h); ctx.restore(); } }); plot.hooks.shutdown.push(function (plot, eventHolder) { eventHolder.unbind("mousemove", onMouseMove); eventHolder.unbind("mousedown", onMouseDown); if (mouseUpHandler) $(document).unbind("mouseup", mouseUpHandler); }); } $.plot.plugins.push({ init: init, options: { selection: { mode: null, // one of null, "x", "y" or "xy" color: "#e8cfac", shape: "round", // one of "round", "miter", or "bevel" minSize: 5 // minimum number of pixels } }, name: 'selection', version: '1.1' }); })(jQuery);
JavaScript
/* Plugin for jQuery for working with colors. * * Version 1.1. * * Inspiration from jQuery color animation plugin by John Resig. * * Released under the MIT license by Ole Laursen, October 2009. * * Examples: * * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString() * var c = $.color.extract($("#mydiv"), 'background-color'); * console.log(c.r, c.g, c.b, c.a); * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)" * * Note that .scale() and .add() return the same modified object * instead of making a new one. * * V. 1.1: Fix error handling so e.g. parsing an empty string does * produce a color rather than just crashing. */ (function($) { $.color = {}; // construct color object with some convenient chainable helpers $.color.make = function (r, g, b, a) { var o = {}; o.r = r || 0; o.g = g || 0; o.b = b || 0; o.a = a != null ? a : 1; o.add = function (c, d) { for (var i = 0; i < c.length; ++i) o[c.charAt(i)] += d; return o.normalize(); }; o.scale = function (c, f) { for (var i = 0; i < c.length; ++i) o[c.charAt(i)] *= f; return o.normalize(); }; o.toString = function () { if (o.a >= 1.0) { return "rgb("+[o.r, o.g, o.b].join(",")+")"; } else { return "rgba("+[o.r, o.g, o.b, o.a].join(",")+")"; } }; o.normalize = function () { function clamp(min, value, max) { return value < min ? min: (value > max ? max: value); } o.r = clamp(0, parseInt(o.r), 255); o.g = clamp(0, parseInt(o.g), 255); o.b = clamp(0, parseInt(o.b), 255); o.a = clamp(0, o.a, 1); return o; }; o.clone = function () { return $.color.make(o.r, o.b, o.g, o.a); }; return o.normalize(); } // extract CSS color property from element, going up in the DOM // if it's "transparent" $.color.extract = function (elem, css) { var c; do { c = elem.css(css).toLowerCase(); // keep going until we find an element that has color, or // we hit the body if (c != '' && c != 'transparent') break; elem = elem.parent(); } while (!$.nodeName(elem.get(0), "body")); // catch Safari's way of signalling transparent if (c == "rgba(0, 0, 0, 0)") c = "transparent"; return $.color.parse(c); } // parse CSS color string (like "rgb(10, 32, 43)" or "#fff"), // returns color object, if parsing failed, you get black (0, 0, // 0) out $.color.parse = function (str) { var res, m = $.color.make; // Look for rgb(num,num,num) if (res = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str)) return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10)); // Look for rgba(num,num,num,num) if (res = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10), parseFloat(res[4])); // Look for rgb(num%,num%,num%) if (res = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str)) return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55); // Look for rgba(num%,num%,num%,num) if (res = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55, parseFloat(res[4])); // Look for #a0b1c2 if (res = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str)) return m(parseInt(res[1], 16), parseInt(res[2], 16), parseInt(res[3], 16)); // Look for #fff if (res = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str)) return m(parseInt(res[1]+res[1], 16), parseInt(res[2]+res[2], 16), parseInt(res[3]+res[3], 16)); // Otherwise, we're most likely dealing with a named color var name = $.trim(str).toLowerCase(); if (name == "transparent") return m(255, 255, 255, 0); else { // default to black res = lookupColors[name] || [0, 0, 0]; return m(res[0], res[1], res[2]); } } var lookupColors = { aqua:[0,255,255], azure:[240,255,255], beige:[245,245,220], black:[0,0,0], blue:[0,0,255], brown:[165,42,42], cyan:[0,255,255], darkblue:[0,0,139], darkcyan:[0,139,139], darkgrey:[169,169,169], darkgreen:[0,100,0], darkkhaki:[189,183,107], darkmagenta:[139,0,139], darkolivegreen:[85,107,47], darkorange:[255,140,0], darkorchid:[153,50,204], darkred:[139,0,0], darksalmon:[233,150,122], darkviolet:[148,0,211], fuchsia:[255,0,255], gold:[255,215,0], green:[0,128,0], indigo:[75,0,130], khaki:[240,230,140], lightblue:[173,216,230], lightcyan:[224,255,255], lightgreen:[144,238,144], lightgrey:[211,211,211], lightpink:[255,182,193], lightyellow:[255,255,224], lime:[0,255,0], magenta:[255,0,255], maroon:[128,0,0], navy:[0,0,128], olive:[128,128,0], orange:[255,165,0], pink:[255,192,203], purple:[128,0,128], violet:[128,0,128], red:[255,0,0], silver:[192,192,192], white:[255,255,255], yellow:[255,255,0] }; })(jQuery);
JavaScript
// Copyright 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Known Issues: // // * Patterns only support repeat. // * Radial gradient are not implemented. The VML version of these look very // different from the canvas one. // * Clipping paths are not implemented. // * Coordsize. The width and height attribute have higher priority than the // width and height style values which isn't correct. // * Painting mode isn't implemented. // * Canvas width/height should is using content-box by default. IE in // Quirks mode will draw the canvas using border-box. Either change your // doctype to HTML5 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) // or use Box Sizing Behavior from WebFX // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) // * Non uniform scaling does not correctly scale strokes. // * Filling very large shapes (above 5000 points) is buggy. // * Optimize. There is always room for speed improvements. // Only add this code if we do not already have a canvas implementation if (!document.createElement('canvas').getContext) { (function() { // alias some functions to make (compiled) code shorter var m = Math; var mr = m.round; var ms = m.sin; var mc = m.cos; var abs = m.abs; var sqrt = m.sqrt; // this is used for sub pixel precision var Z = 10; var Z2 = Z / 2; var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; /** * This funtion is assigned to the <canvas> elements as element.getContext(). * @this {HTMLElement} * @return {CanvasRenderingContext2D_} */ function getContext() { return this.context_ || (this.context_ = new CanvasRenderingContext2D_(this)); } var slice = Array.prototype.slice; /** * Binds a function to an object. The returned function will always use the * passed in {@code obj} as {@code this}. * * Example: * * g = bind(f, obj, a, b) * g(c, d) // will do f.call(obj, a, b, c, d) * * @param {Function} f The function to bind the object to * @param {Object} obj The object that should act as this when the function * is called * @param {*} var_args Rest arguments that will be used as the initial * arguments when the function is called * @return {Function} A new function that has bound this */ function bind(f, obj, var_args) { var a = slice.call(arguments, 2); return function() { return f.apply(obj, a.concat(slice.call(arguments))); }; } function encodeHtmlAttribute(s) { return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;'); } function addNamespace(doc, prefix, urn) { if (!doc.namespaces[prefix]) { doc.namespaces.add(prefix, urn, '#default#VML'); } } function addNamespacesAndStylesheet(doc) { addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); // Setup default CSS. Only add one style sheet per document if (!doc.styleSheets['ex_canvas_']) { var ss = doc.createStyleSheet(); ss.owningElement.id = 'ex_canvas_'; ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + // default size is 300x150 in Gecko and Opera 'text-align:left;width:300px;height:150px}'; } } // Add namespaces and stylesheet at startup. addNamespacesAndStylesheet(document); var G_vmlCanvasManager_ = { init: function(opt_doc) { var doc = opt_doc || document; // Create a dummy element so that IE will allow canvas elements to be // recognized. doc.createElement('canvas'); doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); }, init_: function(doc) { // find all canvas elements var els = doc.getElementsByTagName('canvas'); for (var i = 0; i < els.length; i++) { this.initElement(els[i]); } }, /** * Public initializes a canvas element so that it can be used as canvas * element from now on. This is called automatically before the page is * loaded but if you are creating elements using createElement you need to * make sure this is called on the element. * @param {HTMLElement} el The canvas element to initialize. * @return {HTMLElement} the element that was created. */ initElement: function(el) { if (!el.getContext) { el.getContext = getContext; // Add namespaces and stylesheet to document of the element. addNamespacesAndStylesheet(el.ownerDocument); // Remove fallback content. There is no way to hide text nodes so we // just remove all childNodes. We could hide all elements and remove // text nodes but who really cares about the fallback content. el.innerHTML = ''; // do not use inline function because that will leak memory el.attachEvent('onpropertychange', onPropertyChange); el.attachEvent('onresize', onResize); var attrs = el.attributes; if (attrs.width && attrs.width.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setWidth_(attrs.width.nodeValue); el.style.width = attrs.width.nodeValue + 'px'; } else { el.width = el.clientWidth; } if (attrs.height && attrs.height.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setHeight_(attrs.height.nodeValue); el.style.height = attrs.height.nodeValue + 'px'; } else { el.height = el.clientHeight; } //el.getContext().setCoordsize_() } return el; } }; function onPropertyChange(e) { var el = e.srcElement; switch (e.propertyName) { case 'width': el.getContext().clearRect(); el.style.width = el.attributes.width.nodeValue + 'px'; // In IE8 this does not trigger onresize. el.firstChild.style.width = el.clientWidth + 'px'; break; case 'height': el.getContext().clearRect(); el.style.height = el.attributes.height.nodeValue + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; break; } } function onResize(e) { var el = e.srcElement; if (el.firstChild) { el.firstChild.style.width = el.clientWidth + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; } } G_vmlCanvasManager_.init(); // precompute "00" to "FF" var decToHex = []; for (var i = 0; i < 16; i++) { for (var j = 0; j < 16; j++) { decToHex[i * 16 + j] = i.toString(16) + j.toString(16); } } function createMatrixIdentity() { return [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; } function matrixMultiply(m1, m2) { var result = createMatrixIdentity(); for (var x = 0; x < 3; x++) { for (var y = 0; y < 3; y++) { var sum = 0; for (var z = 0; z < 3; z++) { sum += m1[x][z] * m2[z][y]; } result[x][y] = sum; } } return result; } function copyState(o1, o2) { o2.fillStyle = o1.fillStyle; o2.lineCap = o1.lineCap; o2.lineJoin = o1.lineJoin; o2.lineWidth = o1.lineWidth; o2.miterLimit = o1.miterLimit; o2.shadowBlur = o1.shadowBlur; o2.shadowColor = o1.shadowColor; o2.shadowOffsetX = o1.shadowOffsetX; o2.shadowOffsetY = o1.shadowOffsetY; o2.strokeStyle = o1.strokeStyle; o2.globalAlpha = o1.globalAlpha; o2.font = o1.font; o2.textAlign = o1.textAlign; o2.textBaseline = o1.textBaseline; o2.arcScaleX_ = o1.arcScaleX_; o2.arcScaleY_ = o1.arcScaleY_; o2.lineScale_ = o1.lineScale_; } var colorData = { aliceblue: '#F0F8FF', antiquewhite: '#FAEBD7', aquamarine: '#7FFFD4', azure: '#F0FFFF', beige: '#F5F5DC', bisque: '#FFE4C4', black: '#000000', blanchedalmond: '#FFEBCD', blueviolet: '#8A2BE2', brown: '#A52A2A', burlywood: '#DEB887', cadetblue: '#5F9EA0', chartreuse: '#7FFF00', chocolate: '#D2691E', coral: '#FF7F50', cornflowerblue: '#6495ED', cornsilk: '#FFF8DC', crimson: '#DC143C', cyan: '#00FFFF', darkblue: '#00008B', darkcyan: '#008B8B', darkgoldenrod: '#B8860B', darkgray: '#A9A9A9', darkgreen: '#006400', darkgrey: '#A9A9A9', darkkhaki: '#BDB76B', darkmagenta: '#8B008B', darkolivegreen: '#556B2F', darkorange: '#FF8C00', darkorchid: '#9932CC', darkred: '#8B0000', darksalmon: '#E9967A', darkseagreen: '#8FBC8F', darkslateblue: '#483D8B', darkslategray: '#2F4F4F', darkslategrey: '#2F4F4F', darkturquoise: '#00CED1', darkviolet: '#9400D3', deeppink: '#FF1493', deepskyblue: '#00BFFF', dimgray: '#696969', dimgrey: '#696969', dodgerblue: '#1E90FF', firebrick: '#B22222', floralwhite: '#FFFAF0', forestgreen: '#228B22', gainsboro: '#DCDCDC', ghostwhite: '#F8F8FF', gold: '#FFD700', goldenrod: '#DAA520', grey: '#808080', greenyellow: '#ADFF2F', honeydew: '#F0FFF0', hotpink: '#FF69B4', indianred: '#CD5C5C', indigo: '#4B0082', ivory: '#FFFFF0', khaki: '#F0E68C', lavender: '#E6E6FA', lavenderblush: '#FFF0F5', lawngreen: '#7CFC00', lemonchiffon: '#FFFACD', lightblue: '#ADD8E6', lightcoral: '#F08080', lightcyan: '#E0FFFF', lightgoldenrodyellow: '#FAFAD2', lightgreen: '#90EE90', lightgrey: '#D3D3D3', lightpink: '#FFB6C1', lightsalmon: '#FFA07A', lightseagreen: '#20B2AA', lightskyblue: '#87CEFA', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#B0C4DE', lightyellow: '#FFFFE0', limegreen: '#32CD32', linen: '#FAF0E6', magenta: '#FF00FF', mediumaquamarine: '#66CDAA', mediumblue: '#0000CD', mediumorchid: '#BA55D3', mediumpurple: '#9370DB', mediumseagreen: '#3CB371', mediumslateblue: '#7B68EE', mediumspringgreen: '#00FA9A', mediumturquoise: '#48D1CC', mediumvioletred: '#C71585', midnightblue: '#191970', mintcream: '#F5FFFA', mistyrose: '#FFE4E1', moccasin: '#FFE4B5', navajowhite: '#FFDEAD', oldlace: '#FDF5E6', olivedrab: '#6B8E23', orange: '#FFA500', orangered: '#FF4500', orchid: '#DA70D6', palegoldenrod: '#EEE8AA', palegreen: '#98FB98', paleturquoise: '#AFEEEE', palevioletred: '#DB7093', papayawhip: '#FFEFD5', peachpuff: '#FFDAB9', peru: '#CD853F', pink: '#FFC0CB', plum: '#DDA0DD', powderblue: '#B0E0E6', rosybrown: '#BC8F8F', royalblue: '#4169E1', saddlebrown: '#8B4513', salmon: '#FA8072', sandybrown: '#F4A460', seagreen: '#2E8B57', seashell: '#FFF5EE', sienna: '#A0522D', skyblue: '#87CEEB', slateblue: '#6A5ACD', slategray: '#708090', slategrey: '#708090', snow: '#FFFAFA', springgreen: '#00FF7F', steelblue: '#4682B4', tan: '#D2B48C', thistle: '#D8BFD8', tomato: '#FF6347', turquoise: '#40E0D0', violet: '#EE82EE', wheat: '#F5DEB3', whitesmoke: '#F5F5F5', yellowgreen: '#9ACD32' }; function getRgbHslContent(styleString) { var start = styleString.indexOf('(', 3); var end = styleString.indexOf(')', start + 1); var parts = styleString.substring(start + 1, end).split(','); // add alpha if needed if (parts.length != 4 || styleString.charAt(3) != 'a') { parts[3] = 1; } return parts; } function percent(s) { return parseFloat(s) / 100; } function clamp(v, min, max) { return Math.min(max, Math.max(min, v)); } function hslToRgb(parts){ var r, g, b, h, s, l; h = parseFloat(parts[0]) / 360 % 360; if (h < 0) h++; s = clamp(percent(parts[1]), 0, 1); l = clamp(percent(parts[2]), 0, 1); if (s == 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hueToRgb(p, q, h + 1 / 3); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1 / 3); } return '#' + decToHex[Math.floor(r * 255)] + decToHex[Math.floor(g * 255)] + decToHex[Math.floor(b * 255)]; } function hueToRgb(m1, m2, h) { if (h < 0) h++; if (h > 1) h--; if (6 * h < 1) return m1 + (m2 - m1) * 6 * h; else if (2 * h < 1) return m2; else if (3 * h < 2) return m1 + (m2 - m1) * (2 / 3 - h) * 6; else return m1; } var processStyleCache = {}; function processStyle(styleString) { if (styleString in processStyleCache) { return processStyleCache[styleString]; } var str, alpha = 1; styleString = String(styleString); if (styleString.charAt(0) == '#') { str = styleString; } else if (/^rgb/.test(styleString)) { var parts = getRgbHslContent(styleString); var str = '#', n; for (var i = 0; i < 3; i++) { if (parts[i].indexOf('%') != -1) { n = Math.floor(percent(parts[i]) * 255); } else { n = +parts[i]; } str += decToHex[clamp(n, 0, 255)]; } alpha = +parts[3]; } else if (/^hsl/.test(styleString)) { var parts = getRgbHslContent(styleString); str = hslToRgb(parts); alpha = parts[3]; } else { str = colorData[styleString] || styleString; } return processStyleCache[styleString] = {color: str, alpha: alpha}; } var DEFAULT_STYLE = { style: 'normal', variant: 'normal', weight: 'normal', size: 10, family: 'sans-serif' }; // Internal text style cache var fontStyleCache = {}; function processFontStyle(styleString) { if (fontStyleCache[styleString]) { return fontStyleCache[styleString]; } var el = document.createElement('div'); var style = el.style; try { style.font = styleString; } catch (ex) { // Ignore failures to set to invalid font. } return fontStyleCache[styleString] = { style: style.fontStyle || DEFAULT_STYLE.style, variant: style.fontVariant || DEFAULT_STYLE.variant, weight: style.fontWeight || DEFAULT_STYLE.weight, size: style.fontSize || DEFAULT_STYLE.size, family: style.fontFamily || DEFAULT_STYLE.family }; } function getComputedStyle(style, element) { var computedStyle = {}; for (var p in style) { computedStyle[p] = style[p]; } // Compute the size var canvasFontSize = parseFloat(element.currentStyle.fontSize), fontSize = parseFloat(style.size); if (typeof style.size == 'number') { computedStyle.size = style.size; } else if (style.size.indexOf('px') != -1) { computedStyle.size = fontSize; } else if (style.size.indexOf('em') != -1) { computedStyle.size = canvasFontSize * fontSize; } else if(style.size.indexOf('%') != -1) { computedStyle.size = (canvasFontSize / 100) * fontSize; } else if (style.size.indexOf('pt') != -1) { computedStyle.size = fontSize / .75; } else { computedStyle.size = canvasFontSize; } // Different scaling between normal text and VML text. This was found using // trial and error to get the same size as non VML text. computedStyle.size *= 0.981; return computedStyle; } function buildStyle(style) { return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + style.size + 'px ' + style.family; } var lineCapMap = { 'butt': 'flat', 'round': 'round' }; function processLineCap(lineCap) { return lineCapMap[lineCap] || 'square'; } /** * This class implements CanvasRenderingContext2D interface as described by * the WHATWG. * @param {HTMLElement} canvasElement The element that the 2D context should * be associated with */ function CanvasRenderingContext2D_(canvasElement) { this.m_ = createMatrixIdentity(); this.mStack_ = []; this.aStack_ = []; this.currentPath_ = []; // Canvas context properties this.strokeStyle = '#000'; this.fillStyle = '#000'; this.lineWidth = 1; this.lineJoin = 'miter'; this.lineCap = 'butt'; this.miterLimit = Z * 1; this.globalAlpha = 1; this.font = '10px sans-serif'; this.textAlign = 'left'; this.textBaseline = 'alphabetic'; this.canvas = canvasElement; var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; var el = canvasElement.ownerDocument.createElement('div'); el.style.cssText = cssText; canvasElement.appendChild(el); var overlayEl = el.cloneNode(false); // Use a non transparent background. overlayEl.style.backgroundColor = 'red'; overlayEl.style.filter = 'alpha(opacity=0)'; canvasElement.appendChild(overlayEl); this.element_ = el; this.arcScaleX_ = 1; this.arcScaleY_ = 1; this.lineScale_ = 1; } var contextPrototype = CanvasRenderingContext2D_.prototype; contextPrototype.clearRect = function() { if (this.textMeasureEl_) { this.textMeasureEl_.removeNode(true); this.textMeasureEl_ = null; } this.element_.innerHTML = ''; }; contextPrototype.beginPath = function() { // TODO: Branch current matrix so that save/restore has no effect // as per safari docs. this.currentPath_ = []; }; contextPrototype.moveTo = function(aX, aY) { var p = getCoords(this, aX, aY); this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.lineTo = function(aX, aY) { var p = getCoords(this, aX, aY); this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { var p = getCoords(this, aX, aY); var cp1 = getCoords(this, aCP1x, aCP1y); var cp2 = getCoords(this, aCP2x, aCP2y); bezierCurveTo(this, cp1, cp2, p); }; // Helper function that takes the already fixed cordinates. function bezierCurveTo(self, cp1, cp2, p) { self.currentPath_.push({ type: 'bezierCurveTo', cp1x: cp1.x, cp1y: cp1.y, cp2x: cp2.x, cp2y: cp2.y, x: p.x, y: p.y }); self.currentX_ = p.x; self.currentY_ = p.y; } contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { // the following is lifted almost directly from // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes var cp = getCoords(this, aCPx, aCPy); var p = getCoords(this, aX, aY); var cp1 = { x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) }; var cp2 = { x: cp1.x + (p.x - this.currentX_) / 3.0, y: cp1.y + (p.y - this.currentY_) / 3.0 }; bezierCurveTo(this, cp1, cp2, p); }; contextPrototype.arc = function(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { aRadius *= Z; var arcType = aClockwise ? 'at' : 'wa'; var xStart = aX + mc(aStartAngle) * aRadius - Z2; var yStart = aY + ms(aStartAngle) * aRadius - Z2; var xEnd = aX + mc(aEndAngle) * aRadius - Z2; var yEnd = aY + ms(aEndAngle) * aRadius - Z2; // IE won't render arches drawn counter clockwise if xStart == xEnd. if (xStart == xEnd && !aClockwise) { xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something // that can be represented in binary } var p = getCoords(this, aX, aY); var pStart = getCoords(this, xStart, yStart); var pEnd = getCoords(this, xEnd, yEnd); this.currentPath_.push({type: arcType, x: p.x, y: p.y, radius: aRadius, xStart: pStart.x, yStart: pStart.y, xEnd: pEnd.x, yEnd: pEnd.y}); }; contextPrototype.rect = function(aX, aY, aWidth, aHeight) { this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); }; contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.stroke(); this.currentPath_ = oldPath; }; contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.fill(); this.currentPath_ = oldPath; }; contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { var gradient = new CanvasGradient_('gradient'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.x1_ = aX1; gradient.y1_ = aY1; return gradient; }; contextPrototype.createRadialGradient = function(aX0, aY0, aR0, aX1, aY1, aR1) { var gradient = new CanvasGradient_('gradientradial'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.r0_ = aR0; gradient.x1_ = aX1; gradient.y1_ = aY1; gradient.r1_ = aR1; return gradient; }; contextPrototype.drawImage = function(image, var_args) { var dx, dy, dw, dh, sx, sy, sw, sh; // to find the original width we overide the width and height var oldRuntimeWidth = image.runtimeStyle.width; var oldRuntimeHeight = image.runtimeStyle.height; image.runtimeStyle.width = 'auto'; image.runtimeStyle.height = 'auto'; // get the original size var w = image.width; var h = image.height; // and remove overides image.runtimeStyle.width = oldRuntimeWidth; image.runtimeStyle.height = oldRuntimeHeight; if (arguments.length == 3) { dx = arguments[1]; dy = arguments[2]; sx = sy = 0; sw = dw = w; sh = dh = h; } else if (arguments.length == 5) { dx = arguments[1]; dy = arguments[2]; dw = arguments[3]; dh = arguments[4]; sx = sy = 0; sw = w; sh = h; } else if (arguments.length == 9) { sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else { throw Error('Invalid number of arguments'); } var d = getCoords(this, dx, dy); var w2 = sw / 2; var h2 = sh / 2; var vmlStr = []; var W = 10; var H = 10; // For some reason that I've now forgotten, using divs didn't work vmlStr.push(' <g_vml_:group', ' coordsize="', Z * W, ',', Z * H, '"', ' coordorigin="0,0"' , ' style="width:', W, 'px;height:', H, 'px;position:absolute;'); // If filters are necessary (rotation exists), create them // filters are bog-slow, so only create them if abbsolutely necessary // The following check doesn't account for skews (which don't exist // in the canvas spec (yet) anyway. if (this.m_[0][0] != 1 || this.m_[0][1] || this.m_[1][1] != 1 || this.m_[1][0]) { var filter = []; // Note the 12/21 reversal filter.push('M11=', this.m_[0][0], ',', 'M12=', this.m_[1][0], ',', 'M21=', this.m_[0][1], ',', 'M22=', this.m_[1][1], ',', 'Dx=', mr(d.x / Z), ',', 'Dy=', mr(d.y / Z), ''); // Bounding box calculation (need to minimize displayed area so that // filters don't waste time on unused pixels. var max = d; var c2 = getCoords(this, dx + dw, dy); var c3 = getCoords(this, dx, dy + dh); var c4 = getCoords(this, dx + dw, dy + dh); max.x = m.max(max.x, c2.x, c3.x, c4.x); max.y = m.max(max.y, c2.y, c3.y, c4.y); vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z), 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(', filter.join(''), ", sizingmethod='clip');"); } else { vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;'); } vmlStr.push(' ">' , '<g_vml_:image src="', image.src, '"', ' style="width:', Z * dw, 'px;', ' height:', Z * dh, 'px"', ' cropleft="', sx / w, '"', ' croptop="', sy / h, '"', ' cropright="', (w - sx - sw) / w, '"', ' cropbottom="', (h - sy - sh) / h, '"', ' />', '</g_vml_:group>'); this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); }; contextPrototype.stroke = function(aFill) { var W = 10; var H = 10; // Divide the shape into chunks if it's too long because IE has a limit // somewhere for how long a VML shape can be. This simple division does // not work with fills, only strokes, unfortunately. var chunkSize = 5000; var min = {x: null, y: null}; var max = {x: null, y: null}; for (var j = 0; j < this.currentPath_.length; j += chunkSize) { var lineStr = []; var lineOpen = false; lineStr.push('<g_vml_:shape', ' filled="', !!aFill, '"', ' style="position:absolute;width:', W, 'px;height:', H, 'px;"', ' coordorigin="0,0"', ' coordsize="', Z * W, ',', Z * H, '"', ' stroked="', !aFill, '"', ' path="'); var newSeq = false; for (var i = j; i < Math.min(j + chunkSize, this.currentPath_.length); i++) { if (i % chunkSize == 0 && i > 0) { // move into position for next chunk lineStr.push(' m ', mr(this.currentPath_[i-1].x), ',', mr(this.currentPath_[i-1].y)); } var p = this.currentPath_[i]; var c; switch (p.type) { case 'moveTo': c = p; lineStr.push(' m ', mr(p.x), ',', mr(p.y)); break; case 'lineTo': lineStr.push(' l ', mr(p.x), ',', mr(p.y)); break; case 'close': lineStr.push(' x '); p = null; break; case 'bezierCurveTo': lineStr.push(' c ', mr(p.cp1x), ',', mr(p.cp1y), ',', mr(p.cp2x), ',', mr(p.cp2y), ',', mr(p.x), ',', mr(p.y)); break; case 'at': case 'wa': lineStr.push(' ', p.type, ' ', mr(p.x - this.arcScaleX_ * p.radius), ',', mr(p.y - this.arcScaleY_ * p.radius), ' ', mr(p.x + this.arcScaleX_ * p.radius), ',', mr(p.y + this.arcScaleY_ * p.radius), ' ', mr(p.xStart), ',', mr(p.yStart), ' ', mr(p.xEnd), ',', mr(p.yEnd)); break; } // TODO: Following is broken for curves due to // move to proper paths. // Figure out dimensions so we can do gradient fills // properly if (p) { if (min.x == null || p.x < min.x) { min.x = p.x; } if (max.x == null || p.x > max.x) { max.x = p.x; } if (min.y == null || p.y < min.y) { min.y = p.y; } if (max.y == null || p.y > max.y) { max.y = p.y; } } } lineStr.push(' ">'); if (!aFill) { appendStroke(this, lineStr); } else { appendFill(this, lineStr, min, max); } lineStr.push('</g_vml_:shape>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); } }; function appendStroke(ctx, lineStr) { var a = processStyle(ctx.strokeStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; var lineWidth = ctx.lineScale_ * ctx.lineWidth; // VML cannot correctly render a line if the width is less than 1px. // In that case, we dilute the color to make the line look thinner. if (lineWidth < 1) { opacity *= lineWidth; } lineStr.push( '<g_vml_:stroke', ' opacity="', opacity, '"', ' joinstyle="', ctx.lineJoin, '"', ' miterlimit="', ctx.miterLimit, '"', ' endcap="', processLineCap(ctx.lineCap), '"', ' weight="', lineWidth, 'px"', ' color="', color, '" />' ); } function appendFill(ctx, lineStr, min, max) { var fillStyle = ctx.fillStyle; var arcScaleX = ctx.arcScaleX_; var arcScaleY = ctx.arcScaleY_; var width = max.x - min.x; var height = max.y - min.y; if (fillStyle instanceof CanvasGradient_) { // TODO: Gradients transformed with the transformation matrix. var angle = 0; var focus = {x: 0, y: 0}; // additional offset var shift = 0; // scale factor for offset var expansion = 1; if (fillStyle.type_ == 'gradient') { var x0 = fillStyle.x0_ / arcScaleX; var y0 = fillStyle.y0_ / arcScaleY; var x1 = fillStyle.x1_ / arcScaleX; var y1 = fillStyle.y1_ / arcScaleY; var p0 = getCoords(ctx, x0, y0); var p1 = getCoords(ctx, x1, y1); var dx = p1.x - p0.x; var dy = p1.y - p0.y; angle = Math.atan2(dx, dy) * 180 / Math.PI; // The angle should be a non-negative number. if (angle < 0) { angle += 360; } // Very small angles produce an unexpected result because they are // converted to a scientific notation string. if (angle < 1e-6) { angle = 0; } } else { var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); focus = { x: (p0.x - min.x) / width, y: (p0.y - min.y) / height }; width /= arcScaleX * Z; height /= arcScaleY * Z; var dimension = m.max(width, height); shift = 2 * fillStyle.r0_ / dimension; expansion = 2 * fillStyle.r1_ / dimension - shift; } // We need to sort the color stops in ascending order by offset, // otherwise IE won't interpret it correctly. var stops = fillStyle.colors_; stops.sort(function(cs1, cs2) { return cs1.offset - cs2.offset; }); var length = stops.length; var color1 = stops[0].color; var color2 = stops[length - 1].color; var opacity1 = stops[0].alpha * ctx.globalAlpha; var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; var colors = []; for (var i = 0; i < length; i++) { var stop = stops[i]; colors.push(stop.offset * expansion + shift + ' ' + stop.color); } // When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"', ' method="none" focus="100%"', ' color="', color1, '"', ' color2="', color2, '"', ' colors="', colors.join(','), '"', ' opacity="', opacity2, '"', ' g_o_:opacity2="', opacity1, '"', ' angle="', angle, '"', ' focusposition="', focus.x, ',', focus.y, '" />'); } else if (fillStyle instanceof CanvasPattern_) { if (width && height) { var deltaLeft = -min.x; var deltaTop = -min.y; lineStr.push('<g_vml_:fill', ' position="', deltaLeft / width * arcScaleX * arcScaleX, ',', deltaTop / height * arcScaleY * arcScaleY, '"', ' type="tile"', // TODO: Figure out the correct size to fit the scale. //' size="', w, 'px ', h, 'px"', ' src="', fillStyle.src_, '" />'); } } else { var a = processStyle(ctx.fillStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity, '" />'); } } contextPrototype.fill = function() { this.stroke(true); }; contextPrototype.closePath = function() { this.currentPath_.push({type: 'close'}); }; function getCoords(ctx, aX, aY) { var m = ctx.m_; return { x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 }; }; contextPrototype.save = function() { var o = {}; copyState(this, o); this.aStack_.push(o); this.mStack_.push(this.m_); this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); }; contextPrototype.restore = function() { if (this.aStack_.length) { copyState(this.aStack_.pop(), this); this.m_ = this.mStack_.pop(); } }; function matrixIsFinite(m) { return isFinite(m[0][0]) && isFinite(m[0][1]) && isFinite(m[1][0]) && isFinite(m[1][1]) && isFinite(m[2][0]) && isFinite(m[2][1]); } function setM(ctx, m, updateLineScale) { if (!matrixIsFinite(m)) { return; } ctx.m_ = m; if (updateLineScale) { // Get the line scale. // Determinant of this.m_ means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; ctx.lineScale_ = sqrt(abs(det)); } } contextPrototype.translate = function(aX, aY) { var m1 = [ [1, 0, 0], [0, 1, 0], [aX, aY, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.rotate = function(aRot) { var c = mc(aRot); var s = ms(aRot); var m1 = [ [c, s, 0], [-s, c, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.scale = function(aX, aY) { this.arcScaleX_ *= aX; this.arcScaleY_ *= aY; var m1 = [ [aX, 0, 0], [0, aY, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { var m1 = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { var m = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, m, true); }; /** * The text drawing function. * The maxWidth argument isn't taken in account, since no browser supports * it yet. */ contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { var m = this.m_, delta = 1000, left = 0, right = delta, offset = {x: 0, y: 0}, lineStr = []; var fontStyle = getComputedStyle(processFontStyle(this.font), this.element_); var fontStyleString = buildStyle(fontStyle); var elementStyle = this.element_.currentStyle; var textAlign = this.textAlign.toLowerCase(); switch (textAlign) { case 'left': case 'center': case 'right': break; case 'end': textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; break; case 'start': textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; break; default: textAlign = 'left'; } // 1.75 is an arbitrary number, as there is no info about the text baseline switch (this.textBaseline) { case 'hanging': case 'top': offset.y = fontStyle.size / 1.75; break; case 'middle': break; default: case null: case 'alphabetic': case 'ideographic': case 'bottom': offset.y = -fontStyle.size / 2.25; break; } switch(textAlign) { case 'right': left = delta; right = 0.05; break; case 'center': left = right = delta / 2; break; } var d = getCoords(this, x + offset.x, y + offset.y); lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ', ' coordsize="100 100" coordorigin="0 0"', ' filled="', !stroke, '" stroked="', !!stroke, '" style="position:absolute;width:1px;height:1px;">'); if (stroke) { appendStroke(this, lineStr); } else { // TODO: Fix the min and max params. appendFill(this, lineStr, {x: -left, y: 0}, {x: right, y: fontStyle.size}); } var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ', ' offset="', skewOffset, '" origin="', left ,' 0" />', '<g_vml_:path textpathok="true" />', '<g_vml_:textpath on="true" string="', encodeHtmlAttribute(text), '" style="v-text-align:', textAlign, ';font:', encodeHtmlAttribute(fontStyleString), '" /></g_vml_:line>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; contextPrototype.fillText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, false); }; contextPrototype.strokeText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, true); }; contextPrototype.measureText = function(text) { if (!this.textMeasureEl_) { var s = '<span style="position:absolute;' + 'top:-20000px;left:0;padding:0;margin:0;border:none;' + 'white-space:pre;"></span>'; this.element_.insertAdjacentHTML('beforeEnd', s); this.textMeasureEl_ = this.element_.lastChild; } var doc = this.element_.ownerDocument; this.textMeasureEl_.innerHTML = ''; this.textMeasureEl_.style.font = this.font; // Don't use innerHTML or innerText because they allow markup/whitespace. this.textMeasureEl_.appendChild(doc.createTextNode(text)); return {width: this.textMeasureEl_.offsetWidth}; }; /******** STUBS ********/ contextPrototype.clip = function() { // TODO: Implement }; contextPrototype.arcTo = function() { // TODO: Implement }; contextPrototype.createPattern = function(image, repetition) { return new CanvasPattern_(image, repetition); }; // Gradient / Pattern Stubs function CanvasGradient_(aType) { this.type_ = aType; this.x0_ = 0; this.y0_ = 0; this.r0_ = 0; this.x1_ = 0; this.y1_ = 0; this.r1_ = 0; this.colors_ = []; } CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { aColor = processStyle(aColor); this.colors_.push({offset: aOffset, color: aColor.color, alpha: aColor.alpha}); }; function CanvasPattern_(image, repetition) { assertImageIsValid(image); switch (repetition) { case 'repeat': case null: case '': this.repetition_ = 'repeat'; break case 'repeat-x': case 'repeat-y': case 'no-repeat': this.repetition_ = repetition; break; default: throwException('SYNTAX_ERR'); } this.src_ = image.src; this.width_ = image.width; this.height_ = image.height; } function throwException(s) { throw new DOMException_(s); } function assertImageIsValid(img) { if (!img || img.nodeType != 1 || img.tagName != 'IMG') { throwException('TYPE_MISMATCH_ERR'); } if (img.readyState != 'complete') { throwException('INVALID_STATE_ERR'); } } function DOMException_(s) { this.code = this[s]; this.message = s +': DOM Exception ' + this.code; } var p = DOMException_.prototype = new Error; p.INDEX_SIZE_ERR = 1; p.DOMSTRING_SIZE_ERR = 2; p.HIERARCHY_REQUEST_ERR = 3; p.WRONG_DOCUMENT_ERR = 4; p.INVALID_CHARACTER_ERR = 5; p.NO_DATA_ALLOWED_ERR = 6; p.NO_MODIFICATION_ALLOWED_ERR = 7; p.NOT_FOUND_ERR = 8; p.NOT_SUPPORTED_ERR = 9; p.INUSE_ATTRIBUTE_ERR = 10; p.INVALID_STATE_ERR = 11; p.SYNTAX_ERR = 12; p.INVALID_MODIFICATION_ERR = 13; p.NAMESPACE_ERR = 14; p.INVALID_ACCESS_ERR = 15; p.VALIDATION_ERR = 16; p.TYPE_MISMATCH_ERR = 17; // set up externs G_vmlCanvasManager = G_vmlCanvasManager_; CanvasRenderingContext2D = CanvasRenderingContext2D_; CanvasGradient = CanvasGradient_; CanvasPattern = CanvasPattern_; DOMException = DOMException_; })(); } // if
JavaScript
/* Flot plugin for computing bottoms for filled line and bar charts. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The case: you've got two series that you want to fill the area between. In Flot terms, you need to use one as the fill bottom of the other. You can specify the bottom of each data point as the third coordinate manually, or you can use this plugin to compute it for you. In order to name the other series, you need to give it an id, like this: var dataset = [ { data: [ ... ], id: "foo" } , // use default bottom { data: [ ... ], fillBetween: "foo" }, // use first dataset as bottom ]; $.plot($("#placeholder"), dataset, { lines: { show: true, fill: true }}); As a convenience, if the id given is a number that doesn't appear as an id in the series, it is interpreted as the index in the array instead (so fillBetween: 0 can also mean the first series). Internally, the plugin modifies the datapoints in each series. For line series, extra data points might be inserted through interpolation. Note that at points where the bottom line is not defined (due to a null point or start/end of line), the current line will show a gap too. The algorithm comes from the jquery.flot.stack.js plugin, possibly some code could be shared. */ (function ( $ ) { var options = { series: { fillBetween: null // or number } }; function init( plot ) { function findBottomSeries( s, allseries ) { var i; for ( i = 0; i < allseries.length; ++i ) { if ( allseries[ i ].id === s.fillBetween ) { return allseries[ i ]; } } if ( typeof s.fillBetween === "number" ) { if ( s.fillBetween < 0 || s.fillBetween >= allseries.length ) { return null; } return allseries[ s.fillBetween ]; } return null; } function computeFillBottoms( plot, s, datapoints ) { if ( s.fillBetween == null ) { return; } var other = findBottomSeries( s, plot.getData() ); if ( !other ) { return; } var ps = datapoints.pointsize, points = datapoints.points, otherps = other.datapoints.pointsize, otherpoints = other.datapoints.points, newpoints = [], px, py, intery, qx, qy, bottom, withlines = s.lines.show, withbottom = ps > 2 && datapoints.format[2].y, withsteps = withlines && s.lines.steps, fromgap = true, i = 0, j = 0, l, m; while ( true ) { if ( i >= points.length ) { break; } l = newpoints.length; if ( points[ i ] == null ) { // copy gaps for ( m = 0; m < ps; ++m ) { newpoints.push( points[ i + m ] ); } i += ps; } else if ( j >= otherpoints.length ) { // for lines, we can't use the rest of the points if ( !withlines ) { for ( m = 0; m < ps; ++m ) { newpoints.push( points[ i + m ] ); } } i += ps; } else if ( otherpoints[ j ] == null ) { // oops, got a gap for ( m = 0; m < ps; ++m ) { newpoints.push( null ); } fromgap = true; j += otherps; } else { // cases where we actually got two points px = points[ i ]; py = points[ i + 1 ]; qx = otherpoints[ j ]; qy = otherpoints[ j + 1 ]; bottom = 0; if ( px === qx ) { for ( m = 0; m < ps; ++m ) { newpoints.push( points[ i + m ] ); } //newpoints[ l + 1 ] += qy; bottom = qy; i += ps; j += otherps; } else if ( px > qx ) { // we got past point below, might need to // insert interpolated extra point if ( withlines && i > 0 && points[ i - ps ] != null ) { intery = py + ( points[ i - ps + 1 ] - py ) * ( qx - px ) / ( points[ i - ps ] - px ); newpoints.push( qx ); newpoints.push( intery ); for ( m = 2; m < ps; ++m ) { newpoints.push( points[ i + m ] ); } bottom = qy; } j += otherps; } else { // px < qx // if we come from a gap, we just skip this point if ( fromgap && withlines ) { i += ps; continue; } for ( m = 0; m < ps; ++m ) { newpoints.push( points[ i + m ] ); } // we might be able to interpolate a point below, // this can give us a better y if ( withlines && j > 0 && otherpoints[ j - otherps ] != null ) { bottom = qy + ( otherpoints[ j - otherps + 1 ] - qy ) * ( px - qx ) / ( otherpoints[ j - otherps ] - qx ); } //newpoints[l + 1] += bottom; i += ps; } fromgap = false; if ( l !== newpoints.length && withbottom ) { newpoints[ l + 2 ] = bottom; } } // maintain the line steps invariant if ( withsteps && l !== newpoints.length && l > 0 && newpoints[ l ] !== null && newpoints[ l ] !== newpoints[ l - ps ] && newpoints[ l + 1 ] !== newpoints[ l - ps + 1 ] ) { for (m = 0; m < ps; ++m) { newpoints[ l + ps + m ] = newpoints[ l + m ]; } newpoints[ l + 1 ] = newpoints[ l - ps + 1 ]; } } datapoints.points = newpoints; } plot.hooks.processDatapoints.push( computeFillBottoms ); } $.plot.plugins.push({ init: init, options: options, name: "fillbetween", version: "1.0" }); })(jQuery);
JavaScript
/* Flot plugin for rendering pie charts. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The plugin assumes that each series has a single data value, and that each value is a positive integer or zero. Negative numbers don't make sense for a pie chart, and have unpredictable results. The values do NOT need to be passed in as percentages; the plugin will calculate the total and per-slice percentages internally. * Created by Brian Medendorp * Updated with contributions from btburnett3, Anthony Aragues and Xavi Ivars The plugin supports these options: series: { pie: { show: true/false radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto' innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show) offset: { top: integer value to move the pie up or down left: integer value to move the pie left or right, or 'auto' }, stroke: { color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF') width: integer pixel width of the stroke }, label: { show: true/false, or 'auto' formatter: a user-defined function that modifies the text/style of the label text radius: 0-1 for percentage of fullsize, or a specified pixel length background: { color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000') opacity: 0-1 }, threshold: 0-1 for the percentage value at which to hide labels (if they're too small) }, combine: { threshold: 0-1 for the percentage value at which to combine slices (if they're too small) color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined label: any text value of what the combined slice should be labeled } highlight: { opacity: 0-1 } } } More detail and specific examples can be found in the included HTML file. */ (function($) { // Maximum redraw attempts when fitting labels within the plot var REDRAW_ATTEMPTS = 10; // Factor by which to shrink the pie when fitting labels within the plot var REDRAW_SHRINK = 0.95; function init(plot) { var canvas = null, target = null, maxRadius = null, centerLeft = null, centerTop = null, processed = false, ctx = null; // interactive variables var highlights = []; // add hook to determine if pie plugin in enabled, and then perform necessary operations plot.hooks.processOptions.push(function(plot, options) { if (options.series.pie.show) { options.grid.show = false; // set labels.show if (options.series.pie.label.show == "auto") { if (options.legend.show) { options.series.pie.label.show = false; } else { options.series.pie.label.show = true; } } // set radius if (options.series.pie.radius == "auto") { if (options.series.pie.label.show) { options.series.pie.radius = 3/4; } else { options.series.pie.radius = 1; } } // ensure sane tilt if (options.series.pie.tilt > 1) { options.series.pie.tilt = 1; } else if (options.series.pie.tilt < 0) { options.series.pie.tilt = 0; } } }); plot.hooks.bindEvents.push(function(plot, eventHolder) { var options = plot.getOptions(); if (options.series.pie.show) { if (options.grid.hoverable) { eventHolder.unbind("mousemove").mousemove(onMouseMove); } if (options.grid.clickable) { eventHolder.unbind("click").click(onClick); } } }); plot.hooks.processDatapoints.push(function(plot, series, data, datapoints) { var options = plot.getOptions(); if (options.series.pie.show) { processDatapoints(plot, series, data, datapoints); } }); plot.hooks.drawOverlay.push(function(plot, octx) { var options = plot.getOptions(); if (options.series.pie.show) { drawOverlay(plot, octx); } }); plot.hooks.draw.push(function(plot, newCtx) { var options = plot.getOptions(); if (options.series.pie.show) { draw(plot, newCtx); } }); function processDatapoints(plot, series, datapoints) { if (!processed) { processed = true; canvas = plot.getCanvas(); target = $(canvas).parent(); options = plot.getOptions(); plot.setData(combine(plot.getData())); } } function combine(data) { var total = 0, combined = 0, numCombined = 0, color = options.series.pie.combine.color, newdata = []; // Fix up the raw data from Flot, ensuring the data is numeric for (var i = 0; i < data.length; ++i) { var value = data[i].data; // If the data is an array, we'll assume that it's a standard // Flot x-y pair, and are concerned only with the second value. // Note how we use the original array, rather than creating a // new one; this is more efficient and preserves any extra data // that the user may have stored in higher indexes. if ($.isArray(value) && value.length == 1) { value = value[0]; } if ($.isArray(value)) { // Equivalent to $.isNumeric() but compatible with jQuery < 1.7 if (!isNaN(parseFloat(value[1])) && isFinite(value[1])) { value[1] = +value[1]; } else { value[1] = 0; } } else if (!isNaN(parseFloat(value)) && isFinite(value)) { value = [1, +value]; } else { value = [1, 0]; } data[i].data = [value]; } // Sum up all the slices, so we can calculate percentages for each for (var i = 0; i < data.length; ++i) { total += data[i].data[0][1]; } // Count the number of slices with percentages below the combine // threshold; if it turns out to be just one, we won't combine. for (var i = 0; i < data.length; ++i) { var value = data[i].data[0][1]; if (value / total <= options.series.pie.combine.threshold) { combined += value; numCombined++; if (!color) { color = data[i].color; } } } for (var i = 0; i < data.length; ++i) { var value = data[i].data[0][1]; if (numCombined < 2 || value / total > options.series.pie.combine.threshold) { newdata.push({ data: [[1, value]], color: data[i].color, label: data[i].label, angle: value * Math.PI * 2 / total, percent: value / (total / 100) }); } } if (numCombined > 1) { newdata.push({ data: [[1, combined]], color: color, label: options.series.pie.combine.label, angle: combined * Math.PI * 2 / total, percent: combined / (total / 100) }); } return newdata; } function draw(plot, newCtx) { if (!target) { return; // if no series were passed } var canvasWidth = plot.getPlaceholder().width(), canvasHeight = plot.getPlaceholder().height(), legendWidth = target.children().filter(".legend").children().width() || 0; ctx = newCtx; // WARNING: HACK! REWRITE THIS CODE AS SOON AS POSSIBLE! // When combining smaller slices into an 'other' slice, we need to // add a new series. Since Flot gives plugins no way to modify the // list of series, the pie plugin uses a hack where the first call // to processDatapoints results in a call to setData with the new // list of series, then subsequent processDatapoints do nothing. // The plugin-global 'processed' flag is used to control this hack; // it starts out false, and is set to true after the first call to // processDatapoints. // Unfortunately this turns future setData calls into no-ops; they // call processDatapoints, the flag is true, and nothing happens. // To fix this we'll set the flag back to false here in draw, when // all series have been processed, so the next sequence of calls to // processDatapoints once again starts out with a slice-combine. // This is really a hack; in 0.9 we need to give plugins a proper // way to modify series before any processing begins. processed = false; // calculate maximum radius and center point maxRadius = Math.min(canvasWidth, canvasHeight / options.series.pie.tilt) / 2; centerTop = canvasHeight / 2 + options.series.pie.offset.top; centerLeft = canvasWidth / 2; if (options.series.pie.offset.left == "auto") { if (options.legend.position.match("w")) { centerLeft += legendWidth / 2; } else { centerLeft -= legendWidth / 2; } } else { centerLeft += options.series.pie.offset.left; } if (centerLeft < maxRadius) { centerLeft = maxRadius; } else if (centerLeft > canvasWidth - maxRadius) { centerLeft = canvasWidth - maxRadius; } var slices = plot.getData(), attempts = 0; // Keep shrinking the pie's radius until drawPie returns true, // indicating that all the labels fit, or we try too many times. do { if (attempts > 0) { maxRadius *= REDRAW_SHRINK; } attempts += 1; clear(); if (options.series.pie.tilt <= 0.8) { drawShadow(); } } while (!drawPie() && attempts < REDRAW_ATTEMPTS) if (attempts >= REDRAW_ATTEMPTS) { clear(); target.prepend("<div class='error'>Could not draw pie with labels contained inside canvas</div>"); } if (plot.setSeries && plot.insertLegend) { plot.setSeries(slices); plot.insertLegend(); } // we're actually done at this point, just defining internal functions at this point function clear() { ctx.clearRect(0, 0, canvasWidth, canvasHeight); target.children().filter(".pieLabel, .pieLabelBackground").remove(); } function drawShadow() { var shadowLeft = options.series.pie.shadow.left; var shadowTop = options.series.pie.shadow.top; var edge = 10; var alpha = options.series.pie.shadow.alpha; var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; if (radius >= canvasWidth / 2 - shadowLeft || radius * options.series.pie.tilt >= canvasHeight / 2 - shadowTop || radius <= edge) { return; // shadow would be outside canvas, so don't draw it } ctx.save(); ctx.translate(shadowLeft,shadowTop); ctx.globalAlpha = alpha; ctx.fillStyle = "#000"; // center and rotate to starting position ctx.translate(centerLeft,centerTop); ctx.scale(1, options.series.pie.tilt); //radius -= edge; for (var i = 1; i <= edge; i++) { ctx.beginPath(); ctx.arc(0, 0, radius, 0, Math.PI * 2, false); ctx.fill(); radius -= i; } ctx.restore(); } function drawPie() { var startAngle = Math.PI * options.series.pie.startAngle; var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; // center and rotate to starting position ctx.save(); ctx.translate(centerLeft,centerTop); ctx.scale(1, options.series.pie.tilt); //ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera // draw slices ctx.save(); var currentAngle = startAngle; for (var i = 0; i < slices.length; ++i) { slices[i].startAngle = currentAngle; drawSlice(slices[i].angle, slices[i].color, true); } ctx.restore(); // draw slice outlines if (options.series.pie.stroke.width > 0) { ctx.save(); ctx.lineWidth = options.series.pie.stroke.width; currentAngle = startAngle; for (var i = 0; i < slices.length; ++i) { drawSlice(slices[i].angle, options.series.pie.stroke.color, false); } ctx.restore(); } // draw donut hole drawDonutHole(ctx); ctx.restore(); // Draw the labels, returning true if they fit within the plot if (options.series.pie.label.show) { return drawLabels(); } else return true; function drawSlice(angle, color, fill) { if (angle <= 0 || isNaN(angle)) { return; } if (fill) { ctx.fillStyle = color; } else { ctx.strokeStyle = color; ctx.lineJoin = "round"; } ctx.beginPath(); if (Math.abs(angle - Math.PI * 2) > 0.000000001) { ctx.moveTo(0, 0); // Center of the pie } //ctx.arc(0, 0, radius, 0, angle, false); // This doesn't work properly in Opera ctx.arc(0, 0, radius,currentAngle, currentAngle + angle / 2, false); ctx.arc(0, 0, radius,currentAngle + angle / 2, currentAngle + angle, false); ctx.closePath(); //ctx.rotate(angle); // This doesn't work properly in Opera currentAngle += angle; if (fill) { ctx.fill(); } else { ctx.stroke(); } } function drawLabels() { var currentAngle = startAngle; var radius = options.series.pie.label.radius > 1 ? options.series.pie.label.radius : maxRadius * options.series.pie.label.radius; for (var i = 0; i < slices.length; ++i) { if (slices[i].percent >= options.series.pie.label.threshold * 100) { if (!drawLabel(slices[i], currentAngle, i)) { return false; } } currentAngle += slices[i].angle; } return true; function drawLabel(slice, startAngle, index) { if (slice.data[0][1] == 0) { return true; } // format label text var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter; if (lf) { text = lf(slice.label, slice); } else { text = slice.label; } if (plf) { text = plf(text, slice); } var halfAngle = ((startAngle + slice.angle) + startAngle) / 2; var x = centerLeft + Math.round(Math.cos(halfAngle) * radius); var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt; var html = "<span class='pieLabel' id='pieLabel" + index + "' style='position:absolute;top:" + y + "px;left:" + x + "px;'>" + text + "</span>"; target.append(html); var label = target.children("#pieLabel" + index); var labelTop = (y - label.height() / 2); var labelLeft = (x - label.width() / 2); label.css("top", labelTop); label.css("left", labelLeft); // check to make sure that the label is not outside the canvas if (0 - labelTop > 0 || 0 - labelLeft > 0 || canvasHeight - (labelTop + label.height()) < 0 || canvasWidth - (labelLeft + label.width()) < 0) { return false; } if (options.series.pie.label.background.opacity != 0) { // put in the transparent background separately to avoid blended labels and label boxes var c = options.series.pie.label.background.color; if (c == null) { c = slice.color; } var pos = "top:" + labelTop + "px;left:" + labelLeft + "px;"; $("<div class='pieLabelBackground' style='position:absolute;width:" + label.width() + "px;height:" + label.height() + "px;" + pos + "background-color:" + c + ";'></div>") .css("opacity", options.series.pie.label.background.opacity) .insertBefore(label); } return true; } // end individual label function } // end drawLabels function } // end drawPie function } // end draw function // Placed here because it needs to be accessed from multiple locations function drawDonutHole(layer) { if (options.series.pie.innerRadius > 0) { // subtract the center layer.save(); var innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius; layer.globalCompositeOperation = "destination-out"; // this does not work with excanvas, but it will fall back to using the stroke color layer.beginPath(); layer.fillStyle = options.series.pie.stroke.color; layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false); layer.fill(); layer.closePath(); layer.restore(); // add inner stroke layer.save(); layer.beginPath(); layer.strokeStyle = options.series.pie.stroke.color; layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false); layer.stroke(); layer.closePath(); layer.restore(); // TODO: add extra shadow inside hole (with a mask) if the pie is tilted. } } //-- Additional Interactive related functions -- function isPointInPoly(poly, pt) { for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i) ((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || (poly[j][1] <= pt[1] && pt[1]< poly[i][1])) && (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0]) && (c = !c); return c; } function findNearbySlice(mouseX, mouseY) { var slices = plot.getData(), options = plot.getOptions(), radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius, x, y; for (var i = 0; i < slices.length; ++i) { var s = slices[i]; if (s.pie.show) { ctx.save(); ctx.beginPath(); ctx.moveTo(0, 0); // Center of the pie //ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here. ctx.arc(0, 0, radius, s.startAngle, s.startAngle + s.angle / 2, false); ctx.arc(0, 0, radius, s.startAngle + s.angle / 2, s.startAngle + s.angle, false); ctx.closePath(); x = mouseX - centerLeft; y = mouseY - centerTop; if (ctx.isPointInPath) { if (ctx.isPointInPath(mouseX - centerLeft, mouseY - centerTop)) { ctx.restore(); return { datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i }; } } else { // excanvas for IE doesn;t support isPointInPath, this is a workaround. var p1X = radius * Math.cos(s.startAngle), p1Y = radius * Math.sin(s.startAngle), p2X = radius * Math.cos(s.startAngle + s.angle / 4), p2Y = radius * Math.sin(s.startAngle + s.angle / 4), p3X = radius * Math.cos(s.startAngle + s.angle / 2), p3Y = radius * Math.sin(s.startAngle + s.angle / 2), p4X = radius * Math.cos(s.startAngle + s.angle / 1.5), p4Y = radius * Math.sin(s.startAngle + s.angle / 1.5), p5X = radius * Math.cos(s.startAngle + s.angle), p5Y = radius * Math.sin(s.startAngle + s.angle), arrPoly = [[0, 0], [p1X, p1Y], [p2X, p2Y], [p3X, p3Y], [p4X, p4Y], [p5X, p5Y]], arrPoint = [x, y]; // TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt? if (isPointInPoly(arrPoly, arrPoint)) { ctx.restore(); return { datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i }; } } ctx.restore(); } } return null; } function onMouseMove(e) { triggerClickHoverEvent("plothover", e); } function onClick(e) { triggerClickHoverEvent("plotclick", e); } // trigger click or hover event (they send the same parameters so we share their code) function triggerClickHoverEvent(eventname, e) { var offset = plot.offset(); var canvasX = parseInt(e.pageX - offset.left); var canvasY = parseInt(e.pageY - offset.top); var item = findNearbySlice(canvasX, canvasY); if (options.grid.autoHighlight) { // clear auto-highlights for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.auto == eventname && !(item && h.series == item.series)) { unhighlight(h.series); } } } // highlight the slice if (item) { highlight(item.series, eventname); } // trigger any hover bind events var pos = { pageX: e.pageX, pageY: e.pageY }; target.trigger(eventname, [pos, item]); } function highlight(s, auto) { //if (typeof s == "number") { // s = series[s]; //} var i = indexOfHighlight(s); if (i == -1) { highlights.push({ series: s, auto: auto }); plot.triggerRedrawOverlay(); } else if (!auto) { highlights[i].auto = false; } } function unhighlight(s) { if (s == null) { highlights = []; plot.triggerRedrawOverlay(); } //if (typeof s == "number") { // s = series[s]; //} var i = indexOfHighlight(s); if (i != -1) { highlights.splice(i, 1); plot.triggerRedrawOverlay(); } } function indexOfHighlight(s) { for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.series == s) return i; } return -1; } function drawOverlay(plot, octx) { var options = plot.getOptions(); var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; octx.save(); octx.translate(centerLeft, centerTop); octx.scale(1, options.series.pie.tilt); for (var i = 0; i < highlights.length; ++i) { drawHighlight(highlights[i].series); } drawDonutHole(octx); octx.restore(); function drawHighlight(series) { if (series.angle <= 0 || isNaN(series.angle)) { return; } //octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString(); octx.fillStyle = "rgba(255, 255, 255, " + options.series.pie.highlight.opacity + ")"; // this is temporary until we have access to parseColor octx.beginPath(); if (Math.abs(series.angle - Math.PI * 2) > 0.000000001) { octx.moveTo(0, 0); // Center of the pie } octx.arc(0, 0, radius, series.startAngle, series.startAngle + series.angle / 2, false); octx.arc(0, 0, radius, series.startAngle + series.angle / 2, series.startAngle + series.angle, false); octx.closePath(); octx.fill(); } } } // end init (plugin body) // define pie specific options and their default values var options = { series: { pie: { show: false, radius: "auto", // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value) innerRadius: 0, /* for donut */ startAngle: 3/2, tilt: 1, shadow: { left: 5, // shadow left offset top: 15, // shadow top offset alpha: 0.02 // shadow alpha }, offset: { top: 0, left: "auto" }, stroke: { color: "#fff", width: 1 }, label: { show: "auto", formatter: function(label, slice) { return "<div style='font-size:x-small;text-align:center;padding:2px;color:" + slice.color + ";'>" + label + "<br/>" + Math.round(slice.percent) + "%</div>"; }, // formatter function radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value) background: { color: null, opacity: 0 }, threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow) }, combine: { threshold: -1, // percentage at which to combine little slices into one larger slice color: null, // color to give the new slice (auto-generated if null) label: "Other" // label to give the new slice }, highlight: { //color: "#fff", // will add this functionality once parseColor is available opacity: 0.5 } } } }; $.plot.plugins.push({ init: init, options: options, name: "pie", version: "1.1" }); })(jQuery);
JavaScript
/* Flot plugin for plotting images. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The data syntax is [ [ image, x1, y1, x2, y2 ], ... ] where (x1, y1) and (x2, y2) are where you intend the two opposite corners of the image to end up in the plot. Image must be a fully loaded Javascript image (you can make one with new Image()). If the image is not complete, it's skipped when plotting. There are two helpers included for retrieving images. The easiest work the way that you put in URLs instead of images in the data, like this: [ "myimage.png", 0, 0, 10, 10 ] Then call $.plot.image.loadData( data, options, callback ) where data and options are the same as you pass in to $.plot. This loads the images, replaces the URLs in the data with the corresponding images and calls "callback" when all images are loaded (or failed loading). In the callback, you can then call $.plot with the data set. See the included example. A more low-level helper, $.plot.image.load(urls, callback) is also included. Given a list of URLs, it calls callback with an object mapping from URL to Image object when all images are loaded or have failed loading. The plugin supports these options: series: { images: { show: boolean anchor: "corner" or "center" alpha: [ 0, 1 ] } } They can be specified for a specific series: $.plot( $("#placeholder"), [{ data: [ ... ], images: { ... } ]) Note that because the data format is different from usual data points, you can't use images with anything else in a specific data series. Setting "anchor" to "center" causes the pixels in the image to be anchored at the corner pixel centers inside of at the pixel corners, effectively letting half a pixel stick out to each side in the plot. A possible future direction could be support for tiling for large images (like Google Maps). */ (function ($) { var options = { series: { images: { show: false, alpha: 1, anchor: "corner" // or "center" } } }; $.plot.image = {}; $.plot.image.loadDataImages = function (series, options, callback) { var urls = [], points = []; var defaultShow = options.series.images.show; $.each(series, function (i, s) { if (!(defaultShow || s.images.show)) return; if (s.data) s = s.data; $.each(s, function (i, p) { if (typeof p[0] == "string") { urls.push(p[0]); points.push(p); } }); }); $.plot.image.load(urls, function (loadedImages) { $.each(points, function (i, p) { var url = p[0]; if (loadedImages[url]) p[0] = loadedImages[url]; }); callback(); }); } $.plot.image.load = function (urls, callback) { var missing = urls.length, loaded = {}; if (missing == 0) callback({}); $.each(urls, function (i, url) { var handler = function () { --missing; loaded[url] = this; if (missing == 0) callback(loaded); }; $('<img />').load(handler).error(handler).attr('src', url); }); }; function drawSeries(plot, ctx, series) { var plotOffset = plot.getPlotOffset(); if (!series.images || !series.images.show) return; var points = series.datapoints.points, ps = series.datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { var img = points[i], x1 = points[i + 1], y1 = points[i + 2], x2 = points[i + 3], y2 = points[i + 4], xaxis = series.xaxis, yaxis = series.yaxis, tmp; // actually we should check img.complete, but it // appears to be a somewhat unreliable indicator in // IE6 (false even after load event) if (!img || img.width <= 0 || img.height <= 0) continue; if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } // if the anchor is at the center of the pixel, expand the // image by 1/2 pixel in each direction if (series.images.anchor == "center") { tmp = 0.5 * (x2-x1) / (img.width - 1); x1 -= tmp; x2 += tmp; tmp = 0.5 * (y2-y1) / (img.height - 1); y1 -= tmp; y2 += tmp; } // clip if (x1 == x2 || y1 == y2 || x1 >= xaxis.max || x2 <= xaxis.min || y1 >= yaxis.max || y2 <= yaxis.min) continue; var sx1 = 0, sy1 = 0, sx2 = img.width, sy2 = img.height; if (x1 < xaxis.min) { sx1 += (sx2 - sx1) * (xaxis.min - x1) / (x2 - x1); x1 = xaxis.min; } if (x2 > xaxis.max) { sx2 += (sx2 - sx1) * (xaxis.max - x2) / (x2 - x1); x2 = xaxis.max; } if (y1 < yaxis.min) { sy2 += (sy1 - sy2) * (yaxis.min - y1) / (y2 - y1); y1 = yaxis.min; } if (y2 > yaxis.max) { sy1 += (sy1 - sy2) * (yaxis.max - y2) / (y2 - y1); y2 = yaxis.max; } x1 = xaxis.p2c(x1); x2 = xaxis.p2c(x2); y1 = yaxis.p2c(y1); y2 = yaxis.p2c(y2); // the transformation may have swapped us if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } tmp = ctx.globalAlpha; ctx.globalAlpha *= series.images.alpha; ctx.drawImage(img, sx1, sy1, sx2 - sx1, sy2 - sy1, x1 + plotOffset.left, y1 + plotOffset.top, x2 - x1, y2 - y1); ctx.globalAlpha = tmp; } } function processRawData(plot, series, data, datapoints) { if (!series.images.show) return; // format is Image, x1, y1, x2, y2 (opposite corners) datapoints.format = [ { required: true }, { x: true, number: true, required: true }, { y: true, number: true, required: true }, { x: true, number: true, required: true }, { y: true, number: true, required: true } ]; } function init(plot) { plot.hooks.processRawData.push(processRawData); plot.hooks.drawSeries.push(drawSeries); } $.plot.plugins.push({ init: init, options: options, name: 'image', version: '1.1' }); })(jQuery);
JavaScript
// ------------------------------ // Sidebar Accordion Menu // ------------------------------ $(function () { //if($.cookie('admin_leftbar_collapse') === 'collapse-leftbar') { // $('body').addClass('collapse-leftbar'); //} else { // $('body').removeClass('collapse-leftbar'); //} $('body').on('click', 'ul.acc-menu a', function() { var LIs = $(this).closest('ul.acc-menu').children('li'); $(this).closest('li').addClass('clicked'); $.each( LIs, function(i) { if( $(LIs[i]).hasClass('clicked') ) { $(LIs[i]).removeClass('clicked'); return true; } if($.cookie('admin_leftbar_collapse') !== 'collapse-leftbar' || $(this).parents('.acc-menu').length > 1) $(LIs[i]).find('ul.acc-menu:visible').slideToggle(); $(LIs[i]).removeClass('open'); }); if($(this).siblings('ul.acc-menu:visible').length>0) $(this).closest('li').removeClass('open'); else $(this).closest('li').addClass('open'); if($.cookie('admin_leftbar_collapse') !== 'collapse-leftbar' || $(this).parents('.acc-menu').length > 1) $(this).siblings('ul.acc-menu').slideToggle({ duration: 200, progress: function(){ checkpageheight(); if ($(this).closest('li').is(":last-child")) { //only scroll down if last-child $("#sidebar").animate({ scrollTop: $("#sidebar").height()},0); } }, complete: function(){ $("#sidebar").getNiceScroll().resize(); } }); }); var targetAnchor; $.each ($('ul.acc-menu a'), function() { //console.log(this.href); if( this.href == window.location ) { targetAnchor = this; return false; } }); var parent = $(targetAnchor).closest('li'); while(true) { parent.addClass('active'); parent.closest('ul.acc-menu').show().closest('li').addClass('open'); parent = $(parent).parents('li').eq(0); if( $(parent).parents('ul.acc-menu').length <= 0 ) break; } var liHasUlChild = $('li').filter(function(){ return $(this).find('ul.acc-menu').length; }); $(liHasUlChild).addClass('hasChild'); if($.cookie('admin_leftbar_collapse') === 'collapse-leftbar') { $('ul.acc-menu:first ul.acc-menu').css('visibility', 'hidden'); } $('ul.acc-menu:first > li').hover(function() { if($.cookie('admin_leftbar_collapse') === 'collapse-leftbar') $(this).find('ul.acc-menu').css('visibility', ''); }, function() { if($.cookie('admin_leftbar_collapse') === 'collapse-leftbar') $(this).find('ul.acc-menu').css('visibility', 'hidden'); }); // Reads Cookie for Collapsible Leftbar // if($.cookie('admin_leftbar_collapse') === 'collapse-leftbar') // $("body").addClass("collapse-leftbar"); //Make only visible area scrollable $("#widgetarea").css({"max-height":$("body").height()}); //Bind widgetarea to nicescroll $("#widgetarea").niceScroll({horizrailenabled:false}); //Will open menu if it has link //$('.hasChild.active ul.acc-menu').slideToggle({duration: 200}); // Toggle Buttons // ------------------------------ //On click of left menu $("a#leftmenu-trigger").click(function () { if ((window.innerWidth)<768) { $("body").toggleClass("show-leftbar"); } else { $("body").toggleClass("collapse-leftbar"); //Sets Cookie for Toggle if($.cookie('admin_leftbar_collapse') === 'collapse-leftbar') { $.cookie('admin_leftbar_collapse', ''); $('ul.acc-menu').css('visibility', ''); } else { $.each($('.acc-menu'), function() { if($(this).css('display') == 'none') $(this).css('display', ''); }); $('ul.acc-menu:first ul.acc-menu').css('visibility', 'hidden'); $.cookie('admin_leftbar_collapse', 'collapse-leftbar'); } } checkpageheight(); leftbarScrollShow(); }); // On click of right menu $("a#rightmenu-trigger").click(function () { $("body").toggleClass("show-rightbar"); widgetheight(); if($.cookie('admin_rightbar_show') === 'show-rightbar') $.cookie('admin_rightbar_show', ''); else $.cookie('admin_rightbar_show', 'show-rightbar'); }); //set minimum height of page dh=($(document).height()-40); $("#page-content").css("min-height",dh+"px"); //checkpageheight(); }); // Recalculate widget area on a widget being shown $(".widget-body").on('shown.bs.collapse', function () { widgetheight(); }); // ------------------------------- // Sidebars Positionings // ------------------------------- $(window).scroll(function(){ $("#widgetarea").getNiceScroll().resize(); $(".chathistory").getNiceScroll().resize(); rightbarTopPos(); leftbarTopPos(); }); $(window).resize(function(){ widgetheight(); rightbarRightPos(); $("#sidebar").getNiceScroll().resize(); }); rightbarRightPos(); // ------------------------------- // Mobile Only - set sidebar as fixed position, slide // ------------------------------- enquire.register("screen and (max-width: 767px)", { match : function() { // For less than 768px $(function() { //Bind sidebar to nicescroll $("#sidebar").niceScroll({horizrailenabled:false}); leftbarScrollShow(); //Click on body and hide leftbar $("#wrap").click(function(){ if ($("body").hasClass("show-leftbar")) { $("body").removeClass("show-leftbar"); leftbarScrollShow(); } }); //Fix a bug $('#sidebar ul.acc-menu').css('visibility', ''); //open up leftbar $("body").removeClass("show-leftbar"); $.removeCookie("admin_leftbar_collapse"); $("body").removeClass("collapse-leftbar"); }); console.log("match"); }, unmatch : function() { //Remove nicescroll to clear up some memory $("#sidebar").niceScroll().remove(); $("#sidebar").css("overflow","visible"); console.log("unmatch"); //hide leftbar $("body").removeClass("show-leftbar"); } }); //Helper functions //--------------- //Fixing the show of scroll rails even when sidebar is hidden function leftbarScrollShow () { if ($("body").hasClass("show-leftbar")) { $("#sidebar").getNiceScroll().show(); } else { $("#sidebar").getNiceScroll().hide(); } $("#sidebar").getNiceScroll().resize(); } //set Top positions for changing between static and fixed header function leftbarTopPos() { var scr=$('body.static-header').scrollTop(); if (scr<41) {$('ul#sidebar').css('top',40-scr + 'px');} else {$('ul#sidebar').css('top',0);} } function rightbarTopPos() { var scr=$('body.static-header').scrollTop(); if (scr<41) {$('#page-rightbar').css('top',40-scr + 'px');} else {$('#page-rightbar').css('top',0);} } //Set Right position for fixed layouts function rightbarRightPos () { if ($('body').hasClass('fixed-layout')) { var $pc = $('#page-content'); var ending_right = ($(window).width() - ($pc.offset().left + $pc.outerWidth())); if (ending_right<0) ending_right=0; $('#page-rightbar').css('right',ending_right); } } // Match page height with Sidebar Height function checkpageheight() { sh=$("#page-leftbar").height(); ch=$("#page-content").height(); if (sh>ch) $("#page-content").css("min-height",sh+"px"); } // Recalculate widget area to area visible function widgetheight() { $("#widgetarea").css({"max-height":$("body").height()}); $("#widgetarea").getNiceScroll().resize(); } // ------------------------------- // Back to Top button // ------------------------------- $('#back-to-top').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); // ------------------------------- // Panel Collapses // ------------------------------- $('a.panel-collapse').click(function() { $(this).children().toggleClass("fa-chevron-down fa-chevron-up"); $(this).closest(".panel-heading").next().slideToggle({duration: 200}); $(this).closest(".panel-heading").toggleClass('rounded-bottom'); return false; }); // ------------------------------- // Quick Start // ------------------------------- $('#headerbardropdown').click(function() { $('#headerbar').css('top',0); return false; }); $('#headerbardropdown').click(function(event) { $('html').one('click',function() { $('#headerbar').css('top','-1000px'); }); event.stopPropagation(); }); // ------------------------------- // Keep search open on click // ------------------------------- $('#search>a').click(function () { $('#search').toggleClass('keep-open'); $('#search>a i').toggleClass("opacity-control"); }); $('#search').click(function(event) { $('html').one('click',function() { $('#search').removeClass('keep-open'); $('#search>a i').addClass("opacity-control"); }); event.stopPropagation(); }); //Presentational: set all panel-body with br0 if it has panel-footer $(".panel-footer").prev().css("border-radius","0");
JavaScript
$('#datepageinate-ex1').datepaginator(); $('#datepageinate-ex2').datepaginator({ onSelectedDateChanged: function(event, date) { alert("Selected date: " + moment(date).format("Do, MMM YYYY")); } }); $('#datepageinate-ex3').datepaginator({size: "large"}); $('#datepageinate-ex4').datepaginator({size: "small"});
JavaScript
// Inline Charts examples $(".linecharts").sparkline(); $(".barcharts").sparkline('html', {type: 'bar'}); // Composite line charts, the second using values supplied via javascript $('#compositeline').sparkline('html', { fillColor: false, changeRangeMin: 0, chartRangeMax: 10 }); $('#compositeline').sparkline([4,1,5,7,9,9,8,7,6,6,4,7,8,4,3,2,2,5,6,7], {composite: true, fillColor: false, lineColor: 'red', changeRangeMin: 0, chartRangeMax: 10 }); // Bar + line composite charts $('#compositebar').sparkline('html', { type: 'bar', barColor: '#aaf' }); $('#compositebar').sparkline([4,1,5,7,9,9,8,7,6,6,4,7,8,4,3,2,2,5,6,7], {composite: true, fillColor: false, lineColor: 'red' }); // Discrete charts $('#discrete1').sparkline('html', { type: 'discrete', lineColor: 'blue', xwidth: 18 }); $('#discrete2').sparkline('html', { type: 'discrete', lineColor: 'blue', thresholdColor: 'red', thresholdValue: 4 }); $("#pie").sparkline([1,2,3], {type: 'pie'}); // Large Charts $("#bigline").sparkline([5,4,4,7,6,9,5,8,2,6,4,6,7,4,2,1,5,7,2,1,4,2,0,3,6,3], { type: 'line', width: '100%', height: '200px', lineColor: '#615ef2', fillColor: '#f5f6f7', highlightSpotColor: '#13b213', highlightLineColor: '#f95e5e', spotRadius: 2}); $("#bigline").sparkline([4,3,0,6,6,8,5,9,3,8,7,8,7,6,6,4,5,6,3,3,4,3,3,5,5,6], { type: 'line', width: '100%', height: '200px', lineColor: '#5eb9f2', fillColor: false, highlightSpotColor: '#13b213', highlightLineColor: '#f95e5e', composite: true, spotRadius: 2}); $("#bigpie").sparkline([5,3,4,1 ], {type: 'pie', height: '200px'}); $('#bigstacked').sparkline([5,4,7,6,9,5,8,2,6,4,6,7,6,4,2,1,4,6,2,5,7,2,3,5,3,7,9], { type: 'bar', barColor: '#aaf', height: '200px',width: '100%', barWidth: 10, barSpacing: 5}); $('#bigstacked').sparkline([4,1,5,7,9,9,8,7,6,6,4,7,8,4,3,2,2,5,6,7,8], { composite: true, fillColor: false, lineColor: 'red', height: '200px', width: '100%' });
JavaScript
jQuery(document).ready(function() { $("#chat").niceScroll({horizrailenabled:false,railoffset: {left:0}}); });
JavaScript
$('#bootbox-demo-1').click(function(){ bootbox.alert("Hello world!"); }); $('#bootbox-demo-2').click(function(){ bootbox.alert("Hello world!", function() { alert("Hello world callback"); }); }); $('#bootbox-demo-3').click(function(){ bootbox.confirm("Are you sure?", function(result) { alert("Confirm result: "+result); }); }); $('#bootbox-demo-4').click(function(){ bootbox.prompt("What is your name?", function(result) { if (result === null) { alert("Prompt dismissed"); } else { alert("Hi <b>"+result+"</b>"); } }); }); $('#bootbox-demo-5').click(function(){ bootbox.dialog({ message: "I am a custom dialog", title: "Custom title", buttons: { success: { label: "Success!", className: "btn-success", callback: function() { alert("great success"); } }, danger: { label: "Danger!", className: "btn-danger", callback: function() { alert("uh oh, look out!"); } }, main: { label: "Click ME!", className: "btn-primary", callback: function() { alert("Primary button"); } } } }); });
JavaScript
jQuery(document).ready(function() { $("#pulsate1").pulsate({glow:false}); $("#pulsate2").pulsate({color:"#09f"}); $("#pulsate3").pulsate({reach:100}); $("#pulsate4").pulsate({speed:2500}); $("#pulsate5").pulsate({pause:1000}); $("#pulsate6").pulsate({onHover:true}); }); function show_rich() { $.pnotify({ title: '<span style="color: red;">Rich Content Notice</span>', type: 'success', text: '<span style="color: blue;">Look at my beautiful <strong>strong</strong>, <em>emphasized</em>, and <span style="font-size: 1.5em;">large</span> text.</span>' }); } function dyn_notice() { var percent = 0; var notice = $.pnotify({ title: "Please Wait", type: 'info', icon: 'fa fa-spin fa-refresh', hide: false, closer: false, sticker: false, opacity: 0.75, shadow: false, width: "200px" }); setTimeout(function() { notice.pnotify({ title: false }); var interval = setInterval(function() { percent += 2; var options = { text: percent + "% complete." }; if (percent == 80) options.title = "Almost There"; if (percent >= 100) { window.clearInterval(interval); options.title = "Done!"; options.type = "success"; options.hide = true; options.closer = true; options.sticker = true; options.icon = 'fa fa-check'; options.opacity = 1; options.shadow = true; options.width = $.pnotify.defaults.width; } notice.pnotify(options); }, 120); }, 2000); }
JavaScript
$(function() { $(".dial").knob(); // knob //jQuery UI Sliders //------------------------ $('#demoskylo').on('click',function(){ $(document).skylo('start'); setTimeout(function(){ $(document).skylo('set',50); },1000); setTimeout(function(){ $(document).skylo('end'); },1500); }); $('#setskylo').on('click',function(){ $(document).skylo('show',function(){ $(document).skylo('set',50); }); }); $('#getskylo').on('click',function(){ alert($(document).skylo('get')+'%'); }); $('#inchskylo').on('click',function(){ $(document).skylo('show',function(){ $(document).skylo('inch',10); }); }); //jQuery UI Sliders //------------------------ $(".slider-basic").slider(); // basic sliders // snap inc $("#slider-snap-inc").slider({ value: 100, min: 0, max: 1000, step: 100, slide: function (event, ui) { $("#slider-snap-inc-amount").text("$" + ui.value); } }); $("#slider-snap-inc-amount").text("$" + $("#slider-snap-inc").slider("value")); // range slider $("#slider-range").slider({ range: true, min: 0, max: 500, values: [75, 300], slide: function (event, ui) { $("#slider-range-amount").text("$" + ui.values[0] + " - $" + ui.values[1]); } }); $("#slider-range-amount").text("$" + $("#slider-range").slider("values", 0) + " - $" + $("#slider-range").slider("values", 1)); //range max $("#slider-range-max").slider({ range: "max", min: 1, max: 10, value: 2, slide: function (event, ui) { $("#slider-range-max-amount").text(ui.value); } }); $("#slider-range-max-amount").text($("#slider-range-max").slider("value")); // range min $("#slider-range-min").slider({ range: "min", value: 37, min: 1, max: 700, slide: function (event, ui) { $("#slider-range-min-amount").text("$" + ui.value); } }); $("#slider-range-min-amount").text("$" + $("#slider-range-min").slider("value")); // setup graphic EQ $("#slider-eq > span").each(function () { // read initial values from markup and remove that var value = parseInt($(this).text(), 10); $(this).empty().slider({ range: "min", min: 0, max: 100, value: value, orientation: "vertical" }); }); // vertical slider $("#slider-vertical").slider({ orientation: "vertical", range: "min", min: 0, max: 100, value: 60, slide: function (event, ui) { $("#slider-vertical-amount").text(ui.value); } }); $("#slider-vertical-amount").text($("#slider-vertical").slider("value")); // vertical range sliders $("#slider-range-vertical").slider({ orientation: "vertical", range: true, values: [17, 67], slide: function (event, ui) { $("#slider-range-vertical-amount").text("$" + ui.values[0] + " - $" + ui.values[1]); } }); $("#slider-range-vertical-amount").text("$" + $("#slider-range-vertical").slider("values", 0) + " - $" + $("#slider-range-vertical").slider("values", 1)); //Easy Pie Chart //------------------------ try { //Easy Pie Chart $('.easypiechart#newvisits').easyPieChart({ barColor: "#16a085", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('.easypiechart#bouncerate').easyPieChart({ barColor: "#7ccc2e", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('.easypiechart#clickrate').easyPieChart({ barColor: "#e84747", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('.easypiechart#covertionrate').easyPieChart({ barColor: "#8e44ad", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('#updatePieCharts').on('click', function() { $('.easypiechart#newvisits').data('easyPieChart').update(Math.random()*100); $('.easypiechart#bouncerate').data('easyPieChart').update(Math.random()*100); $('.easypiechart#clickrate').data('easyPieChart').update(Math.random()*100); $('.easypiechart#covertionrate').data('easyPieChart').update(Math.random()*100); return false; }); } catch(error) {} });
JavaScript
$(function(){ // activate Nestable for list 1 $('#nestable_list_1').nestable({ group: 1 }) .on('change', updateOutput); // activate Nestable for list 2 $('#nestable_list_2').nestable({ group: 1 }) .on('change', updateOutput); // output initial serialised data updateOutput($('#nestable_list_1').data('output', $('#nestable_list_1_output'))); updateOutput($('#nestable_list_2').data('output', $('#nestable_list_2_output'))); $('#nestable_list_menu').on('click', function (e) { var target = $(e.target), action = target.data('action'); if (action === 'expand-all') { $('.dd').nestable('expandAll'); } if (action === 'collapse-all') { $('.dd').nestable('collapseAll'); } }); $('#nestable_list_3').nestable(); function updateOutput(e) { var list = e.length ? e : $(e.target), output = list.data('output'); if (window.JSON) { output.val(window.JSON.stringify(list.nestable('serialize'))); //, null, 2)); } else { output.val('JSON browser support required for this demo.'); } } });
JavaScript
$(function(){ var lineChartData = { labels : ["January","February","March","April","May","June","July"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", pointColor : "rgba(151,187,205,1)", pointStrokeColor : "#fff", data : [28,48,40,19,96,27,100] } ] } var myLine = new Chart(document.getElementById("line-chart").getContext("2d")).Line(lineChartData); var barChartData = { labels : ["January","February","March","April","May","June","July"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", data : [28,48,40,19,96,27,100] } ] } var myLine = new Chart(document.getElementById("bar-chart").getContext("2d")).Bar(barChartData); var radarChartData = { labels : ["Eating","Drinking","Sleeping","Designing","Coding","Partying","Running"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", pointColor : "rgba(151,187,205,1)", pointStrokeColor : "#fff", data : [28,48,40,19,96,27,100] } ] } var myRadar = new Chart(document.getElementById("radar-chart").getContext("2d")).Radar(radarChartData,{scaleShowLabels : false, pointLabelFontSize : 10}); var pieData = [ { value: 30, color:"#F38630" }, { value : 50, color : "#E0E4CC" }, { value : 100, color : "#69D2E7" } ]; var myPie = new Chart(document.getElementById("pie-chart").getContext("2d")).Pie(pieData); var chartData = [ { value : Math.random(), color: "#D97041" }, { value : Math.random(), color: "#C7604C" }, { value : Math.random(), color: "#21323D" }, { value : Math.random(), color: "#9D9B7F" }, { value : Math.random(), color: "#7D4F6D" }, { value : Math.random(), color: "#584A5E" } ]; var myPolarArea = new Chart(document.getElementById("polar-area-chart").getContext("2d")).PolarArea(chartData); var doughnutData = [ { value: 30, color:"#F7464A" }, { value : 50, color : "#46BFBD" }, { value : 100, color : "#FDB45C" }, { value : 40, color : "#949FB1" }, { value : 120, color : "#4D5360" } ]; var myDoughnut = new Chart(document.getElementById("donut-chart").getContext("2d")).Doughnut(doughnutData); });
JavaScript
$(function(){ //Uncomment the line and switch modes //$.fn.editable.defaults.mode = 'inline'; //editables $('#username').editable({ type: 'text', pk: 1, name: 'username', title: 'Enter username' }); $('#firstname').editable({ validate: function(value) { if($.trim(value) == '') return 'This field is required'; } }); $('#sex').editable({ prepend: "not selected", source: [ {value: 1, text: 'Male'}, {value: 2, text: 'Female'} ], display: function(value, sourceData) { var colors = {"": "gray", 1: "green", 2: "blue"}, elem = $.grep(sourceData, function(o){return o.value == value;}); if(elem.length) { $(this).text(elem[0].text).css("color", colors[value]); } else { $(this).empty(); } } }); $('#status').editable(); $('#group').editable({ showbuttons: false }); $('#dob').editable(); $('#comments').editable({ showbuttons: 'bottom' }); //inline $('#inline-username').editable({ type: 'text', pk: 1, name: 'username', title: 'Enter username', mode: 'inline' }); $('#inline-firstname').editable({ validate: function(value) { if($.trim(value) == '') return 'This field is required'; }, mode: 'inline' }); $('#inline-sex').editable({ prepend: "not selected", mode: 'inline', source: [ {value: 1, text: 'Male'}, {value: 2, text: 'Female'} ], display: function(value, sourceData) { var colors = {"": "gray", 1: "green", 2: "blue"}, elem = $.grep(sourceData, function(o){return o.value == value;}); if(elem.length) { $(this).text(elem[0].text).css("color", colors[value]); } else { $(this).empty(); } } }); $('#inline-status').editable({mode: 'inline'}); $('#inline-group').editable({ showbuttons: false, mode: 'inline' }); $('#inline-dob').editable({mode: 'inline'}); $('#inline-comments').editable({ showbuttons: 'bottom', mode: 'inline' }); });
JavaScript
// ------------------------------- // Initialize Data Tables // ------------------------------- $(document).ready(function() { $('.datatables').dataTable({ "sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page", "sSearch": "" } }); $('.dataTables_filter input').addClass('form-control').attr('placeholder','Search...'); $('.dataTables_length select').addClass('form-control'); });
JavaScript
// ---------------------- // Inline table editor // ---------------------- $(function () { $('#editable td').editable({ closeOnEnter : true, event:"click", touch : true, callback: function(data) { if( data.fontSize ) { alert('You changed the font size to '+data.fontSize); } } }); }); // ------------------------------- // Initialize Data Tables // ------------------------------- $(document).ready(function() { $('.datatables').dataTable({ "sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page", "sSearch": "" } }); $('.dataTables_filter input').addClass('form-control').attr('placeholder','Search...'); $('.dataTables_length select').addClass('form-control');} ); //------------------------- // With Table Tools Editor //------------------------- var editor; $(function () { editor = new $.fn.dataTable.Editor({ "ajaxUrl":"assets/demo/source.json", "domTable":"#crudtable", "fields":[ { "label":"Browser:", "name":"browser" }, { "label":"Rendering engine:", "name":"engine" }, { "label":"Platform:", "name":"platform" }, { "label":"Version:", "name":"version" }, { "label":"CSS grade:", "name":"grade" } ] }); $('#crudtable').dataTable({ "sDom":"<'row'<'col-sm-6'T><'col-sm-6'f>r>t<'row'<'col-sm-6'i><'col-sm-6'p>>", "sAjaxSource":"assets/demo/source.json", "bServerSide": false, "bAutoWidth": false, "bDestroy": true, "aoColumns":[ { "mData":"browser" }, { "mData":"engine" }, { "mData":"platform" }, { "mData":"version", "sClass":"center" }, { "mData":"grade", "sClass":"center" } ], "oTableTools":{ "sRowSelect":"multi", "aButtons":[ { "sExtends":"editor_create", "editor":editor }, { "sExtends":"editor_edit", "editor":editor }, { "sExtends":"editor_remove", "editor":editor } ] } }); $('.dataTables_filter input').addClass('form-control').attr('placeholder','Search...'); $('.dataTables_length select').addClass('form-control'); //add icons $("#ToolTables_crudtable_0").prepend('<i class="fa fa-plus"/> '); $("#ToolTables_crudtable_1").prepend('<i class="fa fa-pencil-square-o"/> '); $("#ToolTables_crudtable_2").prepend('<i class="fa fa-times-circle"/> '); });
JavaScript
/** * Basic Map */ $(document).ready(function () { //Basic Maps var map = new GMaps({ el:'#basic-map', lat:-12.043333, lng:-77.028333 }); GMaps.geolocate({ success:function (position) { map.setCenter(position.coords.latitude, position.coords.longitude); }, error:function (error) { alert('Geolocation failed: ' + error.message); }, not_supported:function () { alert("Your browser does not support geolocation"); } }); //advance Route var route = new GMaps({ el:'#advance-route', lat:-12.043333, lng:-77.028333 }); $('#start_travel').click(function (e) { e.preventDefault(); route.travelRoute({ origin:[-12.044012922866312, -77.02470665341184], destination:[-12.090814532191756, -77.02271108990476], travelMode:'driving', step:function (e) { $('#instructions').append('<li>' + e.instructions + '</li>'); $('#instructions li:eq(' + e.step_number + ')').delay(450 * e.step_number).fadeIn(200, function () { route.setCenter(e.end_location.lat(), e.end_location.lng()); route.drawPolyline({ path:e.path, strokeColor:'#131540', strokeOpacity:0.6, strokeWeight:6 }); }); } }); }); //street view panaroma var panorama = GMaps.createPanorama({ el:'#panorama', lat:42.3455, lng:-71.0983 }); //fusion table var fusion, infoWindow; infoWindow = new google.maps.InfoWindow({}); fusion = new GMaps({ el:'#fusion', zoom:11, lat:41.850033, lng:-87.6500523 }); fusion.loadFromFusionTables({ query:{ select:'\'Geocodable address\'', from:'1mZ53Z70NsChnBMm-qEYmSDOvLXgrreLTkQUvvg' }, suppressInfoWindows:true, events:{ click:function (point) { infoWindow.setContent('You clicked here!'); infoWindow.setPosition(point.latLng); infoWindow.open(fusion.map); } } }); //polyLInes path = [[-12.044012922866312, -77.02470665341184], [-12.05449279282314, -77.03024273281858], [-12.055122327623378, -77.03039293652341], [-12.075917129727586, -77.02764635449216], [-12.07635776902266, -77.02792530422971], [-12.076819390363665, -77.02893381481931], [-12.088527520066453, -77.0241058385925], [-12.090814532191756, -77.02271108990476]]; var polylines = new GMaps({ el: '#polylines', lat: -12.043333, lng: -77.028333, click: function(e){ console.log(e); } }); polylines.drawPolyline({ path: path, strokeColor: '#131540', strokeOpacity: 0.6, strokeWeight: 6 }); //geo coding var geoCoding = new GMaps({ el: '#geocoding', lat: -12.043333, lng: -77.028333 }); $('#geocoding_form').submit(function(e){ e.preventDefault(); GMaps.geocode({ address: $('#address').val().trim(), callback: function(results, status){ if(status=='OK'){ var latlng = results[0].geometry.location; geoCoding.setCenter(latlng.lat(), latlng.lng()); geoCoding.addMarker({ lat: latlng.lat(), lng: latlng.lng() }); } } }); }); //polygons var polygons = new GMaps({ el: '#polygons', lat: -12.043333, lng: -77.028333 }); var path = [[-12.040397656836609,-77.03373871559225], [-12.040248585302038,-77.03993927003302], [-12.050047116528843,-77.02448169303511], [-12.044804866577001,-77.02154422636042]]; polygon = polygons.drawPolygon({ paths: path, strokeColor: '#BBD8E9', strokeOpacity: 1, strokeWeight: 3, fillColor: '#BBD8E9', fillOpacity: 0.6 }); });
JavaScript
// Demo for FullCalendar with Drag/Drop internal $(document).ready(function() { var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); var calendar = $('#calendar-drag').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, selectable: true, selectHelper: true, select: function(start, end, allDay) { var title = prompt('Event Title:'); if (title) { calendar.fullCalendar('renderEvent', { title: title, start: start, end: end, allDay: allDay }, true // make the event "stick" ); } calendar.fullCalendar('unselect'); }, editable: true, events: [ { title: 'All Day Event', start: new Date(y, m, 8), backgroundColor: '#efa131' }, { title: 'Long Event', start: new Date(y, m, d-5), end: new Date(y, m, d-2), backgroundColor: '#85c744' }, { id: 999, title: 'Repeating Event', start: new Date(y, m, d-3, 16, 0), allDay: false, backgroundColor: '#e74c3c' }, { id: 999, title: 'Repeating Event', start: new Date(y, m, d+4, 16, 0), allDay: false, backgroundColor: '#e74c3c' }, { title: 'Meeting', start: new Date(y, m, d, 10, 30), allDay: false, backgroundColor: '#76c4ed' }, { title: 'Lunch', start: new Date(y, m, d, 12, 0), end: new Date(y, m, d, 14, 0), allDay: false, backgroundColor: '#34495e' }, { title: 'Birthday Party', start: new Date(y, m, d+1, 19, 0), end: new Date(y, m, d+1, 22, 30), allDay: false, backgroundColor: '#2bbce0' }, { title: 'Click for Google', start: new Date(y, m, 28), end: new Date(y, m, 29), url: 'http://google.com/', backgroundColor: '#f1c40f' } ], buttonText: { prev: '<i class="fa fa-angle-left"></i>', next: '<i class="fa fa-angle-right"></i>', prevYear: '<i class="fa fa-angle-double-left"></i>', // << nextYear: '<i class="fa fa-angle-double-right"></i>', // >> today: 'Today', month: 'Month', week: 'Week', day: 'Day' } }); }); // Demo for FullCalendar with Drag/Drop external $(document).ready(function() { /* initialize the external events -----------------------------------------------------------------*/ $('#external-events div.external-event').each(function() { // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/) // it doesn't need to have a start or end var eventObject = { title: $.trim($(this).text()) // use the element's text as the event title }; // store the Event Object in the DOM element so we can get to it later $(this).data('eventObject', eventObject); // make the event draggable using jQuery UI $(this).draggable({ zIndex: 999, revert: true, // will cause the event to go back to its revertDuration: 0 // original position after the drag }); }); /* initialize the calendar -----------------------------------------------------------------*/ $('#calendar-external').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, editable: true, droppable: true, // this allows things to be dropped onto the calendar !!! drop: function(date, allDay) { // this function is called when something is dropped // retrieve the dropped element's stored Event Object var originalEventObject = $(this).data('eventObject'); // we need to copy it, so that multiple events don't have a reference to the same object var copiedEventObject = $.extend({}, originalEventObject); // assign it the date that was reported copiedEventObject.start = date; copiedEventObject.allDay = allDay; // render the event on the calendar // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/) $('#calendar-external').fullCalendar('renderEvent', copiedEventObject, true); // is the "remove after drop" checkbox checked? if ($('#drop-remove').is(':checked')) { // if so, remove the element from the "Draggable Events" list $(this).remove(); } }, buttonText: { prev: '<i class="fa fa-angle-left"></i>', next: '<i class="fa fa-angle-right"></i>', prevYear: '<i class="fa fa-angle-double-left"></i>', // << nextYear: '<i class="fa fa-angle-double-right"></i>', // >> today: 'Today', month: 'Month', week: 'Week', day: 'Day' } }); });
JavaScript
/* Initialize Image Filter and Sort Plugin for Gallery */ $(function(){ $('.gallery').mixitup({ onMixEnd: function() { onclickofimg(); } }); }); /* Bind filter with selectbox */ $("#galleryfilter").change(function(e) { var cat = $("#galleryfilter option:selected").data('filter'); $('.gallery').mixitup('filter', cat); }); /* Switch between grid and list view */ $('#GoList').click(function(e) { $('.gallery').mixitup('toList'); $(this).addClass('active'); var delay = setTimeout(function(){ $('.gallery').addClass('full-width'); $('#GoGrid').removeClass('active'); }); }); $('#GoGrid').click(function(e) { $('#GoList').removeClass('active'); $(this).addClass('active'); var delay = setTimeout(function(){ $('.gallery').mixitup('toGrid'); $('.gallery').removeClass('full-width'); }); }); onclickofimg(); //On click of img function onclickofimg () { $('.mix a').click(function(e){ e.preventDefault(); $('.modal-title').empty(); $('.modal-body').empty(); var title = $(this).siblings('h4').html(); $('.modal-title').html(title); var img= '<img class="img-responsive" src=' +$(this).attr("href")+ '></img>'; $(img).appendTo('.modal-body'); $('#gallarymodal').modal({show:true}); }); }
JavaScript
jQuery(document).ready(function() { $(".demodrop").pulsate({ color: "#2bbce0", repeat: 10 }); $("#threads,#comments,#users").niceScroll({horizrailenabled:false,railoffset: {left:0}}); try { //Easy Pie Chart $('.easypiechart#returningvisits').easyPieChart({ barColor: "#85c744", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('.easypiechart#newvisitor').easyPieChart({ barColor: "#f39c12", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('.easypiechart#clickrate').easyPieChart({ barColor: "#e73c3c", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('#updatePieCharts').on('click', function() { $('.easypiechart#returningvisits').data('easyPieChart').update(Math.random()*100); $('.easypiechart#newvisitor').data('easyPieChart').update(Math.random()*100); $('.easypiechart#clickrate').data('easyPieChart').update(Math.random()*100); return false; }); } catch(e) {} //Date Range Picker $('#daterangepicker2').daterangepicker( { ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)], 'Last 7 Days': [moment().subtract('days', 6), moment()], 'Last 30 Days': [moment().subtract('days', 29), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')] }, opens: 'left', startDate: moment().subtract('days', 29), endDate: moment() }, function(start, end) { $('#daterangepicker2 span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); } ); //Sparklines $("#indexinfocomments").sparkline([12 + randValue(),8 + randValue(),10 + randValue(), 21 + randValue(), 16 + randValue(), 9 + randValue(), 15 + randValue(), 8 + randValue() ,10 + randValue(),19 + randValue()], { type: 'bar', barColor: '#f1948a', height: '45', barWidth: 7}); $("#indexinfolikes").sparkline([120 + randValue(),87 + randValue(),108 + randValue(), 121 + randValue(), 85 + randValue(), 95 + randValue(), 185 + randValue(), 125 + randValue() ,154 + randValue(),109 + randValue()], { type: 'bar', barColor: '#f5c783', height: '45', barWidth: 7}); $("#indexvisits").sparkline([7914 + randValue(),2795 + randValue(),3256 + randValue(), 3018 + randValue(), 2832 + randValue() ,5261 + randValue(),6573 + randValue()], { lineWidth: 1.5, type: 'line', width: '90px', height: '45px', lineColor: '#556b8d', fillColor: 'rgba(85,107,141,0.1)', spotColor: false, minSpotColor: false, highlightLineColor: '#d2d3d6', highlightSpotColor: '#556b8d', spotRadius: 3, maxSpotColor: false}); $("#indexpageviews").sparkline([8263 + randValue(),6314 + randValue(),10467 + randValue(), 12123 + randValue(), 11125 + randValue() ,13414 + randValue(),15519 + randValue()], { lineWidth: 1.5, type: 'line', width: '90px', height: '45px', lineColor: '#4f8edc', fillColor: 'rgba(79,142,220,0.1)', spotColor: false, minSpotColor: false, highlightLineColor: '#d2d3d6', highlightSpotColor: '#4f8edc', spotRadius: 3, maxSpotColor: false}); $("#indexpagesvisit").sparkline([7.41 + randValue(),6.12 + randValue(),6.8 + randValue(), 5.21 + randValue(), 6.15 + randValue() ,7.14 + randValue(),6.19 + randValue()], { lineWidth: 1.5, type: 'line', width: '90px', height: '45px', lineColor: '#a6b0c2', fillColor: 'rgba(166,176,194,0.1)', spotColor: false, minSpotColor: false, highlightLineColor: '#d2d3d6', highlightSpotColor: '#a6b0c2', spotRadius: 3, maxSpotColor: false}); $("#indexavgvisit").sparkline([5.31 + randValue(),2.18 + randValue(),1.06 + randValue(), 3.42 + randValue(), 2.51 + randValue() ,1.45 + randValue(),4.01 + randValue()], { lineWidth: 1.5, type: 'line', width: '90px', height: '45px', lineColor: '#85c744', fillColor: 'rgba(133,199,68,0.1)', spotColor: false, minSpotColor: false, highlightLineColor: '#d2d3d6', highlightSpotColor: '#85c744', spotRadius: 3, maxSpotColor: false}); $("#indexnewvisits").sparkline([70.14 + randValue(),72.95 + randValue(),77.56 + randValue(), 78.18 + randValue(), 76.32 + randValue() ,73.61 + randValue(),74.73 + randValue()], { lineWidth: 1.5, type: 'line', width: '90px', height: '45px', lineColor: '#efa131', fillColor: 'rgba(239,161,49,0.1)', spotColor: false, minSpotColor: false, highlightLineColor: '#d2d3d6', highlightSpotColor: '#efa131', spotRadius: 3, maxSpotColor: false}); $("#indexbouncerate").sparkline([29.14 + randValue(),27.95 + randValue(),32.56 + randValue(), 30.18 + randValue(), 28.32 + randValue() ,32.61 + randValue(),35.73 + randValue()], { lineWidth: 1.5, type: 'line', width: '90px', height: '45px', lineColor: '#e74c3c', fillColor: 'rgba(231,76,60,0.1)', spotColor: false, minSpotColor: false, highlightLineColor: '#d2d3d6', highlightSpotColor: '#e74c3c', spotRadius: 3, maxSpotColor: false}); //Flot function randValue() { return (Math.floor(Math.random() * (2))); } var viewcount = [ [1, 787 + randValue()], [2, 740 + randValue()], [3, 560 + randValue()], [4, 860 + randValue()], [5, 750 + randValue()], [6, 910 + randValue()], [7, 730 + randValue()] ]; var uniqueviews = [ [1, 179 + randValue()], [2, 320 + randValue()], [3, 120 + randValue()], [4, 400 + randValue()], [5, 573 + randValue()], [6, 255 + randValue()], [7, 366 + randValue()] ]; var usercount = [ [1, 70 + randValue()], [2, 260 + randValue()], [3, 30 + randValue()], [4, 147 + randValue()], [5, 333 + randValue()], [6, 155 + randValue()], [7, 166 + randValue()] ]; var plot_statistics = $.plot($("#site-statistics"), [{ data: viewcount, label: "View Count" }, { data: uniqueviews, label: "Unique Views" }, { data: usercount, label: "User Count" }], { series: { lines: { show: true, lineWidth: 1.5, fill: 0.05 }, points: { show: true }, shadowSize: 0 }, grid: { labelMargin: 10, hoverable: true, clickable: true, borderWidth: 0 }, colors: ["#a6b0c2", "#71a5e7", "#aa73c2"], xaxis: { tickColor: "transparent", ticks: [[1, "S"], [2, "M"], [3, "T"], [4, "W"], [5, "T"], [6, "F"], [7, "S"]], tickDecimals: 0, autoscaleMargin: 0, font: { color: '#8c8c8c', size: 12 } }, yaxis: { ticks: 4, tickDecimals: 0, tickColor: "#e3e4e6", font: { color: '#8c8c8c', size: 12 }, tickFormatter: function (val, axis) { if (val>999) {return (val/1000) + "K";} else {return val;} } }, legend : { labelBoxBorderColor: 'transparent' } }); var d1 = [ [1, 29 + randValue()], [2, 62 + randValue()], [3, 52 + randValue()], [4, 41 + randValue()] ]; var d2 = [ [1, 36 + randValue()], [2, 79 + randValue()], [3, 66 + randValue()], [4, 24 + randValue()] ]; for (var i = 1; i < 5; i++) { d1.push([i, parseInt(Math.random() * 1)]); d2.push([i, parseInt(Math.random() * 1)]); } var ds = new Array(); ds.push({ data:d1, label: "Budget", bars: { show: true, barWidth: 0.2, order: 1 } }); ds.push({ data:d2, label: "Actual", bars: { show: true, barWidth: 0.2, order: 2, } }); var variance = $.plot($("#budget-variance"), ds, { series: { bars: { show: true, fill: 0.75, lineWidth: 0 } }, grid: { labelMargin: 10, hoverable: true, clickable: true, tickColor: "#e6e7e8", borderWidth: 0 }, colors: ["#8D96AF", "#556b8d"], xaxis: { autoscaleMargin: 0.05, tickColor: "transparent", ticks: [[1, "Q1"], [2, "Q2"], [3, "Q3"], [4, "Q4"]], tickDecimals: 0, font: { color: '#8c8c8c', size: 12 } }, yaxis: { ticks: [0, 25, 50, 75, 100], font: { color: '#8c8c8c', size: 12 }, tickFormatter: function (val, axis) { return "$" + val + "K"; } }, legend : { labelBoxBorderColor: 'transparent' } }); var previousPoint = null; $("#site-statistics").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if (item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX, item.pageY-7, item.series.label + ": " + Math.round(y)); } } else { $("#tooltip").remove(); previousPoint = null; } }); var previousPointBar = null; $("#budget-variance").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if (item) { if (previousPointBar != item.dataIndex) { previousPointBar = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX+20, item.pageY, item.series.label + ": $" + Math.round(y)+"K"); } } else { $("#tooltip").remove(); previousPointBar = null; } }); function showTooltip(x, y, contents) { $('<div id="tooltip" class="tooltip top in"><div class="tooltip-inner">' + contents + '<\/div><\/div>').css({ display: 'none', top: y - 40, left: x - 55, }).appendTo("body").fadeIn(200); } var container = $("#server-load"); // Determine how many data points to keep based on the placeholder's initial size; // this gives us a nice high-res plot while avoiding more than one point per pixel. var maximum = container.outerWidth() / 2 || 300; var data = []; function getRandomData() { if (data.length) { data = data.slice(1); } while (data.length < maximum) { var previous = data.length ? data[data.length - 1] : 50; var y = previous + Math.random() * 10 - 5; data.push(y < 0 ? 0 : y > 100 ? 100 : y); } // zip the generated y values with the x values var res = []; for (var i = 0; i < data.length; ++i) { res.push([i, data[i]]) } return res; } // series = [{ data: getRandomData() }]; // var plot = $.plot(container, series, { series: { lines: { show: true, lineWidth: 1.5, fill: 0.15 }, shadowSize: 0 }, grid: { labelMargin: 10, tickColor: "#e6e7e8", borderWidth: 0 }, colors: ["#f1c40f"], xaxis: { tickFormatter: function() { return ""; }, tickColor: "transparent" }, yaxis: { ticks: 2, min: 0, max: 100, tickFormatter: function (val, axis) { return val + "%"; }, font: { color: '#8c8c8c', size: 12 } }, legend: { show: true } }); // Update the random dataset at 25FPS for a smoothly-animating chart setInterval(function updateRandom() { series[0].data = getRandomData(); plot.setData(series); plot.draw(); }, 40); }); // Calendar // If screensize > 1200, render with m/w/d view, if not by default render with just title renderCalendar({left: 'title',right: 'prev,next'}); enquire.register("screen and (min-width: 1200px)", { match : function() { $('#calendar-drag').removeData('fullCalendar').empty(); renderCalendar({left: 'prev,next',center: 'title',right: 'month,basicWeek,basicDay'}); }, unmatch : function() { $('#calendar-drag').removeData('fullCalendar').empty(); renderCalendar({left: 'title',right: 'prev,next'}); } }); function renderCalendar(headertype) { // Demo for FullCalendar with Drag/Drop internal var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); var calendar = $('#calendar-drag').fullCalendar({ header: headertype, selectable: true, selectHelper: true, select: function(start, end, allDay) { var title = prompt('Event Title:'); if (title) { calendar.fullCalendar('renderEvent', { title: title, start: start, end: end, allDay: allDay }, true // make the event "stick" ); } calendar.fullCalendar('unselect'); }, editable: true, events: [ { title: 'All Day Event', start: new Date(y, m, 8), backgroundColor: '#efa131' }, { title: 'Long Event', start: new Date(y, m, d-5), end: new Date(y, m, d-2), backgroundColor: '#7a869c' }, { id: 999, title: 'Repeating Event', start: new Date(y, m, d-3, 16, 0), allDay: false, backgroundColor: '#e74c3c' }, { id: 999, title: 'Repeating Event', start: new Date(y, m, d+4, 16, 0), allDay: false, backgroundColor: '#e74c3c' }, { title: 'Meeting', start: new Date(y, m, d, 10, 30), allDay: false, backgroundColor: '#76c4ed' }, { title: 'Lunch', start: new Date(y, m, d, 12, 0), end: new Date(y, m, d, 14, 0), allDay: false, backgroundColor: '#34495e' }, { title: 'Birthday Party', start: new Date(y, m, d+1, 19, 0), end: new Date(y, m, d+1, 22, 30), allDay: false, backgroundColor: '#2bbce0' }, { title: 'Click for Google', start: new Date(y, m, 28), end: new Date(y, m, 29), url: 'http://google.com/', backgroundColor: '#f1c40f' } ], buttonText: { prev: '<i class="fa fa-angle-left"></i>', next: '<i class="fa fa-angle-right"></i>', prevYear: '<i class="fa fa-angle-double-left"></i>', // << nextYear: '<i class="fa fa-angle-double-right"></i>', // >> today: 'Today', month: 'Month', week: 'Week', day: 'Day' } }); // Listen for click on toggle checkbox $('#select-all').click(function(event) { if(this.checked) { $('.selects :checkbox').each(function() { this.checked = true; }); } else { $('.selects :checkbox').each(function() { this.checked = false; }); } }); $( ".panel-tasks" ).sortable({placeholder: 'item-placeholder'}); $('.panel-tasks input[type="checkbox"]').click(function(event) { if(this.checked) { $(this).next(".task-description").addClass("done"); } else { $(this).next(".task-description").removeClass("done"); } }); }
JavaScript
// ------------------------------- // Demos: Form Components // ------------------------------- $(function() { //FSEditor $(".fullscreen").fseditor({maxHeight: 500}); // iPhone like button Toggle (uncommented because already activated in demo.js) // $('.toggle').toggles({on:true}); // Autogrow Textarea $('textarea.autosize').autosize({append: "\n"}); //Typeahead for Autocomplete $('.example-countries.typeahead').typeahead({ name: 'countries', prefetch: 'assets/demo/countries.json', limit: 10 }); //Color Picker $('.cpicker').colorpicker(); //Bootstrap Date Picker $('#datepicker,#datepicker2,#datepicker3').datepicker(); $('#datepicker-pastdisabled').datepicker({startDate: "today"}); $('#datepicker-startview1').datepicker({startView: 1}); //http://eternicode.github.io/bootstrap-datepicker/ //jQueryUI Time Picker $('#timepicker1,#timepicker3').timepicker(); $("#timepicker2").timepicker({ showPeriod: true, showLeadingZero: true }); $('#timepickerbtn2').click(function () { $('#timepicker2').timepicker("show"); }); $("#timepicker4").timepicker({ hours: { starts: 6, ends: 19 }, minutes: { interval: 15 }, rows: 3, showPeriodLabels: true, minuteText: 'Min' }); // Date Range Picker $(document).ready(function() { $('#daterangepicker1').daterangepicker(); }); $('#daterangepicker2').daterangepicker( { ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)], 'Last 7 Days': [moment().subtract('days', 6), moment()], 'Last 30 Days': [moment().subtract('days', 29), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')] }, opens: 'left', startDate: moment().subtract('days', 29), endDate: moment() }, function(start, end) { $('#daterangepicker2 span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); } ); $('#daterangepicker3').daterangepicker({ timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A' }); //Tokenfield $('#tokenfield-jQUI').tokenfield({ autocomplete: { source: ['red','blue','green','yellow','violet','brown','purple','black','white'], delay: 100 }, showAutocompleteOnFocus: true }); $('#tokenfield-typeahead').tokenfield({ typeahead: { name: 'tags', local: ['red','blue','green','yellow','violet','brown','purple','black','white'], } }); $('#tokenfield-email') .on('beforeCreateToken', function (e) { var token = e.token.value.split('|') e.token.value = token[1] || token[0] e.token.label = token[1] ? token[0] + ' (' + token[1] + ')' : token[0] }) .on('afterCreateToken', function (e) { // Über-simplistic e-mail validation var re = /\S+@\S+\.\S+/ var valid = re.test(e.token.value) if (!valid) { $(e.relatedTarget).addClass('invalid') } }) .on('beforeEditToken', function (e) { if (e.token.label !== e.token.value) { var label = e.token.label.split(' (') e.token.value = label[0] + '|' + e.token.value } }) .on('removeToken', function (e) { alert('Token removed! Token value was: ' + e.token.value) }) .on('preventDuplicateToken', function (e) { alert('Duplicate detected! Token value is: ' + e.token.value) }) .tokenfield(); //SELECT2 //For detailed documentation, see: http://ivaynberg.github.io/select2/index.html //Populate all select boxes with from select#source var opts=$("#source").html(), opts2="<option></option>"+opts; $("select.populate").each(function() { var e=$(this); e.html(e.hasClass("placeholder")?opts2:opts); }); //select2 $("#e1,#e2").select2({width: 'resolve'}); $("#e3").select2({ minimumInputLength: 2, width: 'resolve' }); $("#e5").select2({ minimumInputLength: 1, width: 'resolve', query: function (query) { var data = {results: []}, i, j, s; for (i = 1; i < 5; i++) { s = ""; for (j = 0; j < i; j++) {s = s + query.term;} data.results.push({id: query.term + i, text: s}); } query.callback(data); } }); $("#e12").select2({width: "resolve", tags:["red", "white", "purple", "orange", "yellow"]}); $("#e9").select2({width: 'resolve'}); //Rotten Tomatoes Infinite Scroll + Remote Data example $("#e7").select2({ placeholder: "Search for a movie", minimumInputLength: 3, width: 'resolve', ajax: { url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json", dataType: 'jsonp', quietMillis: 100, data: function (term, page) { // page is the one-based page number tracked by Select2 return { q: term, //search term page_limit: 10, // page size page: page, // page number apikey: "q7jnbsc56ysdyvvbeanghegk" // please do not use so this example keeps working }; }, results: function (data, page) { var more = (page * 10) < data.total; // whether or not there are more results available // notice we return the value of more so Select2 knows if more results can be loaded return {results: data.movies, more: more}; } }, formatResult: movieFormatResult, formatSelection: movieFormatSelection, dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results }); //MULTISELECT2 // For detailed documentatin, see: loudev.com $('#multi-select2').multiSelect(); $('#multi-select').multiSelect({ selectableHeader: "<input type='text' class='form-control' style='margin-bottom: 10px;' autocomplete='off' placeholder='Filter entries...'>", selectionHeader: "<input type='text' class='form-control' style='margin-bottom: 10px;' autocomplete='off' placeholder='Filter entries...'>", afterInit: function(ms){ var that = this, $selectableSearch = that.$selectableUl.prev(), $selectionSearch = that.$selectionUl.prev(), selectableSearchString = '#'+that.$container.attr('id')+' .ms-elem-selectable:not(.ms-selected)', selectionSearchString = '#'+that.$container.attr('id')+' .ms-elem-selection.ms-selected'; that.qs1 = $selectableSearch.quicksearch(selectableSearchString) .on('keydown', function(e){ if (e.which === 40){ that.$selectableUl.focus(); return false; } }); that.qs2 = $selectionSearch.quicksearch(selectionSearchString) .on('keydown', function(e){ if (e.which == 40){ that.$selectionUl.focus(); return false; } }); }, afterSelect: function(){ this.qs1.cache(); this.qs2.cache(); }, afterDeselect: function(){ this.qs1.cache(); this.qs2.cache(); } }); }); function movieFormatResult(movie) { var markup = "<table class='movie-result'><tr>"; if (movie.posters !== undefined && movie.posters.thumbnail !== undefined) { markup += "<td class='movie-image'><img src='" + movie.posters.thumbnail + "'/></td>"; } markup += "<td class='movie-info'><div class='movie-title'>" + movie.title + "</div>"; if (movie.critics_consensus !== undefined) { markup += "<div class='movie-synopsis'>" + movie.critics_consensus + "</div>"; } else if (movie.synopsis !== undefined) { markup += "<div class='movie-synopsis'>" + movie.synopsis + "</div>"; } markup += "</td></tr></table>" return markup; } function movieFormatSelection(movie) { return movie.title; }
JavaScript
$(function () { //Interacting with Data Points example var sin = [], cos = []; for (var i = 0; i < 14; i += 0.5) { sin.push([i, Math.sin(i) / i]); cos.push([i, Math.cos(i)]); } var plot = $.plot($("#sincos"), [{ data: sin, label: "sin(x)/x" }, { data: cos, label: "cos(x)" }], { series: { shadowSize: 0, lines: { show: true }, points: { show: true } }, grid: { hoverable: true, clickable: true}, yaxis: { min: -1.2, max: 1.2 }, colors: ["#539F2E", "#3C67A5"] }); function showTooltip(x, y, contents) { $('<div id="tooltip">' + contents + '</div>').css({ position: 'absolute', display: 'none', top: y + 5, left: x + 5, border: '1px solid #fdd', padding: '2px', 'background-color': '#dfeffc', opacity: 0.80 }).appendTo("body").fadeIn(200); } var previousPoint = null; $("#sincos").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if (item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y); } } else { $("#tooltip").remove(); previousPoint = null; } }); $("#sincos").bind("plotclick", function (event, pos, item) { if (item) { $("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + "."); plot.highlight(item.series, item.datapoint); } }); //Multiple var d1 = []; for (var i = 0; i < 14; i += 0.5) d1.push([i, Math.sin(i)]); var d2 = [[0, 3], [4, 8], [8, 5], [9, 13]]; var d3 = []; for (var i = 0; i < 14; i += 0.5) d3.push([i, Math.cos(i)]); var d4 = []; for (var i = 0; i < 14; i += 0.1) d4.push([i, Math.sqrt(i * 10)]); var d5 = []; for (var i = 0; i < 14; i += 0.5) d5.push([i, Math.sqrt(i)]); var d6 = []; for (var i = 0; i < 14; i += 0.5 + Math.random()) d6.push([i, Math.sqrt(2*i + Math.sin(i) + 5)]); $.plot($("#multiple"), [ { data: d1, lines: { show: true, fill: true }, shadowSize: 0 }, { data: d2, bars: { show: true }, shadowSize: 0 }, { data: d3, points: { show: true }, shadowSize: 0 }, { data: d4, lines: { show: true }, shadowSize: 0 }, { data: d5, lines: { show: true }, points: { show: true }, shadowSize: 0 }, { data: d6, lines: { show: true, steps: true }, shadowSize: 0 } ]); // We use an inline data source in the example, usually data would // be fetched from a server var dxta = [], totalPoints = 300; var updateInterval = 30; function getRandomData() { if (dxta.length > 0) dxta = dxta.slice(1); // Do a random walk while (dxta.length < totalPoints) { var prev = dxta.length > 0 ? dxta[dxta.length - 1] : 50, y = prev + Math.random() * 10 - 5; if (y < 0) { y = 0; } else if (y > 100) { y = 100; } dxta.push(y); } // Zip the generated y values with the x values var res = []; for (var i = 0; i < dxta.length; ++i) { res.push([i, dxta[i]]) } return res; } var plot = $.plot("#realtime-updates", [ getRandomData() ], { series: { shadowSize: 0 // Drawing is faster without shadows }, yaxis: { min: 0, max: 100 }, xaxis: { show: false } }); function update() { plot.setData([getRandomData()]); // Since the axes don't change, we don't need to call plot.setupGrid() plot.draw(); setTimeout(update, updateInterval); } update(); var d1 = []; for (var i = 0; i <= 10; i += 1) { d1.push([i, parseInt(Math.random() * 30)]); } var d2 = []; for (var i = 0; i <= 10; i += 1) { d2.push([i, parseInt(Math.random() * 30)]); } var d3 = []; for (var i = 0; i <= 10; i += 1) { d3.push([i, parseInt(Math.random() * 30)]); } var stack = 0, bars = true, lines = false, steps = false; function plotWithOptions() { $.plot("#stacking", [ d1, d2, d3 ], { series: { stack: stack, lines: { show: lines, fill: true, steps: steps }, bars: { show: bars, barWidth: 0.6 } } }); } plotWithOptions(); $(".stackControls button").click(function (e) { e.preventDefault(); stack = $(this).text() == "With stacking" ? true : null; plotWithOptions(); }); $(".graphControls button").click(function (e) { e.preventDefault(); bars = $(this).text().indexOf("Bars") != -1; lines = $(this).text().indexOf("Lines") != -1; steps = $(this).text().indexOf("steps") != -1; plotWithOptions(); }); // data var data = [ { label: "Series1", data: 10}, { label: "Series2", data: 30}, { label: "Series3", data: 90}, { label: "Series4", data: 70}, { label: "Series5", data: 80}, { label: "Series6", data: 110} ]; var series = Math.floor(Math.random()*10)+1; for( var i = 0; i<series; i++) { data[i] = { label: "Series"+(i+1), data: Math.floor(Math.random()*100)+1 } } $.plot($("#graph0"), data, { series: { pie: { show: true } } }); // DONUT $.plot($("#donut"), data, { series: { pie: { innerRadius: 0.5, show: true } }, legend: { show: false } }); // INTERACTIVE $.plot($("#interactive"), data, { series: { pie: { show: true } }, grid: { hoverable: true, clickable: true }, legend: { show: false } }); $("#interactive").bind("plothover", pieHover); function pieHover(event, pos, obj) { if (!obj) return; percent = parseFloat(obj.series.percent).toFixed(2); $("#hover").html('<span style="font-weight: bold; color: '+obj.series.color+'">'+obj.series.label+' ('+percent+'%)</span>'); } });
JavaScript
$(document).ready(function(){ $("#demo").click(function(){ bootstro.start(".bootstro", { onComplete : function(params) { alert("Reached end of introduction with total " + (params.idx + 1)+ " slides"); }, onExit : function(params) { alert("Introduction stopped at slide #" + (params.idx + 1)); }, }); }); }); //<div class="col-md-4 bootstro" data-bootstro-title="I can align to [left,right,bottom,top]" data-bootstro-content="Simply because I am a popover. Specify me with &lt;b&gt;data-bootstro-placement&lt;/b&gt;" data-bootstro-placement="right" data-bootstro-width="400px" data-bootstro-step="3">
JavaScript
$(function() { //Parsley Form Validation //While the JS is not usually required in Parsley, we will be modifying //the default classes so it plays well with Bootstrap $('#validate-form').parsley({ successClass: 'has-success', errorClass: 'has-error', errors: { classHandler: function(el) { return $(el).closest('.form-group'); }, errorsWrapper: '<ul class=\"help-block list-unstyled\"></ul>', errorElem: '<li></li>' } }); });
JavaScript
$(function() { $('.mask').inputmask(); });
JavaScript
$(function(){ Morris.Line({ element: 'line-example', data: [ { y: '2006', a: 100, b: 90 }, { y: '2007', a: 75, b: 65 }, { y: '2008', a: 50, b: 40 }, { y: '2009', a: 75, b: 65 }, { y: '2010', a: 50, b: 40 }, { y: '2011', a: 75, b: 65 }, { y: '2012', a: 100, b: 90 } ], xkey: 'y', ykeys: ['a', 'b'], labels: ['Series A', 'Series B'] }); Morris.Bar({ element: 'bar-example', data: [ { y: '2006', a: 100, b: 90 }, { y: '2007', a: 75, b: 65 }, { y: '2008', a: 50, b: 40 }, { y: '2009', a: 75, b: 65 }, { y: '2010', a: 50, b: 40 }, { y: '2011', a: 75, b: 65 }, { y: '2012', a: 100, b: 90 } ], xkey: 'y', ykeys: ['a', 'b'], labels: ['Series A', 'Series B'] }); Morris.Donut({ element: 'donut-example', data: [ {label: "Download Sales", value: 12}, {label: "In-Store Sales", value: 30}, {label: "Mail-Order Sales", value: 20} ] }); Morris.Area({ element: 'area-example', data: [ { y: '2006', a: 100, b: 90 }, { y: '2007', a: 75, b: 65 }, { y: '2008', a: 50, b: 40 }, { y: '2009', a: 75, b: 65 }, { y: '2010', a: 50, b: 40 }, { y: '2011', a: 75, b: 65 }, { y: '2012', a: 100, b: 90 } ], xkey: 'y', ykeys: ['a', 'b'], labels: ['Series A', 'Series B'] }); });
JavaScript
$(document).ready(function() { //Load Wizards $('#basicwizard').stepy(); $('#wizard').stepy({finishButton: true, titleClick: true, block: true, validate: true}); //Add Wizard Compability - see docs $('.stepy-navigator').wrapInner('<div class="pull-right"></div>'); //Make Validation Compability - see docs $('#wizard').validate({ errorClass: "help-block", validClass: "help-block", highlight: function(element, errorClass,validClass) { $(element).closest('.form-group').addClass("has-error"); }, unhighlight: function(element, errorClass,validClass) { $(element).closest('.form-group').removeClass("has-error"); } }); });
JavaScript
$(function(){ var lineChartData = { labels : ["January","February","March","April","May","June","July"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", pointColor : "rgba(151,187,205,1)", pointStrokeColor : "#fff", data : [28,48,40,19,96,27,100] } ] } var myLine = new Chart(document.getElementById("line-chart").getContext("2d")).Line(lineChartData); var barChartData = { labels : ["January","February","March","April","May","June","July"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", data : [28,48,40,19,96,27,100] } ] } var myLine = new Chart(document.getElementById("bar-chart").getContext("2d")).Bar(barChartData); var radarChartData = { labels : ["Eating","Drinking","Sleeping","Designing","Coding","Partying","Running"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", pointColor : "rgba(151,187,205,1)", pointStrokeColor : "#fff", data : [28,48,40,19,96,27,100] } ] } var myRadar = new Chart(document.getElementById("radar-chart").getContext("2d")).Radar(radarChartData,{scaleShowLabels : false, pointLabelFontSize : 10}); var pieData = [ { value: 30, color:"#F38630" }, { value : 50, color : "#E0E4CC" }, { value : 100, color : "#69D2E7" } ]; var myPie = new Chart(document.getElementById("pie-chart").getContext("2d")).Pie(pieData); var chartData = [ { value : Math.random(), color: "#D97041" }, { value : Math.random(), color: "#C7604C" }, { value : Math.random(), color: "#21323D" }, { value : Math.random(), color: "#9D9B7F" }, { value : Math.random(), color: "#7D4F6D" }, { value : Math.random(), color: "#584A5E" } ]; var myPolarArea = new Chart(document.getElementById("polar-area-chart").getContext("2d")).PolarArea(chartData); var doughnutData = [ { value: 30, color:"#F7464A" }, { value : 50, color : "#46BFBD" }, { value : 100, color : "#FDB45C" }, { value : 40, color : "#949FB1" }, { value : 120, color : "#4D5360" } ]; var myDoughnut = new Chart(document.getElementById("donut-chart").getContext("2d")).Doughnut(doughnutData); });
JavaScript
$(function(){ //Default $('#crop-default').Jcrop(); //Event Handler $('#crop-handler').Jcrop({ onChange: showCoords, onSelect: showCoords }); function showCoords(c) { $('#x1').val(c.x); $('#y1').val(c.y); $('#x2').val(c.x2); $('#y2').val(c.y2); $('#w').val(c.w); $('#h').val(c.h); }; });
JavaScript
// ------------------------------- // Demos // ------------------------------- $(document).ready( function() { $('.popovers').popover({container: 'body', trigger: 'hover', placement: 'top'}); //bootstrap's popover $('.tooltips').tooltip(); //bootstrap's tooltip $(".chathistory").niceScroll({horizrailenabled:false}); //chathistory scroll try { //Set nicescroll on notifications $(".scrollthis").niceScroll({horizrailenabled:false}); $('.dropdown').on('shown.bs.dropdown', function () { $(".scrollthis").getNiceScroll().resize(); $(".scrollthis").getNiceScroll().show(); }); $('.dropdown').on('hide.bs.dropdown', function () { $(".scrollthis").getNiceScroll().hide(); }); $(window).scroll(function(){ $(".scrollthis").getNiceScroll().resize(); }); } catch(e) {} prettyPrint(); //Apply Code Prettifier $('.toggle').toggles({on:true}); //EasyPieChart in rightbar try { $('.easypiechart#serverload').easyPieChart({ barColor: "#e73c3c", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'round', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('.easypiechart#ramusage').easyPieChart({ barColor: "#f39c12", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'round', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); } catch(error) {} $("#currentbalance").sparkline([12700,8573,10145,21077,15380,14399,19158,23911,15401,16793,13115,23315], { type: 'bar', barColor: '#62bc1f', height: '45', barWidth: 7}); }); // ------------------------------- // Demo: Chatbar. // ------------------------------- $('.chatinput textarea').keypress(function (e) { if (e.which == 13) { var chatmsg = $(".chatinput textarea").val(); var oo=$(".chathistory").html(); var d=new Date(); var n=d.toLocaleTimeString(); if (!!$(".chatinput textarea").val()) $(".chathistory").html(oo+ "<div class='chatmsg'><p>"+chatmsg+"</p><span class='timestamp'>"+n+"</span></div>"); $(".chathistory").getNiceScroll().resize(); $(".chathistory").animate({ scrollTop: $(document).height() }, 0); $(this).val(''); // empty textarea return false; } }); // Toggle buttons $("a#hidechatbtn").click(function () { $("#widgetarea").toggle(); $("#chatarea").toggle(); }); $("#chatbar li a").click(function () { $("#widgetarea").toggle(); $("#chatarea").toggle(); }); // ------------------------------- // Show Theme Settings // ------------------------------- $('#slideitout').click(function() { $('#demo-theme-settings').toggleClass('shown'); return false; }); // ------------------------------- // Demo: Theme Settings // ------------------------------- // Demo Fixed Header if($.cookie('fixed-header') === 'navbar-static-top') { $('#fixedheader').toggles(); } else { $('#fixedheader').toggles({on:true}); } $('.dropdown-menu').on('click', function(e){ if($(this).hasClass('dropdown-menu-form')){ e.stopPropagation(); } }); $('#fixedheader').on('toggle', function (e, active) { $('header').toggleClass('navbar-fixed-top navbar-static-top'); $('body').toggleClass('static-header'); rightbarTopPos(); if (active) { $.removeCookie('fixed-header'); } else { $.cookie('fixed-header', 'navbar-static-top'); } }); // Demo Color Variation // Read the CSS files from data attributes $("#demo-color-variations a").click(function(){ $("head link#styleswitcher").attr("href", 'assets/demo/variations/' + $(this).data("theme")); $.cookie('theme',$(this).data("theme")); return false; }); $("#demo-header-variations a").click(function(){ $("head link#headerswitcher").attr("href", 'assets/demo/variations/' + $(this).data("headertheme")); $.cookie('headertheme',$(this).data("headertheme")); return false; }); //Demo Background Pattern $(".demo-blocks").click(function(){ $('.fixed-layout').css('background',$(this).css('background')); return false; });
JavaScript
jQuery(document).ready(function() { jQuery('#worldmap').vectorMap({ map: 'world_en', backgroundColor: 'transparent', color: '#f5f5f5', hoverOpacity: 0.7, selectedColor: '#0264d2', enableZoom: true, showTooltip: true, values: sample_data, scaleColors: ['#7cb4f2', '#1e80ee'], normalizeFunction: 'polynomial' }); jQuery('#usamap').vectorMap({ map: 'usa_en', backgroundColor: 'transparent', color: '#509BBD', hoverOpacity: 0.7, selectedColor: '#1278a6', enableZoom: true, showTooltip: true, values: sample_data, scaleColors: ['#C8EEFF', '#006491'], normalizeFunction: 'polynomial' }); jQuery('#euromap').vectorMap({ map: 'europe_en', backgroundColor: 'transparent', color: '#dddddd', hoverOpacity: 0.7, selectedColor: '#1dda1d', enableZoom: true, showTooltip: true, values: sample_data, scaleColors: ['#b6ddb7', '#51d951'], normalizeFunction: 'polynomial' }); });
JavaScript
jQuery.extend({ tooltip:function(s){ var mainElement=$('#'+s.mainElement); var tipElement=$('#'+s.tipElement); var width=s.width? s.width : 200; var top=s.top? s.top : 10; var left=s.left? s.left : 15; tipElement.css('width', width); mainElement.bind('mouseover', function(e){ x=e.pageX || event.clientX; y=e.pageY || event.clientY; tipElement.css('top', (y-top<0? y+top : y-top)); tipElement.css('left', x+left); tipElement.fadeIn('fast'); }); mainElement.bind('mouseout', function(){ tipElement.fadeOut('fast'); }); mainElement.bind('mousemove', function(e){ x=e.pageX || event.clientX; y=e.pageY || event.clientY; tipElement.css('top', (y-top<0? y+top : y-top)); tipElement.css('left', x+left); }); } });
JavaScript
function q(id) { if(document.getElementById(id)){ obj=document.getElementById(id); }else{ obj=document.getElementsByName(id); if(obj){ obj=obj[0]; } } return obj; }
JavaScript
jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) { var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />'); if(typeof uri== 'boolean'){ io.src = 'javascript:false'; } else if(typeof uri== 'string'){ io.src = uri; } } else { var io = document.createElement('iframe'); io.id = frameId; io.name = frameId; } io.style.position = 'absolute'; io.style.top = '-1000px'; io.style.left = '-1000px'; document.body.appendChild(io); return io }, createUploadForm: function(id, fileElementId) { //create form var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); var oldElement = $('#' + fileElementId); var newElement = $(oldElement).clone(); $(oldElement).attr('id', fileId); $(oldElement).before(newElement); $(oldElement).appendTo(form); //set attributes $(form).css('position', 'absolute'); $(form).css('top', '-1200px'); $(form).css('left', '-1200px'); $(form).appendTo('body'); return form; }, ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = new Date().getTime() var form = jQuery.createUploadForm(id, s.fileElementId); var io = jQuery.createUploadIframe(id, s.secureuri); var frameId = 'jUploadFrame' + id; var formId = 'jUploadForm' + id; // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) {//alert('start'); jQuery.event.trigger( "ajaxStart" ); } var requestDone = false; // Create the request object var xml = {} if ( s.global ) jQuery.event.trigger("ajaxSend", [xml, s]); // Wait for a response to come back var uploadCallback = function(isTimeout) { var io = document.getElementById(frameId); try { alert('er6'); if(io.contentWindow) { xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument) { xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null; xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; } }catch(e) {//alert(e);alert('er'); jQuery.handleError(s, xml, null, e); } if ( xml || isTimeout == "timeout") { requestDone = true; var status; try {//alert('er7'); status = isTimeout != "timeout" ? "success" : "error"; // Make sure that the request was successful or notmodified if ( status != "error" ) { // process the data (runs the xml through httpData regardless of callback) var data = jQuery.uploadHttpData( xml, s.dataType ); // If a local callback was specified, fire it and pass it the data if ( s.success ) s.success( data, status ); // Fire the global callback if( s.global ) jQuery.event.trigger( "ajaxSuccess", [xml, s] ); } else{alert(e);alert('er'); jQuery.handleError(s, xml, status);} } catch(e) {alert(e);alert('er3'); status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if( s.global ) jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); // Process result if ( s.complete ) s.complete(xml, status); jQuery(io).unbind() setTimeout(function() { try {//alert('er8'); $(io).remove(); $(form).remove(); } catch(e) {//alert(e);alert('er4'); jQuery.handleError(s, xml, null, e); } }, 100) xml = null } }alert('finish call'); // Timeout checker if ( s.timeout > 0 ) { setTimeout(function(){ // Check to see if the request is still happening if( !requestDone ) uploadCallback( "timeout" ); }, s.timeout); } try {//alert('er9');alert(s.timeout); // var io = $('#' + frameId); var form = $('#' + formId); $(form).attr('action', s.url); $(form).attr('method', 'POST'); $(form).attr('target', frameId); if(form.encoding) { form.encoding = 'multipart/form-data'; } else { form.enctype = 'multipart/form-data'; } $(form).submit(); } catch(e) { //alert(e);alert('er5'); jQuery.handleError(s, xml, null, e); } if(window.attachEvent){ document.getElementById(frameId).attachEvent('onload', uploadCallback); } else{ document.getElementById(frameId).addEventListener('load', uploadCallback, false); } return {abort: function () {}}; }, uploadHttpData: function( r, type ) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context if ( type == "script" ) jQuery.globalEval( data ); // Get the JavaScript object, if JSON is used. if ( type == "json" ) eval( "data = " + data ); // evaluate scripts within html if ( type == "html" ) jQuery("<div>").html(data).evalScripts(); //alert($('param', data).each(function(){alert($(this).attr('value'));})); return data; } })
JavaScript
// Config.js, Version 1.1, 2005/04 // Copyright (C) 2004 by Hans Bauer, Schillerstr. 30, D-73072 Donzdorf // http://www.h-bauer.de // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation. // // History: // Version 1.1: Including the autoclose-feature // function config(name, tree, title, tooltip) { //>config this.name = name; this.tree = tree; // this.title = title; this.titelTTip = tooltip; // this.lines = true; this.linesTxt = 'Show Lines'; // this.linesTTip = 'Lines indicate hierarchy'; // this.icons = true; this.iconsTxt = 'Show Symbols'; // this.iconsTTip = 'Symbols indicate node status';// this.aclose = false; this.acloseTxt = 'Autoclose subtrees'; // this.acloseTTip = 'Autoclose left subtrees'; // this.cookies = false; this.cookiesTxt = 'Save Cookies'; // this.cookiesTTip= 'Stores tree configuration'; // this.expireTxt= 'days'; this.expireTTip = 'Cookie expiration period'; // this.level = -1; this.levelTxt = 'Open Level'; this.levelTTip = 'Open tree up to this level'; // this.helpTxt = 'Help'; this.helpTTip = 'Items show tooltips'; // this.helpAlert= 'Tooltips are shown on mouse-over'; } // // ------------- TextOf ... ------------ config.prototype.textOfLines = function(text, tooltip) { //>TextOfLines (show lines) this.linesTxt = text; this.linesTTip = tooltip; } // config.prototype.textOfIcons = function(text, tooltip) { //>TextOfIcons (show symbols) this.iconsTxt = text; this.iconsTTip = tooltip; } // config.prototype.textOfAClose= function(text,tooltip) { //>TextOfAClose (autoclose) this.acloseTxt= text; this.acloseTTip=tooltip; } // config.prototype.textOfCookies = function(text, tooltip) { //>TextOfCookies this.cookiesTxt = text; this.cookiesTTip = tooltip; } // config.prototype.textOfExpire = function(text, tooltip) { //>TextOfExpire this.expireTxt = text; this.expireTTip = tooltip; } // config.prototype.textOfLevel = function(text, tooltip) { //>TextOfLevel this.levelTxt = text; this.levelTTip = tooltip; } // config.prototype.textOfHelp = function(text, tooltip, alert) { //>TextOfHelp this.helpTxt = text; this.helpTTip = tooltip; this.helpAlert = alert; } // // ---------- Build Html-Code ---------- config.prototype.toString = function() { //>ToString var str = '<form><div class="Config">'; // Encapsulate class 'Config' in a form var icon = (this.tree.showIcons) ? 'gif/config.gif' : 'gif/minicon.gif'; // Decide icon = config- or minIcon.gif str += '<a href="javascript: ' + this.name + '.toggle()">' // Config-icon: + '<img id="' + this.name + 'ConfigGif"' // Write Html-string for the image + ' src="' + icon + '" alt="" /></a>'; // and a reference to this -> toggle str += '<a href="javascript: ' + this.name + '.toggle()"' // Config-text + ' id="' + this.name + 'ConfigTxt" class="ConfigText"' // Write Html-string for the text + ' title="' + this.titelTTip + '">' // in class 'Text' with tooltip + this.title + '</a>'; // and a reference to this -> toggle str += '<div id="' + this.name + 'SubTree"' // SubTree-block (default is invisible: + ' class="SubTree" style="display:none">'; // to show or hide the SubTree str += '<img src="gif/empty.gif" alt="" />' // Show Lines: + '<input type="checkbox" name="Lines" value="Lines"' // Checkbox: Name & value is 'Lines' + ' id="' + this.name + 'LinesCheck"' // ID for checkbox + ' onClick="javascript: ' + this.name + '.changeLines()">' // OnClick -> java.changeLines + '<a id="' + this.name + 'LinesTxt" class="Text"' // Text: Define ID and class + ' title="' + this.linesTTip + '">' + this.linesTxt + '</a><br>'; // Write tooltip and text str += '<img src="gif/empty.gif" alt="" />' // Show Icons: + '<input type="checkbox" name="Icons" value="Icons"' // Checkbox: Name & value is 'Icons' + ' id="' + this.name + 'IconsCheck"' // ID for checkbox + ' onClick="javascript: ' + this.name + '.changeIcons()">' // OnClick -> java.changeIcons + '<a id="' + this.name + 'IconsTxt" class="Text"' // Text: Define ID and class + ' title="' + this.iconsTTip + '">' + this.iconsTxt + '</a><br>'; // Write tooltip and text str += '<img src="gif/empty.gif" alt="" />' // Autoclose: + '<input type="checkbox" name="AClose" value="AClose"' // Checkbox: Name & value is 'AClose' + ' id="' + this.name + 'ACloseCheck"' // ID for checkbox + ' onClick="javascript: ' + this.name + '.changeAClose()">' // OnClick -> java.changeAClose + '<a id="' + this.name + 'ACloseTxt" class="Text"' // Text: Define ID and class + ' title="' + this.acloseTTip + '">' + this.acloseTxt + '</a><br>'; // Write tooltip and text str += '<img src="gif/empty.gif" alt="" />' // Use Cookies: + '<input type="checkbox" name="Cookies" value="Cookies"' // Checkbox: Name & value is 'Cookies' + ' id="' + this.name + 'CookiesCheck"' // ID for checkbox + ' onClick="javascript: ' + this.name + '.changeCookies()">' // OnClick -> java.changeCookies + '<a id="' + this.name + 'CookiesTxt" class="Text"' // Text: Define ID and class + ' title="' + this.cookiesTTip + '">' + this.cookiesTxt + '</a><br>'; // Write tooltip and text str += '<img src="gif/empty.gif" alt="" /><img src="gif/empty.gif" alt="" />' // Expire period of cookies + '&nbsp;<select name="Expire" size="1"' // Select options 'Expire' + ' id="' + this.name + 'ExpireList"' // ID for options + ' onClick="' + this.name + '.changeExpire()">'; // OnClick -> call this.changeExpire for (i=0; i<7; i++) str += '<option>' + Math.pow(2,i) + '</option>'; // Loop: include options 1, 2, 4,... str += '</select>' // Close 'Expire'-select + '<a id="' + this.name + 'ExpireTxt" class="Text"' // Text: Define ID and class + ' title="' + this.expireTTip + '">' + this.expireTxt + '</a><br>'; // Write tooltip and text str += '<img src="gif/empty.gif" alt="" />'; // Open Level: str += '<select name="Level" size="1"' // Select options 'Level + ' id="' + this.name + 'LevelList"' // ID for options + ' onClick="' + this.name + '.clickLevel()">' // OnClick -> call this.clickLevel + '<option>-</option>'; // Option '-' str += '</select>' // End of 'select' + '<a id="' + this.name + 'LevelTxt" class="Text"' // Text: Define ID and class + ' title="' + this.levelTTip + '">' + this.levelTxt + '</a><br>'; // Write tooltip and text str += '<img src="gif/empty.gif" alt="" />' // Help: + '<a href="javascript: ' + this.name + '.help()">' // Icon: + '<img id="' + this.name + 'HelpGif"' // Write Html-string for the image + ' src="gif/help.gif" alt="" /></a>'; // and a reference to this -> toggle str += '<a href="javascript: ' + this.name + '.help()"' // Text + ' id="' + this.name + 'HelpTxt" class="Text"' // Write Html-string for the text + ' title="' + this.helpTTip + '">' // in class 'Text' with tooltip + this.helpTxt + '</a>'; // and a reference to this -> help str += '<hr></div></div></form>'; // Close SubTree, class 'Config', form return str; } // Return Html-string config.prototype.toggle = function() { //>Toggle config tree subTree = document.getElementById(this.name + 'SubTree'); // Get element: SubTree status = subTree.style.display; // Status of the SubTree (open/close) subTree.style.display = (status=='none') ? 'block' : 'none'; // Toggle SubTree-status if (subTree.style.display=='block') this.updateOnOpen(); } // UpdateOnOpen this using tree.values config.prototype.updateOnOpen = function() { //>Update config-tree on opening var check; // Initialize 'check' check = document.getElementById(this.name + 'LinesCheck'); // Lines checkbox check.checked = (this.tree.showLines) ? true : false; // Get setting from 'tree' check = document.getElementById(this.name + 'IconsCheck'); // Icons checkbox check.checked = (this.tree.showIcons) ? true : false; // Get setting from 'tree' check = document.getElementById(this.name + 'ACloseCheck'); // Icons checkbox check.checked = (this.tree.autoclose) ? true : false; // Get setting from 'tree' check = document.getElementById(this.name + 'CookiesCheck'); // Cookies checkbox check.checked = (this.tree.useCookies) ? true : false; // Get setting from 'tree' this.updateExpireList(); // Update Expire-list this.fillLevelList(); } // Fill Level-list config.prototype.updateExpireList = function() { //>UpdateExpireList for (i=0; i<7; i++) if (Math.pow(2,i)==this.tree.expire) break; // Loop to find the tree's expire var list = document.getElementById(this.name + 'ExpireList'); // Expire list list.selectedIndex = i; } // Select appropriate option config.prototype.fillLevelList = function() { //>FillLevelList var list = document.getElementById(this.name + 'LevelList'); // Level list if (list.length>1) return; // List already filled -> nothing for (i=0; i<=this.tree.maxIndent; i++) { // Loop levels up to maxIndent of tree var item = new Option(i,i,false,false); // Options 0, 1,... maxIndent-1 list.options[list.length] = item; } } // Append next indent-number config.prototype.changeLines = function() { //>ChangeLines (Checkbox Show Lines) var check = document.getElementById(this.name + 'LinesCheck'); // Lines checkbox this.tree.lines(check.checked); } // Transfer setting to 'tree' config.prototype.changeIcons = function() { //>ChangeIcons (Checkbox Show Icons) var icon = document.getElementById(this.name + 'ConfigGif'); // Main icon of config-tree: var check = document.getElementById(this.name + 'IconsCheck'); // Icons checkbos icon.src = (check.checked) ? 'gif/config.gif' : 'gif/minIcon.gif'; // Show or hide main icon of this this.tree.icons(check.checked); } // Show or hide the icons of the tree config.prototype.changeAClose = function() { //>ChangeAClose (Checkbox Autoclose) var check = document.getElementById(this.name + 'ACloseCheck'); // Autoclose checkbox this.tree.setAutoclose(check.checked); } // Transfer setting to 'tree' config.prototype.changeCookies = function() { //>ChangeCookies (Checkbox Use Cookies) var check = document.getElementById(this.name + 'CookiesCheck'); // Cookies checkbox this.tree.cookies(check.checked); } // Transfer setting to 'tree' config.prototype.changeExpire = function() { //>ChangeExpire (Listbox expire) var list = document.getElementById(this.name + 'ExpireList'); // ExpireList, IE fakes 'list.value' this.tree.expiration(Math.pow(2,list.selectedIndex)); } // Transfer selected option to 'tree' config.prototype.clickLevel = function() { //>ClickLevel var list = document.getElementById(this.name + 'LevelList'); // Level list if (this.level==list.selectedIndex-1) this.level = -1; // Invalidate level on opening options else { this.level = list.selectedIndex - 1; // Else: Get selected level and if (this.level>=0) this.tree.level(this.level); } } // apply selected level in tree config.prototype.help = function() { alert(this.helpAlert); } //>Help message on click
JavaScript
// default.js, Version 1.1, 2005/04 // Copyright (C) 2004 by Hans Bauer, Schillerstr. 30, D-73072 Donzdorf // http://www.h-bauer.de // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation. // History: // Version 1.1: Enhanced detection of the relative pathD of the document // function loaded(document) { //>Loaded a document if (0==parent.frames.length) return; // Only if frames are used var pathDocu = backslashToSlash(document.location.pathname); // Path of the document with '/' var pathMenu = backslashToSlash(parent.menu.document.location.pathname); // Path of the menu-file with '/' var common = 0; // common = Number of common characters var minLen = pathDocu.length; // minLen = Min( pathlength of Docu if (minLen > pathMenu.length) minLen = pathMenu.length; // or pathlength of Menu ) for (var i=0; i<minLen; i++) { // Loop over minLen: if (pathDocu.charAt(i)!=pathMenu.charAt(i)) { common = i; break; } } // Equal character -> increase common var pathRel = ''; // Initialize relative path for (var i=common; i<pathMenu.length; i++) { // Loop substring behind 'common' if (pathMenu.charAt(i)=='/') pathRel = pathRel + '../'; } // Each '/' leads to '../' in pathRel pathRel = pathRel + pathDocu.substr(common); // Add remaining pathDocu to pathRel if (parent.menu.tree) parent.menu.tree.selectPath(pathRel); } // Select appropriate node in menu function backslashToSlash(path) { //>BackslashToSlash var parts = path.split("\\"); // Split path at '\' into string-array var str = parts[0]; // Write first part to 'str' for (var i=1; i<parts.length; i++) str = str + '/' + parts[i]; // Add next parts divided by '/' return str; } // Return path with '/' instead of '\'
JavaScript
// TreeMenu.js, Version 1.1, 2005/04 // Copyright (C) 2004 by Hans Bauer, Schillerstr. 30, D-73072 Donzdorf // http://www.h-bauer.de // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation. // History: // Version 1.1: Minor bug-fixes, direct access // - writeNodeSymbol(): Remove a faulty '")' from the html-code // - several routines: Allways use the keyword 'var' for new variables // due to problems with the internet explorer // when reloading pages with new menus // - Description for direct access to preselect a page with a query // - Classes 'SubTree_i' for subtrees of menu-items with indent=i // - Autoclose the subtree you left by selecting from another subtree // - Cookies now also save the name of the tree -> each tree uses own cookies // function Node(id,id2,indent,text,target,url,tooltip,iconOpen,iconClose,isOpen) { //>Node (Folder or Item) this.id = id; this.indent = indent; // Initialize variables this.text = text; this.target = target; // .. .. this.url = url; this.tooltip = tooltip; // .. .. this.iconOpen = iconOpen; this.iconClose = iconClose; // .. .. this.parent = null; this.childs = []; // .. .. this.isOpen = isOpen; this.id2 = id2; } // .. .. function treemenu(name, showLines, showIcons, useCookies, imageURL) { //>treemenu this.name = name; this.showLines = showLines; // Initialize variables this.showIcons = showIcons; this.useCookies= useCookies; // .. .. this.nodes = []; this.root = new Node(-1,-1,'root'); // .. .. this.selected = -1; this.maxIndent = 0; // .. .. this.expire = 1; this.openNodes = ''; // .. .. this.classDepth= 2; this.autoclose = false; // ClassDepth for text-format-> css-file this.readCookies(); // Read cookies if available if (!navigator.cookieEnabled) this.useCookies = false; // Respect the browsers cookie setting if (arguments.length>=5) this.autoclose = arguments[4]; // Optional argument for 'autoclose' this.defaults = { // Default images/icons iconRoot : imageURL+'/images/root.gif', iconItem : imageURL+'/images/item.gif', // .. .. iconOpen : imageURL+'/images/open.gif', iconClose : imageURL+'/images/close.gif', // .. .. passLine : imageURL+'/images/passline.gif', empty : imageURL+'/images/empty.gif', // .. .. tieLine : imageURL+'/images/tieline.gif', tiePlus : imageURL+'/images/tieplus.gif', // .. .. endLine : imageURL+'/images/endline.gif', endPlus : imageURL+'/images/endplus.gif', // .. .. rectPlus : imageURL+'/images/rectplus.gif', tieMinus : imageURL+'/images/tieminus.gif', // .. .. rectMinus : imageURL+'/images/rectminus.gif', endMinus : imageURL+'/images/endminus.gif', // .. .. minIcon : imageURL+'/images/minicon.gif' } } // // ----------- Build up menu ----------- treemenu.prototype.put = function(id2, open, label, target, url, //>Put a node to the treemenu tooltip, iconOpen, iconClose) { // that is initially to be loaded if (this.selected==-1) this.selected = this.nodes.length; // Set 'selected' if not cookie-defined this.add(id2, open, label, target, url, tooltip, iconOpen, iconClose); } // Add a node to the treemenu treemenu.prototype.add = function(id2, open, label, target, url, //>Add a node to the treemenu tooltip, iconOpen, iconClose) { // var indent = 0; // Indent: initialize while (label.charAt(indent)==' ') indent++; // Indent by leading spaces if (this.maxIndent<indent) this.maxIndent = indent; // Adjust 'maxIndent' var id = this.nodes.length; // ID of the new node var isOpen = (open==0) ? false : true; // IsOpen from given value '0' or '1' if (this.openNodes && id<this.openNodes.length) // On given 'OpenNodes' isOpen = (this.openNodes.charAt(id)=='1') ? true : false; // -> Status depending on cookie var node = new Node(id, id2, indent, label.substr(indent), // New node: ID corresponds with number target, url, tooltip, iconOpen, iconClose, isOpen); // Text without leading spaces this.nodes[this.nodes.length] = node; // Append node to the nodes-array for (var i=this.nodes.length-1; i>=0; i--) // Parent node: if (this.nodes[i].indent < indent) { node.parent = this.nodes[i]; break; } // Loop back to find parent by indent if (!node.parent) node.parent = this.root; // Root-node is parent if none found if (node.parent.indent<node.indent-1) // Invalid indent alert('Indent of "' + node.text + '" must be <' + (node.parent.indent+2)); // -> alert-message node.parent.childs[node.parent.childs.length] = node; } // New node is child of the parent // ---------- Build Html-code ---------- treemenu.prototype.toString = function() { //>ToString used by document.write(...) var str = '<div class="TreeMenu">'; // Encapsulate class 'TreeMenu' var lastIndent = 0; // Initialize lastIndent for (var id=0; id<this.nodes.length; id++) { // Loop: Nodes var node = this.nodes[id] // Current node if (lastIndent < node.indent) lastIndent = node.indent; // Update lastIndent to max while (lastIndent>node.indent) { str += '</div>'; lastIndent--; } // Close previous </div>-Subtrees str += this.writeNode(node); // Write node if (0<node.childs.length) { // Parent -> SubTree of childs str += '<div id="' + this.name + 'SubTree_' + id // -> Write <div..-block to display + '" class="SubTree_' + node.indent // or to hide the SubTree + '" style="display:' // according to isOpen-value + ((node.isOpen) ? 'block' : 'none') + '">'; } } // + Defining class SubTree_x for (var i=lastIndent; i>0; i--) str += '</div>'; // Close remaining SubTrees str += this.writeCreatedWithTreeMenu(); // Write CreatedWithTreeMenu str += '</div>'; // Close class 'TreeMenu' this.setCookies(this.expire); // Set Cookies this.loadSelected(); // LoadSelected on already filled frames // alert(str); // Discomment to see the Html-Code return str; } // Return HTML-String // -------------- Write ---------------- treemenu.prototype.writeNode = function(node) { //>WriteNode if (node.target=='hide') return ''; // Only node with no hidden target var str = '<div>' // Open <div>-block for the node + this.writeIndenting(node) + this.writeTieUpIcon(node) // Write Indenting, tieUpIcon + this.writeNodeSymbol(node) + this.writeNodeText(node) + '</div>'; // Symbol, Text, close 'TreeNode' return str; } // Return cumulated Html-String treemenu.prototype.writeIndenting = function(node) { //>WriteIndenting if (node.indent < 2) return ''; // Only if node-indent >= 2 var str = ''; // Initialize str var icons = []; // icons[] var ancestor = node.parent; // Start at ancestor = node.parent for (var i=node.indent-2; i>=0; i--, ancestor=ancestor.parent) { // Loop ancestors from right to left icons[i] = (this.isLastChild(ancestor) ? 'empty' : 'passLine'); } // Last child -> empty, else passLine for (var i=0; i<=node.indent-2; i++) { // Loop from left to right: var icon = this.defaults.empty; // Default icon = empty if (this.showLines && icons[i]!='empty') icon = this.defaults.passLine; // or passLine to be shown str += '<img name="' + icons[i] + '" src="' + icon + '" alt="" />'; } // Html-string for the icon return str; } // Return html-string treemenu.prototype.writeTieUpIcon = function(node) { //>WriteTieUpIcon if (node.indent < 1) return ''; // Only for indents > 1 var icon = this.getTieUpIcon(node); // GetTieUpIcon var str = ''; // Initialize str if (0==node.childs.length) // No childs -> Return only TieUpIcon str = '<img id="' + this.name + 'TieUp_' + node.id // Write tieUpIcon with + '" src="' + icon + '" alt="" />'; // name & source else str = '<a href="javascript: ' + this.name + '.toggle(' + node.id + ')">' // Parent node: + '<img id="' + this.name + 'TieUp_' + node.id // Write tieUpIcon with + '" src="' + icon + '" alt="" /></a>'; // name, source & javascript:toggle return str; } // Html-code for the TieUpIcon treemenu.prototype.getTieUpIcon = function(node) { //>GetTieUpIcon if (0 == node.childs.length) { // No childs: if (!this.showLines) return this.defaults.empty; // Don't show Lines -> empty else if (this.isLastChild(node)) return this.defaults.endLine; // Else if last child -> endLine else return this.defaults.tieLine; } // Else if fore child -> tieLine else if (node.isOpen) { // Open parent: if (!this.showLines) return this.defaults.rectMinus; // Don't show Lines -> rectMinus else if (this.isLastChild(node)) return this.defaults.endMinus; // Else if last child -> endMinus else return this.defaults.tieMinus; } // Else if fore child -> tieMinus else { // Closed parent: if (!this.showLines) return this.defaults.rectPlus; // Don't show Lines -> rectPlus else if (this.isLastChild(node)) return this.defaults.endPlus; // Else if last child -> endPlus else return this.defaults.tiePlus; } } // Else if fore child -> tiePlus treemenu.prototype.writeNodeSymbol = function(node) { //>WriteNodeSymbol var icon = this.getNodeSymbol(node) ; // GetNodeSymbol if (0==node.childs.length) { // No childs: var str = ''; // Reference to the nodes url if (node.url) { str += '<a href="' + node.url + '"'; // if a url is given and load if (node.target) str += ' target="' + node.target + '"'; // the url into the target frame. str += '>'; } // Close leading <a..>-tag str += '<img id="' + this.name + 'Symbol_' + node.id // Write the Html-code for the + '" src="' + icon + '" alt="" />'; // image of the node-symbol if (node.url) str += '</a>'; // Close trailing </a>-tag if any return str; } // Return Html-string for symbol return '<a href="javascript: ' + this.name + '.toggle(' + node.id + ')">' // Parent: + '<img id="' + this.name + 'Symbol_' + node.id // Write Html-string for the image + '" src="' + icon + '" alt="" /></a>'; } // and a reference to java -> toggle treemenu.prototype.getNodeSymbol = function(node) { //>GetNodeSymbol if (!this.showIcons) return this.defaults.minIcon; // No Symbols-> 'minIcon' (for IE) if (0==node.childs.length) { // No childs: if (node.iconOpen) return node.iconOpen; // Use nodes 'iconOpen' else return this.defaults.iconItem; } // or default 'iconItem' else if (node.isOpen) { // Open parent: if (node.iconOpen) return node.iconOpen; // Use nodes 'iconOpen' else return this.defaults.iconOpen; } // or default 'iconOpen' else { // Closed parent: if (node.iconClose) return node.iconClose; // Use nodes 'iconClose' else return this.defaults.iconClose; } } // or default 'iconClose' treemenu.prototype.writeNodeText = function(node) { //>WriteNodeText var cls = this.getNodeTextClass(node, this.selected); // Get NodeTextClass var str = '<a id="' + this.name + 'Node_' + node.id + '" class="' + cls + '"'; // Add '<a id=...' and 'class=...' if (node.url) str += ' href="' + node.url + '"'; // HRef-link to node.url else str += ' href="javascript: '+this.name+'.toggle('+node.id+')"'; // or to java.toggle if (node.url && node.target) str += ' target="' + node.target + '"'; // Target ="node.target" if (node.tooltip) str += ' title="' + node.tooltip + '"'; // Title ="node.tooltip" str += ' onclick="javascript: ' + this.name + '.pick(\'' + node.id + '\')"'; // OnClick="javascript.pick" //str += ' onmouseover="javascript: display_info(' + node.id2 + ');"'; // OnClick="javascript.pick" str += '>' + node.text + ((node.url) ? '</a>' : '</a>') ; // Node text, close 'a>' return str; } // Return HTML-string treemenu.prototype.getNodeTextClass = function(node, selectID) { //>GetNodeTextClass for TreeMenu.css var cls = (node.id==selectID) ? 'Selected' : 'Node'; // Class 'Selected', 'Node' if (!node.url) cls = 'Item'; // or 'Item' (without url) return cls + '_' + Math.min(node.indent, this.classDepth); } // Append '_indent' or '_classDepth' treemenu.prototype.writeCreatedWithTreeMenu = function() { //>WriteCreatedWithTreeMenu var str = ''; return str; } // --------------- Load ---------------- treemenu.prototype.loadSelected = function() { this.loadNode(this.selected); } //>LoadSelected treemenu.prototype.loadNode = function(id) { //>LoadNode by ID into it's target frame if (id<0 || id>=this.nodes.length) return; // Only nodes with valid id if (this.nodes[id].target=='hide') return; // Only nodes with no hidden target for (var i=0; i<parent.frames.length; i++) { // Loop: Frames in frameset if (parent.frames[i].name==this.nodes[id].target) { // Target-frame of the selected node parent.frames[i].location.href = this.nodes[id].url; // -> Reference to the node to load break; } } } // Break the loop and return // ----------- Pick / Select ----------- treemenu.prototype.pick = function(id) { //>Pick a node by id var node = this.nodes[id]; // Picked node if (node.url) { // Nodes with URL (->no href to toggle) if (node.indent==0 && this.showIcons==false) this.toggle(id); // -> Toggle top node without icon else if (node.childs.length>0 && node.isOpen==false) this.toggle(id); } // Else: open closed parent node this.select(id); } // Select node by ID & unselect previous treemenu.prototype.select = function(id) { //>Select a node by a given ID if (id<0 || id>=this.nodes.length) return; // Only nodes with valid id if (!this.nodes[id].url) return; // Only for a node with url: if (this.autoclose==true) this.autocloseTree(id); // Autoclose the old tree (?) if (this.selected>=0 && this.selected<this.nodes.length) { // Deselect selected Html-node: var nodeA = document.getElementById(this.name + 'Node_' + this.selected); // Get selected Html-node by id var nameA = this.getNodeTextClass(this.nodes[this.selected],-1); // ClassName for unselected if (nodeA && nameA) nodeA.className = nameA; // Unselect previous selected node this.selected = -1; } // Invalidate this.selected var nodeB = document.getElementById(this.name + 'Node_' + id); // Select Html-node: var nameB = this.getNodeTextClass(this.nodes[id], id); // ClassName for selected if (nodeB && nameB) nodeB.className = nameB; // Selected previous unselected node this.selected = id; // Set this.selected value to id this.openAncestors(id); // Open the nodes ancestors this.setCookies(this.expire); } // Set cookies treemenu.prototype.selectPath = function(path) { //>SelectPath var path = this.pathWithSlash(path); // Ensure path with slash '/' if (this.selected>=0 && this.selected<this.nodes.length) { // A node ist already selected: var url = this.pathWithSlash(this.nodes[this.selected].url); // URL of the selected node if (url==path) return; } // URL already selected -> return for (var id=0; id<this.nodes.length; id++) { // Loop to search node: var url = this.pathWithSlash(this.nodes[id].url); // Node path with slash '/' if (url && url==path) { this.select(id); break; } } } // Equal path -> select node by id treemenu.prototype.openAncestors = function(id) { //>OpenAncestors of the node with id if (id<0) return; // Only valid nodes with ID>=0 var ancestor = this.nodes[id].parent; // Ancestor is parent node; while(ancestor.indent>=0) { // Loop: Ancestors if (!ancestor.isOpen) { ancestor.isOpen=true; this.updateNode(ancestor); } // Open and update ancestor ancestor = ancestor.parent; } } // Parent of ancestor } treemenu.prototype.pathWithSlash = function(path) { //>PathWithSlash var parts = path.split("\\"); // Split path at '\' into string-array var str = parts[0]; // Write first part to 'str' for (var i=1; i<parts.length; i++) str = str + '/' + parts[i]; // Add next parts divided by '/' return str; } // Return path with '/' instead of '\' // --------- Autoclose Tree ------------ treemenu.prototype.setAutoclose = function(bool) { this.autoclose = bool; } //>SetAutoclose variable treemenu.prototype.autocloseTree = function(id) { //>AutocloseTree for left subtree var current = this.getPathIDs(this.selected); // PathIDs of current selected node var picked = this.getPathIDs(id); // PathIDs of mewly picked node var minLen = (current.length<picked.length) ? current.length : picked.length; // Minimal number of path-steps for (var i=0; i<minLen; i++) { // Loop common ancestors: if (current[i]!=picked[i]) { // First uncommon ancestors var id = current[i]; // -> Get the node-id of the selected this.nodes[id].isOpen=false; // Close the associated subtree this.updateNode(this.nodes[id]); // Update the associated node return; } } } // Return: Autoclose is done treemenu.prototype.getPathIDs = function(id) { //>GetPathIDs (array of id's) var ids = new Array(this.nodes[id].indent+1); // Instantiate array[0,1..] of id's var ancestor = this.nodes[id]; // Self-ID while(ancestor.indent>=0) { // Loop ancestors: ids[ancestor.indent] = ancestor.id; // Store the id using the indent ancestor = ancestor.parent; } // Get next ancestor return ids; } // Return array of id's // ---------- Toggle / Update ---------- treemenu.prototype.toggle = function(id) { //>Toggle a node by id if (this.nodes[id].childs.length==0) return; // Only for parent nodes this.nodes[id].isOpen = !this.nodes[id].isOpen; // Toggle node-status (open or close) this.updateNode(this.nodes[id]); // Update the node this.setCookies(this.expire); } // Set cookies treemenu.prototype.updateNode = function(node) { //>UpdateNode var subTree = document.getElementById(this.name + 'SubTree_' + node.id); // Get Html-element: SubTree var tieUp = document.getElementById(this.name + 'TieUp_' + node.id); // TieUpIcon var symbol = document.getElementById(this.name + 'Symbol_' + node.id); // NodeSymbol if (subTree) subTree.style.display = (node.isOpen) ? 'block' : 'none'; // Update Html-elem. SubTree if (tieUp) tieUp.src = this.getTieUpIcon(node); // TieUpIcon if (symbol) symbol.src = this.getNodeSymbol(node); } // NodeSymbol // ----------- IsLastChild ------------- treemenu.prototype.isLastChild = function(node) { //>IsLastChild (?) var parent = node.parent; // Parent of the node return ((node == parent.childs[parent.childs.length-1]) ? true : false); } // Check for last child // --------- Level/Lines/Icons --------- treemenu.prototype.level = function(level) { //>Level to open/close menu for (var id=0; id<this.nodes.length; id++) { // Loop: nodes this.nodes[id].isOpen = (this.nodes[id].indent<level) ? true : false; // Open/close node depending on level this.updateNode(this.nodes[id]); } // Update the node this.setCookies(this.expire); } // Set cookies treemenu.prototype.lines = function(bool) { //>Lines to be shown (?) if (this.showLines == bool) return; // Nothing changed -> return this.showLines = bool; // Update 'showLines' var passLines = document.getElementsByName("passLine"); // Get PassLines if (!passLines) return; // Existing passLines: for (var i=0; i<passLines.length; i++) { // Loop: passLines passLines[i].src = (bool) ? this.defaults.passLine : this.defaults.empty; } // Update icon-source for (var id=0; id<this.nodes.length; id++) { // TieUpIcon for each node if (this.nodes[id].indent < 1) continue; // with indent >= 1 var tieUp = document.getElementById(this.name + 'TieUp_' + id); // TieUpIcon of the node if (tieUp) tieUp.src = this.getTieUpIcon(this.nodes[id]); } // Update icon-source this.setCookies(this.expire); } // Set cookies treemenu.prototype.icons = function(bool) { //>Icons to be shown (?) if (this.showIcons == bool) return; // Nothing changed -> return this.showIcons = bool; // Set 'showIcons'-value for (var id=0; id<this.nodes.length; id++) { // Loop: nodes var icon = this.getNodeSymbol(this.nodes[id]); // Get node symbol var image = document.getElementById(this.name + 'Symbol_' + id) // Get Html-image by id if (image) image.src = icon; } // Set image source to node symbol this.setCookies(this.expire); } // Set cookies // -------------- Cookies -------------- treemenu.prototype.expiration = function(expire) { //>Expiration this.expire = expire; this.setCookies(this.expire); } // Set/Save expiration period of cookies treemenu.prototype.cookies = function(bool) { //>Cookies to be used (?) if (bool) { this.useCookies = bool; this.setCookies(this.expire); } // Use cookies -> Set cookies else { this.setCookies(-1); this.useCookies = bool; } } // No cookies -> Clear existing cookies treemenu.prototype.setCookies = function(expire) { //>SetCookies this.openNodes = ''; // Initialize 'openNodes'-String for (var i=0; i<this.nodes.length; i++) // Loop: nodes this.openNodes += (this.nodes[i].isOpen) ? '1' : '0'; // Fill 'openNodes'-String this.setCookie("OpenNodes", this.openNodes, expire); // Set cookie 'OpenNodes' this.setCookie("ShowLines", this.showLines, expire); // 'ShowLines' this.setCookie("ShowIcons", this.showIcons, expire); // 'ShowIcons' this.setCookie("Selected", this.selected, expire); // 'Selected' this.setCookie("Autoclose", this.autoclose, expire); // 'Autoclose' this.setCookie("Expire" , this.expire, expire); } // 'Expire' treemenu.prototype.readCookies = function() { //>ReadCookies (as string!) var lines = this.getCookie("ShowLines"); // Get Cookie: 'ShowLines' var icons = this.getCookie("ShowIcons"); // 'ShowIcons' var select = this.getCookie("Selected"); // 'Selected' var autocl = this.getCookie("Autoclose"); // 'Autoclose' var open = this.getCookie("OpenNodes"); // 'OpenNodes' var expire = this.getCookie("Expire"); // 'Expire' if (lines) this.showLines = (lines=='true') ? true : false; // Set value of 'showLines' if (icons) this.showIcons = (icons=='true') ? true : false; // 'showIcons' if (select) this.selected = select; // 'selected' if (autocl) this.autoclose = autocl; // 'autoclose' if (open) this.openNodes = open; // 'openNodes' if (expire) this.expire = expire; // 'expire' if (lines || icons || select || open || autocl) this.useCookies = true; } // Cookies found -> useCookies is true // --------------- Cookie -------------- treemenu.prototype.setCookie = function(name, value, expire) { //>SetCookie by name and value if (!this.useCookies) return; // Only if cookies are to be used var exp = new Date(); // Actual date var end = exp.getTime() + (expire * 24 * 60 * 60 * 1000); // In 'expire'-days (-1: -> invalidate) exp.setTime(end); // Expire time of cookes document.cookie = this.name+name+'='+value+'; expires='+exp.toGMTString(); } // Set cookie with expiration-date treemenu.prototype.getCookie = function(name) { //>GetCookie value (as string!) var cookies = document.cookie; // Cookies separated by ';' var posName = cookies.indexOf(this.name + name + '='); // Start position of 'tree_name=' if (posName == -1) return ''; // Cookie not found -> Return '' var posValue = posName + this.name.length + name.length + 1; // Start position of cookie-value var endValue = cookies.indexOf(';',posValue); // End position of cookie value at ';' if (endValue !=-1) return cookies.substring(posValue, endValue); // ';' -> Return substring as value return cookies.substring(posValue); } // Else-> Return rest of line as value
JavaScript
// TreeMenu.js, Version 1.1, 2005/04 // Copyright (C) 2004 by Hans Bauer, Schillerstr. 30, D-73072 Donzdorf // http://www.h-bauer.de // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation. // History: // Version 1.1: Minor bug-fixes, direct access // - writeNodeSymbol(): Remove a faulty '")' from the html-code // - several routines: Allways use the keyword 'var' for new variables // due to problems with the internet explorer // when reloading pages with new menus // - Description for direct access to preselect a page with a query // - Classes 'SubTree_i' for subtrees of menu-items with indent=i // - Autoclose the subtree you left by selecting from another subtree // - Cookies now also save the name of the tree -> each tree uses own cookies // function Node(id,id2,indent,text,target,url,tooltip,iconOpen,iconClose,isOpen) { //>Node (Folder or Item) this.id = id; this.indent = indent; // Initialize variables this.text = text; this.target = target; // .. .. this.url = url; this.tooltip = tooltip; // .. .. this.iconOpen = iconOpen; this.iconClose = iconClose; // .. .. this.parent = null; this.childs = []; // .. .. this.isOpen = isOpen; this.id2 = id2; } // .. .. function treemenu(name, showLines, showIcons, useCookies, imageURL) { //>treemenu this.name = name; this.showLines = showLines; // Initialize variables this.showIcons = showIcons; this.useCookies= useCookies; // .. .. this.nodes = []; this.root = new Node(-1,-1,'root'); // .. .. this.selected = -1; this.maxIndent = 0; // .. .. this.expire = 1; this.openNodes = ''; // .. .. this.classDepth= 2; this.autoclose = false; // ClassDepth for text-format-> css-file this.readCookies(); // Read cookies if available if (!navigator.cookieEnabled) this.useCookies = false; // Respect the browsers cookie setting if (arguments.length>=5) this.autoclose = arguments[4]; // Optional argument for 'autoclose' this.defaults = { // Default images/icons iconRoot : imageURL+'/images/root.gif', iconItem : imageURL+'/images/item.gif', // .. .. iconOpen : imageURL+'/images/open.gif', iconClose : imageURL+'/images/close.gif', // .. .. passLine : imageURL+'/images/passline.gif', empty : imageURL+'/images/empty.gif', // .. .. tieLine : imageURL+'/images/tieline.gif', tiePlus : imageURL+'/images/tieplus.gif', // .. .. endLine : imageURL+'/images/endline.gif', endPlus : imageURL+'/images/endplus.gif', // .. .. rectPlus : imageURL+'/images/rectplus.gif', tieMinus : imageURL+'/images/tieminus.gif', // .. .. rectMinus : imageURL+'/images/rectminus.gif', endMinus : imageURL+'/images/endminus.gif', // .. .. minIcon : imageURL+'/images/minicon.gif' } } // // ----------- Build up menu ----------- treemenu.prototype.put = function(id2, open, label, target, url, //>Put a node to the treemenu tooltip, iconOpen, iconClose) { // that is initially to be loaded if (this.selected==-1) this.selected = this.nodes.length; // Set 'selected' if not cookie-defined this.add(id2, open, label, target, url, tooltip, iconOpen, iconClose); } // Add a node to the treemenu treemenu.prototype.add = function(id2, open, label, target, url, //>Add a node to the treemenu tooltip, iconOpen, iconClose) { // var indent = 0; // Indent: initialize while (label.charAt(indent)==' ') indent++; // Indent by leading spaces if (this.maxIndent<indent) this.maxIndent = indent; // Adjust 'maxIndent' var id = this.nodes.length; // ID of the new node var isOpen = (open==0) ? false : true; // IsOpen from given value '0' or '1' if (this.openNodes && id<this.openNodes.length) // On given 'OpenNodes' isOpen = (this.openNodes.charAt(id)=='1') ? true : false; // -> Status depending on cookie var node = new Node(id, id2, indent, label.substr(indent), // New node: ID corresponds with number target, url, tooltip, iconOpen, iconClose, isOpen); // Text without leading spaces this.nodes[this.nodes.length] = node; // Append node to the nodes-array for (var i=this.nodes.length-1; i>=0; i--) // Parent node: if (this.nodes[i].indent < indent) { node.parent = this.nodes[i]; break; } // Loop back to find parent by indent if (!node.parent) node.parent = this.root; // Root-node is parent if none found if (node.parent.indent<node.indent-1) // Invalid indent alert('Indent of "' + node.text + '" must be <' + (node.parent.indent+2)); // -> alert-message node.parent.childs[node.parent.childs.length] = node; } // New node is child of the parent // ---------- Build Html-code ---------- treemenu.prototype.toString = function() { //>ToString used by document.write(...) var str = '<div class="TreeMenu">'; // Encapsulate class 'TreeMenu' var lastIndent = 0; // Initialize lastIndent for (var id=0; id<this.nodes.length; id++) { // Loop: Nodes var node = this.nodes[id] // Current node if (lastIndent < node.indent) lastIndent = node.indent; // Update lastIndent to max while (lastIndent>node.indent) { str += '</div>'; lastIndent--; } // Close previous </div>-Subtrees str += this.writeNode(node); // Write node if (0<node.childs.length) { // Parent -> SubTree of childs str += '<div id="' + this.name + 'SubTree_' + id // -> Write <div..-block to display + '" class="SubTree_' + node.indent // or to hide the SubTree + '" style="display:' // according to isOpen-value + ((node.isOpen) ? 'block' : 'none') + '">'; } } // + Defining class SubTree_x for (var i=lastIndent; i>0; i--) str += '</div>'; // Close remaining SubTrees str += this.writeCreatedWithTreeMenu(); // Write CreatedWithTreeMenu str += '</div>'; // Close class 'TreeMenu' this.setCookies(this.expire); // Set Cookies this.loadSelected(); // LoadSelected on already filled frames // alert(str); // Discomment to see the Html-Code return str; } // Return HTML-String // -------------- Write ---------------- treemenu.prototype.writeNode = function(node) { //>WriteNode if (node.target=='hide') return ''; // Only node with no hidden target var str = '<div>' // Open <div>-block for the node + this.writeIndenting(node) + this.writeTieUpIcon(node) // Write Indenting, tieUpIcon + this.writeNodeSymbol(node) + this.writeNodeText(node) + '</div>'; // Symbol, Text, close 'TreeNode' return str; } // Return cumulated Html-String treemenu.prototype.writeIndenting = function(node) { //>WriteIndenting if (node.indent < 2) return ''; // Only if node-indent >= 2 var str = ''; // Initialize str var icons = []; // icons[] var ancestor = node.parent; // Start at ancestor = node.parent for (var i=node.indent-2; i>=0; i--, ancestor=ancestor.parent) { // Loop ancestors from right to left icons[i] = (this.isLastChild(ancestor) ? 'empty' : 'passLine'); } // Last child -> empty, else passLine for (var i=0; i<=node.indent-2; i++) { // Loop from left to right: var icon = this.defaults.empty; // Default icon = empty if (this.showLines && icons[i]!='empty') icon = this.defaults.passLine; // or passLine to be shown str += '<img name="' + icons[i] + '" src="' + icon + '" alt="" />'; } // Html-string for the icon return str; } // Return html-string treemenu.prototype.writeTieUpIcon = function(node) { //>WriteTieUpIcon if (node.indent < 1) return ''; // Only for indents > 1 var icon = this.getTieUpIcon(node); // GetTieUpIcon var str = ''; // Initialize str if (0==node.childs.length) // No childs -> Return only TieUpIcon str = '<img id="' + this.name + 'TieUp_' + node.id // Write tieUpIcon with + '" src="' + icon + '" alt="" />'; // name & source else str = '<a href="javascript: ' + this.name + '.toggle(' + node.id + ')">' // Parent node: + '<img id="' + this.name + 'TieUp_' + node.id // Write tieUpIcon with + '" src="' + icon + '" alt="" /></a>'; // name, source & javascript:toggle return str; } // Html-code for the TieUpIcon treemenu.prototype.getTieUpIcon = function(node) { //>GetTieUpIcon if (0 == node.childs.length) { // No childs: if (!this.showLines) return this.defaults.empty; // Don't show Lines -> empty else if (this.isLastChild(node)) return this.defaults.endLine; // Else if last child -> endLine else return this.defaults.tieLine; } // Else if fore child -> tieLine else if (node.isOpen) { // Open parent: if (!this.showLines) return this.defaults.rectMinus; // Don't show Lines -> rectMinus else if (this.isLastChild(node)) return this.defaults.endMinus; // Else if last child -> endMinus else return this.defaults.tieMinus; } // Else if fore child -> tieMinus else { // Closed parent: if (!this.showLines) return this.defaults.rectPlus; // Don't show Lines -> rectPlus else if (this.isLastChild(node)) return this.defaults.endPlus; // Else if last child -> endPlus else return this.defaults.tiePlus; } } // Else if fore child -> tiePlus treemenu.prototype.writeNodeSymbol = function(node) { //>WriteNodeSymbol var icon = this.getNodeSymbol(node) ; // GetNodeSymbol if (0==node.childs.length) { // No childs: var str = ''; // Reference to the nodes url if (node.url) { str += '<a href="' + node.url + '"'; // if a url is given and load if (node.target) str += ' target="' + node.target + '"'; // the url into the target frame. str += '>'; } // Close leading <a..>-tag str += '<img id="' + this.name + 'Symbol_' + node.id // Write the Html-code for the + '" src="' + icon + '" alt="" />'; // image of the node-symbol if (node.url) str += '</a>'; // Close trailing </a>-tag if any return str; } // Return Html-string for symbol return '<a href="javascript: ' + this.name + '.toggle(' + node.id + ')">' // Parent: + '<img id="' + this.name + 'Symbol_' + node.id // Write Html-string for the image + '" src="' + icon + '" alt="" /></a>'; } // and a reference to java -> toggle treemenu.prototype.getNodeSymbol = function(node) { //>GetNodeSymbol if (!this.showIcons) return this.defaults.minIcon; // No Symbols-> 'minIcon' (for IE) if (0==node.childs.length) { // No childs: if (node.iconOpen) return node.iconOpen; // Use nodes 'iconOpen' else return this.defaults.iconItem; } // or default 'iconItem' else if (node.isOpen) { // Open parent: if (node.iconOpen) return node.iconOpen; // Use nodes 'iconOpen' else return this.defaults.iconOpen; } // or default 'iconOpen' else { // Closed parent: if (node.iconClose) return node.iconClose; // Use nodes 'iconClose' else return this.defaults.iconClose; } } // or default 'iconClose' treemenu.prototype.writeNodeText = function(node) { //>WriteNodeText var cls = this.getNodeTextClass(node, this.selected); // Get NodeTextClass var str = '<a id="' + this.name + 'Node_' + node.id + '" class="' + cls + '"'; // Add '<a id=...' and 'class=...' if (node.url) str += ' href="' + node.url + '"'; // HRef-link to node.url else str += ' href="javascript: '+this.name+'.toggle('+node.id+')"'; // or to java.toggle if (node.url && node.target) str += ' target="' + node.target + '"'; // Target ="node.target" if (node.tooltip) str += ' title="' + node.tooltip + '"'; // Title ="node.tooltip" str += ' onclick="javascript: ' + this.name + '.pick(\'' + node.id + '\')"'; // OnClick="javascript.pick" //str += ' onmouseover="javascript: display_info(' + node.id2 + ');"'; // OnClick="javascript.pick" str += '>' + node.text + ((node.url) ? '</a>' : '</a>') ; // Node text, close 'a>' return str; } // Return HTML-string treemenu.prototype.getNodeTextClass = function(node, selectID) { //>GetNodeTextClass for TreeMenu.css var cls = (node.id==selectID) ? 'Selected' : 'Node'; // Class 'Selected', 'Node' if (!node.url) cls = 'Item'; // or 'Item' (without url) return cls + '_' + Math.min(node.indent, this.classDepth); } // Append '_indent' or '_classDepth' treemenu.prototype.writeCreatedWithTreeMenu = function() { //>WriteCreatedWithTreeMenu var str = ''; return str; } // --------------- Load ---------------- treemenu.prototype.loadSelected = function() { this.loadNode(this.selected); } //>LoadSelected treemenu.prototype.loadNode = function(id) { //>LoadNode by ID into it's target frame if (id<0 || id>=this.nodes.length) return; // Only nodes with valid id if (this.nodes[id].target=='hide') return; // Only nodes with no hidden target for (var i=0; i<parent.frames.length; i++) { // Loop: Frames in frameset if (parent.frames[i].name==this.nodes[id].target) { // Target-frame of the selected node parent.frames[i].location.href = this.nodes[id].url; // -> Reference to the node to load break; } } } // Break the loop and return // ----------- Pick / Select ----------- treemenu.prototype.pick = function(id) { //>Pick a node by id var node = this.nodes[id]; // Picked node if (node.url) { // Nodes with URL (->no href to toggle) if (node.indent==0 && this.showIcons==false) this.toggle(id); // -> Toggle top node without icon else if (node.childs.length>0 && node.isOpen==false) this.toggle(id); } // Else: open closed parent node this.select(id); } // Select node by ID & unselect previous treemenu.prototype.select = function(id) { //>Select a node by a given ID if (id<0 || id>=this.nodes.length) return; // Only nodes with valid id if (!this.nodes[id].url) return; // Only for a node with url: if (this.autoclose==true) this.autocloseTree(id); // Autoclose the old tree (?) if (this.selected>=0 && this.selected<this.nodes.length) { // Deselect selected Html-node: var nodeA = document.getElementById(this.name + 'Node_' + this.selected); // Get selected Html-node by id var nameA = this.getNodeTextClass(this.nodes[this.selected],-1); // ClassName for unselected if (nodeA && nameA) nodeA.className = nameA; // Unselect previous selected node this.selected = -1; } // Invalidate this.selected var nodeB = document.getElementById(this.name + 'Node_' + id); // Select Html-node: var nameB = this.getNodeTextClass(this.nodes[id], id); // ClassName for selected if (nodeB && nameB) nodeB.className = nameB; // Selected previous unselected node this.selected = id; // Set this.selected value to id this.openAncestors(id); // Open the nodes ancestors this.setCookies(this.expire); } // Set cookies treemenu.prototype.selectPath = function(path) { //>SelectPath var path = this.pathWithSlash(path); // Ensure path with slash '/' if (this.selected>=0 && this.selected<this.nodes.length) { // A node ist already selected: var url = this.pathWithSlash(this.nodes[this.selected].url); // URL of the selected node if (url==path) return; } // URL already selected -> return for (var id=0; id<this.nodes.length; id++) { // Loop to search node: var url = this.pathWithSlash(this.nodes[id].url); // Node path with slash '/' if (url && url==path) { this.select(id); break; } } } // Equal path -> select node by id treemenu.prototype.openAncestors = function(id) { //>OpenAncestors of the node with id if (id<0) return; // Only valid nodes with ID>=0 var ancestor = this.nodes[id].parent; // Ancestor is parent node; while(ancestor.indent>=0) { // Loop: Ancestors if (!ancestor.isOpen) { ancestor.isOpen=true; this.updateNode(ancestor); } // Open and update ancestor ancestor = ancestor.parent; } } // Parent of ancestor } treemenu.prototype.pathWithSlash = function(path) { //>PathWithSlash var parts = path.split("\\"); // Split path at '\' into string-array var str = parts[0]; // Write first part to 'str' for (var i=1; i<parts.length; i++) str = str + '/' + parts[i]; // Add next parts divided by '/' return str; } // Return path with '/' instead of '\' // --------- Autoclose Tree ------------ treemenu.prototype.setAutoclose = function(bool) { this.autoclose = bool; } //>SetAutoclose variable treemenu.prototype.autocloseTree = function(id) { //>AutocloseTree for left subtree var current = this.getPathIDs(this.selected); // PathIDs of current selected node var picked = this.getPathIDs(id); // PathIDs of mewly picked node var minLen = (current.length<picked.length) ? current.length : picked.length; // Minimal number of path-steps for (var i=0; i<minLen; i++) { // Loop common ancestors: if (current[i]!=picked[i]) { // First uncommon ancestors var id = current[i]; // -> Get the node-id of the selected this.nodes[id].isOpen=false; // Close the associated subtree this.updateNode(this.nodes[id]); // Update the associated node return; } } } // Return: Autoclose is done treemenu.prototype.getPathIDs = function(id) { //>GetPathIDs (array of id's) var ids = new Array(this.nodes[id].indent+1); // Instantiate array[0,1..] of id's var ancestor = this.nodes[id]; // Self-ID while(ancestor.indent>=0) { // Loop ancestors: ids[ancestor.indent] = ancestor.id; // Store the id using the indent ancestor = ancestor.parent; } // Get next ancestor return ids; } // Return array of id's // ---------- Toggle / Update ---------- treemenu.prototype.toggle = function(id) { //>Toggle a node by id if (this.nodes[id].childs.length==0) return; // Only for parent nodes this.nodes[id].isOpen = !this.nodes[id].isOpen; // Toggle node-status (open or close) this.updateNode(this.nodes[id]); // Update the node this.setCookies(this.expire); } // Set cookies treemenu.prototype.updateNode = function(node) { //>UpdateNode var subTree = document.getElementById(this.name + 'SubTree_' + node.id); // Get Html-element: SubTree var tieUp = document.getElementById(this.name + 'TieUp_' + node.id); // TieUpIcon var symbol = document.getElementById(this.name + 'Symbol_' + node.id); // NodeSymbol if (subTree) subTree.style.display = (node.isOpen) ? 'block' : 'none'; // Update Html-elem. SubTree if (tieUp) tieUp.src = this.getTieUpIcon(node); // TieUpIcon if (symbol) symbol.src = this.getNodeSymbol(node); } // NodeSymbol // ----------- IsLastChild ------------- treemenu.prototype.isLastChild = function(node) { //>IsLastChild (?) var parent = node.parent; // Parent of the node return ((node == parent.childs[parent.childs.length-1]) ? true : false); } // Check for last child // --------- Level/Lines/Icons --------- treemenu.prototype.level = function(level) { //>Level to open/close menu for (var id=0; id<this.nodes.length; id++) { // Loop: nodes this.nodes[id].isOpen = (this.nodes[id].indent<level) ? true : false; // Open/close node depending on level this.updateNode(this.nodes[id]); } // Update the node this.setCookies(this.expire); } // Set cookies treemenu.prototype.lines = function(bool) { //>Lines to be shown (?) if (this.showLines == bool) return; // Nothing changed -> return this.showLines = bool; // Update 'showLines' var passLines = document.getElementsByName("passLine"); // Get PassLines if (!passLines) return; // Existing passLines: for (var i=0; i<passLines.length; i++) { // Loop: passLines passLines[i].src = (bool) ? this.defaults.passLine : this.defaults.empty; } // Update icon-source for (var id=0; id<this.nodes.length; id++) { // TieUpIcon for each node if (this.nodes[id].indent < 1) continue; // with indent >= 1 var tieUp = document.getElementById(this.name + 'TieUp_' + id); // TieUpIcon of the node if (tieUp) tieUp.src = this.getTieUpIcon(this.nodes[id]); } // Update icon-source this.setCookies(this.expire); } // Set cookies treemenu.prototype.icons = function(bool) { //>Icons to be shown (?) if (this.showIcons == bool) return; // Nothing changed -> return this.showIcons = bool; // Set 'showIcons'-value for (var id=0; id<this.nodes.length; id++) { // Loop: nodes var icon = this.getNodeSymbol(this.nodes[id]); // Get node symbol var image = document.getElementById(this.name + 'Symbol_' + id) // Get Html-image by id if (image) image.src = icon; } // Set image source to node symbol this.setCookies(this.expire); } // Set cookies // -------------- Cookies -------------- treemenu.prototype.expiration = function(expire) { //>Expiration this.expire = expire; this.setCookies(this.expire); } // Set/Save expiration period of cookies treemenu.prototype.cookies = function(bool) { //>Cookies to be used (?) if (bool) { this.useCookies = bool; this.setCookies(this.expire); } // Use cookies -> Set cookies else { this.setCookies(-1); this.useCookies = bool; } } // No cookies -> Clear existing cookies treemenu.prototype.setCookies = function(expire) { //>SetCookies this.openNodes = ''; // Initialize 'openNodes'-String for (var i=0; i<this.nodes.length; i++) // Loop: nodes this.openNodes += (this.nodes[i].isOpen) ? '1' : '0'; // Fill 'openNodes'-String this.setCookie("OpenNodes", this.openNodes, expire); // Set cookie 'OpenNodes' this.setCookie("ShowLines", this.showLines, expire); // 'ShowLines' this.setCookie("ShowIcons", this.showIcons, expire); // 'ShowIcons' this.setCookie("Selected", this.selected, expire); // 'Selected' this.setCookie("Autoclose", this.autoclose, expire); // 'Autoclose' this.setCookie("Expire" , this.expire, expire); } // 'Expire' treemenu.prototype.readCookies = function() { //>ReadCookies (as string!) var lines = this.getCookie("ShowLines"); // Get Cookie: 'ShowLines' var icons = this.getCookie("ShowIcons"); // 'ShowIcons' var select = this.getCookie("Selected"); // 'Selected' var autocl = this.getCookie("Autoclose"); // 'Autoclose' var open = this.getCookie("OpenNodes"); // 'OpenNodes' var expire = this.getCookie("Expire"); // 'Expire' if (lines) this.showLines = (lines=='true') ? true : false; // Set value of 'showLines' if (icons) this.showIcons = (icons=='true') ? true : false; // 'showIcons' if (select) this.selected = select; // 'selected' if (autocl) this.autoclose = autocl; // 'autoclose' if (open) this.openNodes = open; // 'openNodes' if (expire) this.expire = expire; // 'expire' if (lines || icons || select || open || autocl) this.useCookies = true; } // Cookies found -> useCookies is true // --------------- Cookie -------------- treemenu.prototype.setCookie = function(name, value, expire) { //>SetCookie by name and value if (!this.useCookies) return; // Only if cookies are to be used var exp = new Date(); // Actual date var end = exp.getTime() + (expire * 24 * 60 * 60 * 1000); // In 'expire'-days (-1: -> invalidate) exp.setTime(end); // Expire time of cookes document.cookie = this.name+name+'='+value+'; expires='+exp.toGMTString(); } // Set cookie with expiration-date treemenu.prototype.getCookie = function(name) { //>GetCookie value (as string!) var cookies = document.cookie; // Cookies separated by ';' var posName = cookies.indexOf(this.name + name + '='); // Start position of 'tree_name=' if (posName == -1) return ''; // Cookie not found -> Return '' var posValue = posName + this.name.length + name.length + 1; // Start position of cookie-value var endValue = cookies.indexOf(';',posValue); // End position of cookie value at ';' if (endValue !=-1) return cookies.substring(posValue, endValue); // ';' -> Return substring as value return cookies.substring(posValue); } // Else-> Return rest of line as value // Config.js, Version 1.1, 2005/04 // Copyright (C) 2004 by Hans Bauer, Schillerstr. 30, D-73072 Donzdorf // http://www.h-bauer.de // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation. // // History: // Version 1.1: Including the autoclose-feature // function config(name, tree, title, tooltip) { //>config this.name = name; this.tree = tree; // this.title = title; this.titelTTip = tooltip; // this.lines = true; this.linesTxt = 'Show Lines'; // this.linesTTip = 'Lines indicate hierarchy'; // this.icons = true; this.iconsTxt = 'Show Symbols'; // this.iconsTTip = 'Symbols indicate node status';// this.aclose = false; this.acloseTxt = 'Autoclose subtrees'; // this.acloseTTip = 'Autoclose left subtrees'; // this.cookies = false; this.cookiesTxt = 'Save Cookies'; // this.cookiesTTip= 'Stores tree configuration'; // this.expireTxt= 'days'; this.expireTTip = 'Cookie expiration period'; // this.level = -1; this.levelTxt = 'Open Level'; this.levelTTip = 'Open tree up to this level'; // this.helpTxt = 'Help'; this.helpTTip = 'Items show tooltips'; // this.helpAlert= 'Tooltips are shown on mouse-over'; } // // ------------- TextOf ... ------------ config.prototype.textOfLines = function(text, tooltip) { //>TextOfLines (show lines) this.linesTxt = text; this.linesTTip = tooltip; } // config.prototype.textOfIcons = function(text, tooltip) { //>TextOfIcons (show symbols) this.iconsTxt = text; this.iconsTTip = tooltip; } // config.prototype.textOfAClose= function(text,tooltip) { //>TextOfAClose (autoclose) this.acloseTxt= text; this.acloseTTip=tooltip; } // config.prototype.textOfCookies = function(text, tooltip) { //>TextOfCookies this.cookiesTxt = text; this.cookiesTTip = tooltip; } // config.prototype.textOfExpire = function(text, tooltip) { //>TextOfExpire this.expireTxt = text; this.expireTTip = tooltip; } // config.prototype.textOfLevel = function(text, tooltip) { //>TextOfLevel this.levelTxt = text; this.levelTTip = tooltip; } // config.prototype.textOfHelp = function(text, tooltip, alert) { //>TextOfHelp this.helpTxt = text; this.helpTTip = tooltip; this.helpAlert = alert; } // // ---------- Build Html-Code ---------- config.prototype.toString = function() { //>ToString var str = '<form><div class="Config">'; // Encapsulate class 'Config' in a form var icon = (this.tree.showIcons) ? 'gif/config.gif' : 'gif/minicon.gif'; // Decide icon = config- or minIcon.gif str += '<a href="javascript: ' + this.name + '.toggle()">' // Config-icon: + '<img id="' + this.name + 'ConfigGif"' // Write Html-string for the image + ' src="' + icon + '" alt="" /></a>'; // and a reference to this -> toggle str += '<a href="javascript: ' + this.name + '.toggle()"' // Config-text + ' id="' + this.name + 'ConfigTxt" class="ConfigText"' // Write Html-string for the text + ' title="' + this.titelTTip + '">' // in class 'Text' with tooltip + this.title + '</a>'; // and a reference to this -> toggle str += '<div id="' + this.name + 'SubTree"' // SubTree-block (default is invisible: + ' class="SubTree" style="display:none">'; // to show or hide the SubTree str += '<img src="gif/empty.gif" alt="" />' // Show Lines: + '<input type="checkbox" name="Lines" value="Lines"' // Checkbox: Name & value is 'Lines' + ' id="' + this.name + 'LinesCheck"' // ID for checkbox + ' onClick="javascript: ' + this.name + '.changeLines()">' // OnClick -> java.changeLines + '<a id="' + this.name + 'LinesTxt" class="Text"' // Text: Define ID and class + ' title="' + this.linesTTip + '">' + this.linesTxt + '</a><br>'; // Write tooltip and text str += '<img src="gif/empty.gif" alt="" />' // Show Icons: + '<input type="checkbox" name="Icons" value="Icons"' // Checkbox: Name & value is 'Icons' + ' id="' + this.name + 'IconsCheck"' // ID for checkbox + ' onClick="javascript: ' + this.name + '.changeIcons()">' // OnClick -> java.changeIcons + '<a id="' + this.name + 'IconsTxt" class="Text"' // Text: Define ID and class + ' title="' + this.iconsTTip + '">' + this.iconsTxt + '</a><br>'; // Write tooltip and text str += '<img src="gif/empty.gif" alt="" />' // Autoclose: + '<input type="checkbox" name="AClose" value="AClose"' // Checkbox: Name & value is 'AClose' + ' id="' + this.name + 'ACloseCheck"' // ID for checkbox + ' onClick="javascript: ' + this.name + '.changeAClose()">' // OnClick -> java.changeAClose + '<a id="' + this.name + 'ACloseTxt" class="Text"' // Text: Define ID and class + ' title="' + this.acloseTTip + '">' + this.acloseTxt + '</a><br>'; // Write tooltip and text str += '<img src="gif/empty.gif" alt="" />' // Use Cookies: + '<input type="checkbox" name="Cookies" value="Cookies"' // Checkbox: Name & value is 'Cookies' + ' id="' + this.name + 'CookiesCheck"' // ID for checkbox + ' onClick="javascript: ' + this.name + '.changeCookies()">' // OnClick -> java.changeCookies + '<a id="' + this.name + 'CookiesTxt" class="Text"' // Text: Define ID and class + ' title="' + this.cookiesTTip + '">' + this.cookiesTxt + '</a><br>'; // Write tooltip and text str += '<img src="gif/empty.gif" alt="" /><img src="gif/empty.gif" alt="" />' // Expire period of cookies + '&nbsp;<select name="Expire" size="1"' // Select options 'Expire' + ' id="' + this.name + 'ExpireList"' // ID for options + ' onClick="' + this.name + '.changeExpire()">'; // OnClick -> call this.changeExpire for (i=0; i<7; i++) str += '<option>' + Math.pow(2,i) + '</option>'; // Loop: include options 1, 2, 4,... str += '</select>' // Close 'Expire'-select + '<a id="' + this.name + 'ExpireTxt" class="Text"' // Text: Define ID and class + ' title="' + this.expireTTip + '">' + this.expireTxt + '</a><br>'; // Write tooltip and text str += '<img src="gif/empty.gif" alt="" />'; // Open Level: str += '<select name="Level" size="1"' // Select options 'Level + ' id="' + this.name + 'LevelList"' // ID for options + ' onClick="' + this.name + '.clickLevel()">' // OnClick -> call this.clickLevel + '<option>-</option>'; // Option '-' str += '</select>' // End of 'select' + '<a id="' + this.name + 'LevelTxt" class="Text"' // Text: Define ID and class + ' title="' + this.levelTTip + '">' + this.levelTxt + '</a><br>'; // Write tooltip and text str += '<img src="gif/empty.gif" alt="" />' // Help: + '<a href="javascript: ' + this.name + '.help()">' // Icon: + '<img id="' + this.name + 'HelpGif"' // Write Html-string for the image + ' src="gif/help.gif" alt="" /></a>'; // and a reference to this -> toggle str += '<a href="javascript: ' + this.name + '.help()"' // Text + ' id="' + this.name + 'HelpTxt" class="Text"' // Write Html-string for the text + ' title="' + this.helpTTip + '">' // in class 'Text' with tooltip + this.helpTxt + '</a>'; // and a reference to this -> help str += '<hr></div></div></form>'; // Close SubTree, class 'Config', form return str; } // Return Html-string config.prototype.toggle = function() { //>Toggle config tree subTree = document.getElementById(this.name + 'SubTree'); // Get element: SubTree status = subTree.style.display; // Status of the SubTree (open/close) subTree.style.display = (status=='none') ? 'block' : 'none'; // Toggle SubTree-status if (subTree.style.display=='block') this.updateOnOpen(); } // UpdateOnOpen this using tree.values config.prototype.updateOnOpen = function() { //>Update config-tree on opening var check; // Initialize 'check' check = document.getElementById(this.name + 'LinesCheck'); // Lines checkbox check.checked = (this.tree.showLines) ? true : false; // Get setting from 'tree' check = document.getElementById(this.name + 'IconsCheck'); // Icons checkbox check.checked = (this.tree.showIcons) ? true : false; // Get setting from 'tree' check = document.getElementById(this.name + 'ACloseCheck'); // Icons checkbox check.checked = (this.tree.autoclose) ? true : false; // Get setting from 'tree' check = document.getElementById(this.name + 'CookiesCheck'); // Cookies checkbox check.checked = (this.tree.useCookies) ? true : false; // Get setting from 'tree' this.updateExpireList(); // Update Expire-list this.fillLevelList(); } // Fill Level-list config.prototype.updateExpireList = function() { //>UpdateExpireList for (i=0; i<7; i++) if (Math.pow(2,i)==this.tree.expire) break; // Loop to find the tree's expire var list = document.getElementById(this.name + 'ExpireList'); // Expire list list.selectedIndex = i; } // Select appropriate option config.prototype.fillLevelList = function() { //>FillLevelList var list = document.getElementById(this.name + 'LevelList'); // Level list if (list.length>1) return; // List already filled -> nothing for (i=0; i<=this.tree.maxIndent; i++) { // Loop levels up to maxIndent of tree var item = new Option(i,i,false,false); // Options 0, 1,... maxIndent-1 list.options[list.length] = item; } } // Append next indent-number config.prototype.changeLines = function() { //>ChangeLines (Checkbox Show Lines) var check = document.getElementById(this.name + 'LinesCheck'); // Lines checkbox this.tree.lines(check.checked); } // Transfer setting to 'tree' config.prototype.changeIcons = function() { //>ChangeIcons (Checkbox Show Icons) var icon = document.getElementById(this.name + 'ConfigGif'); // Main icon of config-tree: var check = document.getElementById(this.name + 'IconsCheck'); // Icons checkbos icon.src = (check.checked) ? 'gif/config.gif' : 'gif/minIcon.gif'; // Show or hide main icon of this this.tree.icons(check.checked); } // Show or hide the icons of the tree config.prototype.changeAClose = function() { //>ChangeAClose (Checkbox Autoclose) var check = document.getElementById(this.name + 'ACloseCheck'); // Autoclose checkbox this.tree.setAutoclose(check.checked); } // Transfer setting to 'tree' config.prototype.changeCookies = function() { //>ChangeCookies (Checkbox Use Cookies) var check = document.getElementById(this.name + 'CookiesCheck'); // Cookies checkbox this.tree.cookies(check.checked); } // Transfer setting to 'tree' config.prototype.changeExpire = function() { //>ChangeExpire (Listbox expire) var list = document.getElementById(this.name + 'ExpireList'); // ExpireList, IE fakes 'list.value' this.tree.expiration(Math.pow(2,list.selectedIndex)); } // Transfer selected option to 'tree' config.prototype.clickLevel = function() { //>ClickLevel var list = document.getElementById(this.name + 'LevelList'); // Level list if (this.level==list.selectedIndex-1) this.level = -1; // Invalidate level on opening options else { this.level = list.selectedIndex - 1; // Else: Get selected level and if (this.level>=0) this.tree.level(this.level); } } // apply selected level in tree config.prototype.help = function() { alert(this.helpAlert); } //>Help message on click
JavaScript
function open_popup(s){ var settings=jQuery.extend({content:'',id:'',width:600,top:30}, s); //document width & height var dwidth = 0, dheight = 0; if( typeof( window.innerWidth ) == 'number' ) { //Non-IE dwidth = window.innerWidth; dheight = window.innerHeight; } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { //IE 6+ in 'standards compliant mode' dwidth = document.documentElement.clientWidth; dheight = document.documentElement.clientHeight; } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { //IE 4 compatible dwidth = document.body.clientWidth; dheight = document.body.clientHeight; } //document scroll top/left var scrollX = 0, scrollY = 0; if( typeof( window.pageYOffset ) == 'number' ) { //Netscape compliant scrollY = window.pageYOffset; scrollX = window.pageXOffset; } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) { //DOM compliant scrollY = document.body.scrollTop; scrollX = document.body.scrollLeft; } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) { //IE6 standards compliant mode scrollY = document.documentElement.scrollTop; scrollX = document.documentElement.scrollLeft; } pLeft=(dwidth-settings.width)/2; pLeft=(pLeft<0? 0 : pLeft)+scrollX; var popup='<div id=\"'+settings.id+'\"></div>'; $('body').append(popup); $('div#'+settings.id) .addClass('popup') .css('width', settings.width) .css('top', scrollY+settings.top) .css('left', pLeft) .html(settings.content) .fadeIn('fast'); } function close_popup(id){ obj=id? $('#'+id) : $('.popup'); obj.each(function(){ $(this).fadeOut('fast', function(){$(this).remove();}); }); }
JavaScript
function htmlentities( string ){ // http://kevin.vanzonneveld.net // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // % note: table from http://www.the-art-of-web.com/html/character-codes/ // * example 1: htmlentities('Kevin & van Zonneveld'); // * returns 1: 'Kevin &amp; van Zonneveld' var histogram = {}, code = 0, tmp_arr = []; histogram['34'] = 'quot'; histogram['38'] = 'amp'; histogram['60'] = 'lt'; histogram['62'] = 'gt'; histogram['160'] = 'nbsp'; histogram['161'] = 'iexcl'; histogram['162'] = 'cent'; histogram['163'] = 'pound'; histogram['164'] = 'curren'; histogram['165'] = 'yen'; histogram['166'] = 'brvbar'; histogram['167'] = 'sect'; histogram['168'] = 'uml'; histogram['169'] = 'copy'; histogram['170'] = 'ordf'; histogram['171'] = 'laquo'; histogram['172'] = 'not'; histogram['173'] = 'shy'; histogram['174'] = 'reg'; histogram['175'] = 'macr'; histogram['176'] = 'deg'; histogram['177'] = 'plusmn'; histogram['178'] = 'sup2'; histogram['179'] = 'sup3'; histogram['180'] = 'acute'; histogram['181'] = 'micro'; histogram['182'] = 'para'; histogram['183'] = 'middot'; histogram['184'] = 'cedil'; histogram['185'] = 'sup1'; histogram['186'] = 'ordm'; histogram['187'] = 'raquo'; histogram['188'] = 'frac14'; histogram['189'] = 'frac12'; histogram['190'] = 'frac34'; histogram['191'] = 'iquest'; histogram['192'] = 'Agrave'; histogram['193'] = 'Aacute'; histogram['194'] = 'Acirc'; histogram['195'] = 'Atilde'; histogram['196'] = 'Auml'; histogram['197'] = 'Aring'; histogram['198'] = 'AElig'; histogram['199'] = 'Ccedil'; histogram['200'] = 'Egrave'; histogram['201'] = 'Eacute'; histogram['202'] = 'Ecirc'; histogram['203'] = 'Euml'; histogram['204'] = 'Igrave'; histogram['205'] = 'Iacute'; histogram['206'] = 'Icirc'; histogram['207'] = 'Iuml'; histogram['208'] = 'ETH'; histogram['209'] = 'Ntilde'; histogram['210'] = 'Ograve'; histogram['211'] = 'Oacute'; histogram['212'] = 'Ocirc'; histogram['213'] = 'Otilde'; histogram['214'] = 'Ouml'; histogram['215'] = 'times'; histogram['216'] = 'Oslash'; histogram['217'] = 'Ugrave'; histogram['218'] = 'Uacute'; histogram['219'] = 'Ucirc'; histogram['220'] = 'Uuml'; histogram['221'] = 'Yacute'; histogram['222'] = 'THORN'; histogram['223'] = 'szlig'; histogram['224'] = 'agrave'; histogram['225'] = 'aacute'; histogram['226'] = 'acirc'; histogram['227'] = 'atilde'; histogram['228'] = 'auml'; histogram['229'] = 'aring'; histogram['230'] = 'aelig'; histogram['231'] = 'ccedil'; histogram['232'] = 'egrave'; histogram['233'] = 'eacute'; histogram['234'] = 'ecirc'; histogram['235'] = 'euml'; histogram['236'] = 'igrave'; histogram['237'] = 'iacute'; histogram['238'] = 'icirc'; histogram['239'] = 'iuml'; histogram['240'] = 'eth'; histogram['241'] = 'ntilde'; histogram['242'] = 'ograve'; histogram['243'] = 'oacute'; histogram['244'] = 'ocirc'; histogram['245'] = 'otilde'; histogram['246'] = 'ouml'; histogram['247'] = 'divide'; histogram['248'] = 'oslash'; histogram['249'] = 'ugrave'; histogram['250'] = 'uacute'; histogram['251'] = 'ucirc'; histogram['252'] = 'uuml'; histogram['253'] = 'yacute'; histogram['254'] = 'thorn'; histogram['255'] = 'yuml'; for (i = 0; i < string.length; ++i) { code = string.charCodeAt(i); if (code in histogram) { tmp_arr[i] = '&'+histogram[code]+';'; } else { tmp_arr[i] = string.charAt(i); } } return tmp_arr.join(''); }
JavaScript
function number_format(str,decimal,prefix){ var prefix = prefix || ''; var decimal = decimal || 0; var nStr=''+str; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; if(decimal>0){ if(x2.length>(decimal+1)){ x2=x2.substr(0, decimal+1); }else if(x2.length<(decimal+1)){ if(x2.length==0){ x2='.'; } for(var i=x2.length;i<(decimal+1);i++){ x2+='0'; } } }else{ x2=''; } var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) x1 = x1.replace(rgx, '$1' + ',' + '$2'); return prefix + x1 + x2; }
JavaScript
function array_flip(trans){var key,tmp_ar={};for(key in trans){tmp_ar[trans[key]]=key;}return tmp_ar;}
JavaScript
var Slate = function () { var chartColors, nav, navTop; chartColors = ["#263849", "#F90", "#666", "#BBB"]; return { start: start, chartColors: chartColors }; function start () { nav = $('#nav'); navTop = nav.offset ().top; bindNavEvents (); bindWidgetEvents (); bindAccordionEvents (); enableAutoPlugins (); } function enableAutoPlugins () { if ($.fn.tooltip) { $('.ui-tooltip').tooltip (); } if ($.fn.popover) { $('.ui-popover').popover (); } if ($.fn.lightbox) { $('.ui-lightbox').lightbox(); } if ($.fn.dataTable) { $('.data-table').dataTable( { sDom: "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>", sPaginationType: "bootstrap", oLanguage: { "sLengthMenu": "_MENU_ records per page" } }); } } function bindNavEvents () { var msie8 = $.browser.version === '8.0' && $.browser.msie; if (!msie8) { $(window).bind ('scroll', navScroll); } $('#info-trigger').live ('click', function (e) { e.preventDefault (); $('#info-menu').toggleClass ('toggle-menu-show'); $(document).bind ('click.info', function (e) { if ($(e.target).is ('#info-menu')) { return false; } if ($(e.target).parents ('#info-menu').length == 1) { return false; } $('#info-menu').removeClass ('toggle-menu-show'); $(document).unbind ('click.info'); }); }); } function navScroll () { var p = $(window).scrollTop (); ((p)>navTop) ? $('body').addClass ('nav-fixed') : $('body').removeClass ('nav-fixed'); } function bindWidgetEvents () { $('.widget-tabs .nav-tabs a').live ('click', widgetTabClickHandler); } function bindAccordionEvents () { $('.widget-accordion .accordion').on('show', function (e) { $(e.target).prev('.accordion-heading').parent ().addClass('open'); }); $('.widget-accordion .accordion').on('hide', function (e) { $(this).find('.accordion-toggle').not($(e.target)).parents ('.accordion-group').removeClass('open'); }); $('.widget-accordion .accordion').each (function () { $(this).find ('.accordion-body.in').parent ().addClass ('open'); }); } function widgetTabClickHandler (e) { e.preventDefault(); $(this).tab('show'); } }(); $(function () { Slate.start (); });
JavaScript
/** Script: Slideshow.js Slideshow - A javascript class for Mootools to stream and animate the presentation of images on your website. License: MIT-style license. Copyright: Copyright (c) 2008 [Aeron Glemann](http://www.electricprism.com/aeron/). Dependencies: Mootools 1.2 Core: Fx.Morph, Fx.Tween, Selectors, Element.Dimensions. Mootools 1.2 More: Assets. */ Slideshow = new Class({ Implements: [Chain, Events, Options], options: {/* onComplete: $empty, onEnd: $empty, onStart: $empty,*/ captions: true, center: true, classes: [], controller: false, delay: 2000, duration: 1500, fast: false, height: false, href: '', hu: '', linked: false, loader: {'animate': ['css/loader-#.png', 12]}, loop: true, match: /\?slide=(\d+)$/, overlap: true, paused: false, properties: ['href', 'rel', 'rev', 'title'], random: false, replace: [/(\.[^\.]+)$/, 't$1'], resize: 'width', slide: 0, thumbnails: false, titles: true, transition: function(p){return -(Math.cos(Math.PI * p) - 1) / 2;}, width: false }, /** Constructor: initialize Creates an instance of the Slideshow class. Arguments: element - (element) The wrapper element. data - (array or object) The images and optional thumbnails, captions and links for the show. options - (object) The options below. Syntax: var myShow = new Slideshow(element, data, options); */ initialize: function(el, data, options){ this.setOptions(options); this.slideshow = $(el); if (!this.slideshow) return; this.slideshow.set('styles', {'display': 'block', 'position': 'relative', 'z-index': 0}); var match = window.location.href.match(this.options.match); this.slide = (this.options.match && match) ? match[1].toInt() : this.options.slide; this.counter = this.delay = this.transition = 0; this.direction = 'left'; this.paused = false; if (!this.options.overlap) this.options.duration *= 2; var anchor = this.slideshow.getElement('a') || new Element('a'); if (!this.options.href) this.options.href = anchor.get('href') || ''; if (this.options.hu.length && !this.options.hu.test(/\/$/)) this.options.hu += '/'; if (this.options.fast === true) this.options.fast = 2; // styles var keys = ['slideshow', 'first', 'prev', 'play', 'pause', 'next', 'last', 'images', 'captions', 'controller', 'thumbnails', 'hidden', 'visible', 'inactive', 'active', 'loader']; var values = keys.map(function(key, i){ return this.options.classes[i] || key; }, this); this.classes = values.associate(keys); this.classes.get = function(){ var str = '.' + this.slideshow; for (var i = 0, l = arguments.length; i < l; i++) str += ('-' + this[arguments[i]]); return str; }.bind(this.classes); // data if (!data){ this.options.hu = ''; data = {}; var thumbnails = this.slideshow.getElements(this.classes.get('thumbnails') + ' img'); this.slideshow.getElements(this.classes.get('images') + ' img').each(function(img, i){ var src = img.get('src'); var caption = $pick(img.get('alt'), img.get('title'), ''); var parent = img.getParent(); var properties = (parent.get('tag') == 'a') ? parent.getProperties : {}; var href = img.getParent().get('href') || ''; var thumbnail = (thumbnails[i]) ? thumbnails[i].get('src') : ''; data[src] = {'caption': caption, 'href': href, 'thumbnail': thumbnail}; }); } var loaded = this.load(data); if (!loaded) return; // events this.events = $H({'keydown': [], 'keyup': [], 'mousemove': []}); var keyup = function(e){ switch(e.key){ case 'left': this.prev(e.shift); break; case 'right': this.next(e.shift); break; case 'p': this.pause(); break; } }.bind(this); this.events.keyup.push(keyup); document.addEvent('keyup', keyup); // required elements var el = this.slideshow.getElement(this.classes.get('images')); var images = (el) ? el.empty() : new Element('div', {'class': this.classes.get('images').substr(1)}).inject(this.slideshow); var div = images.getSize(); this.height = this.options.height || div.y; this.width = this.options.width || div.x; images.set({'styles': {'display': 'block', 'height': this.height, 'overflow': 'hidden', 'position': 'relative', 'width': this.width}}); this.slideshow.store('images', images); this.a = this.image = this.slideshow.getElement('img') || new Element('img'); if (Browser.Engine.trident && Browser.Engine.version > 4) this.a.style.msInterpolationMode = 'bicubic'; this.a.set('styles', {'display': 'none', 'position': 'absolute', 'zIndex': 1}); this.b = this.a.clone(); [this.a, this.b].each(function(img){ anchor.clone().cloneEvents(anchor).grab(img).inject(images); }); // optional elements if (this.options.captions) this._captions(); if (this.options.controller) this._controller(); if (this.options.loader) this._loader(); if (this.options.thumbnails) this._thumbnails(); // begin show this._preload(); }, /** Public method: go Jump directly to a slide in the show. Arguments: n - (integer) The index number of the image to jump to, 0 being the first image in the show. Syntax: myShow.go(n); */ go: function(n, direction){ if ((this.slide - 1 + this.data.images.length) % this.data.images.length == n || $time() < this.transition) return; $clear(this.timer); this.delay = 0; this.direction = (direction) ? direction : ((n < this.slide) ? 'right' : 'left'); this.slide = n; if (this.preloader) this.preloader = this.preloader.destroy(); this._preload(this.options.fast == 2 || (this.options.fast == 1 && this.paused)); }, /** Public method: first Goes to the first image in the show. Syntax: myShow.first(); */ first: function(){ this.prev(true); }, /** Public method: prev Goes to the previous image in the show. Syntax: myShow.prev(); */ prev: function(first){ var n = 0; if (!first){ if (this.options.random){ // if it's a random show get the previous slide from the showed array if (this.showed.i < 2) return; this.showed.i -= 2; n = this.showed.array[this.showed.i]; } else n = (this.slide - 2 + this.data.images.length) % this.data.images.length; } this.go(n, 'right'); }, /** Public method: pause Toggles play / pause state of the show. Arguments: p - (undefined, 1 or 0) Call pause with no arguments to toggle the pause state. Call pause(1) to force pause, or pause(0) to force play. Syntax: myShow.pause(p); */ pause: function(p){ if ($chk(p)) this.paused = (p) ? false : true; if (this.paused){ this.paused = false; this.delay = this.transition = 0; this.timer = this._preload.delay(100, this); [this.a, this.b].each(function(img){ ['morph', 'tween'].each(function(p){ if (this.retrieve(p)) this.get(p).resume(); }, img); }); if (this.options.controller) this.slideshow.getElement('.' + this.classes.pause).removeClass(this.classes.play); } else { this.paused = true; this.delay = Number.MAX_VALUE; this.transition = 0; $clear(this.timer); [this.a, this.b].each(function(img){ ['morph', 'tween'].each(function(p){ if (this.retrieve(p)) this.get(p).pause(); }, img); }); if (this.options.controller) this.slideshow.getElement('.' + this.classes.pause).addClass(this.classes.play); } }, /** Public method: next Goes to the next image in the show. Syntax: myShow.next(); */ next: function(last){ var n = (last) ? this.data.images.length - 1 : this.slide; this.go(n, 'left'); }, /** Public method: last Goes to the last image in the show. Syntax: myShow.last(); */ last: function(){ this.next(true); }, /** Public method: load Loads a new data set into the show: will stop the current show, rewind and rebuild thumbnails if applicable. Arguments: data - (array or object) The images and optional thumbnails, captions and links for the show. Syntax: myShow.load(data); */ load: function(data){ this.firstrun = true; this.showed = {'array': [], 'i': 0}; if ($type(data) == 'array'){ this.options.captions = false; data = new Array(data.length).associate(data.map(function(image, i){ return image + '?' + i })); } this.data = {'images': [], 'captions': [], 'hrefs': [], 'thumbnails': []}; for (var image in data){ var obj = data[image] || {}; var caption = (obj.caption) ? obj.caption.trim() : ''; var href = (obj.href) ? obj.href.trim() : ((this.options.linked) ? this.options.hu + image : this.options.href); var thumbnail = (obj.thumbnail) ? obj.thumbnail.trim() : image.replace(this.options.replace[0], this.options.replace[1]); this.data.images.push(image); this.data.captions.push(caption); this.data.hrefs.push(href); this.data.thumbnails.push(thumbnail); } if (this.options.random) this.slide = $random(0, this.data.images.length - 1); // only run when data is loaded dynamically into an existing slideshow instance if (this.options.thumbnails && this.slideshow.retrieve('thumbnails')) this._thumbnails(); if (this.slideshow.retrieve('images')){ [this.a, this.b].each(function(img){ ['morph', 'tween'].each(function(p){ if (this.retrieve(p)) this.get(p).cancel(); }, img); }); this.slide = this.transition = 0; this.go(0); } return this.data.images.length; }, /** Public method: destroy Destroys a Slideshow instance. Arguments: p - (string) The images and optional thumbnails, captions and links for the show. Syntax: myShow.destroy(p); */ destroy: function(p){ this.events.each(function(array, e){ array.each(function(fn){ document.removeEvent(e, fn); }); }); this.pause(1); if (this.options.loader) $clear(this.slideshow.retrieve('loader').retrieve('timer')); if (this.options.thumbnails) $clear(this.slideshow.retrieve('thumbnails').retrieve('timer')); this.slideshow.uid = Native.UID++; if (p) this.slideshow[p](); }, /** Private method: preload Preloads the next slide in the show, once loaded triggers the show, updates captions, thumbnails, etc. */ _preload: function(fast){ if (!this.preloader) this.preloader = new Asset.image(this.options.hu + this.data.images[this.slide], {'onload': function(){ this.store('loaded', true); }}); if (this.preloader.retrieve('loaded') && $time() > this.delay && $time() > this.transition){ if (this.stopped){ if (this.options.captions) this.slideshow.retrieve('captions').get('morph').cancel().start(this.classes.get('captions', 'hidden')); this.pause(1); if (this.end) this.fireEvent('end'); this.stopped = this.end = false; return; } this.image = (this.counter % 2) ? this.b : this.a; this.image.set('styles', {'display': 'block', 'height': 'auto', 'visibility': 'hidden', 'width': 'auto', 'zIndex': this.counter}); ['src', 'height', 'width'].each(function(prop){ this.image.set(prop, this.preloader.get(prop)); }, this); this._resize(this.image); this._center(this.image); var anchor = this.image.getParent(); if (this.data.hrefs[this.slide]) anchor.set('href', this.data.hrefs[this.slide]); else anchor.erase('href'); var text = (this.data.captions[this.slide]) ? this.data.captions[this.slide].replace(/<.+?>/gm, '').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, "'") : ''; this.image.set('alt', text); if (this.options.titles) anchor.set('title', text); if (this.options.loader) this.slideshow.retrieve('loader').fireEvent('hide'); if (this.options.captions) this.slideshow.retrieve('captions').fireEvent('update', fast); if (this.options.thumbnails) this.slideshow.retrieve('thumbnails').fireEvent('update', fast); this._show(fast); this._loaded(); } else { if ($time() > this.delay && this.options.loader) this.slideshow.retrieve('loader').fireEvent('show'); this.timer = (this.paused && this.preloader.retrieve('loaded')) ? null : this._preload.delay(100, this, fast); } }, /** Private method: show Does the slideshow effect. */ _show: function(fast){ if (!this.image.retrieve('morph')){ var options = (this.options.overlap) ? {'duration': this.options.duration, 'link': 'cancel'} : {'duration': this.options.duration / 2, 'link': 'chain'}; $$(this.a, this.b).set('morph', $merge(options, {'onStart': this._start.bind(this), 'onComplete': this._complete.bind(this), 'transition': this.options.transition})); } var hidden = this.classes.get('images', ((this.direction == 'left') ? 'next' : 'prev')); var visible = this.classes.get('images', 'visible'); var img = (this.counter % 2) ? this.a : this.b; if (fast){ img.get('morph').cancel().set(hidden); this.image.get('morph').cancel().set(visible); } else { if (this.options.overlap){ img.get('morph').set(visible); this.image.get('morph').set(hidden).start(visible); } else { var fn = function(hidden, visible){ this.image.get('morph').set(hidden).start(visible); }.pass([hidden, visible], this); hidden = this.classes.get('images', ((this.direction == 'left') ? 'prev' : 'next')); img.get('morph').set(visible).start(hidden).chain(fn); } } }, /** Private method: loaded Run after the current image has been loaded, sets up the next image to be shown. */ _loaded: function(){ this.counter++; this.delay = (this.paused) ? Number.MAX_VALUE : $time() + this.options.duration + this.options.delay; this.direction = 'left'; this.transition = (this.options.fast == 2 || (this.options.fast == 1 && this.paused)) ? 0 : $time() + this.options.duration; if (this.slide + 1 == this.data.images.length && !this.options.loop && !this.options.random) this.stopped = this.end = true; if (this.options.random){ this.showed.i++; if (this.showed.i >= this.showed.array.length){ var n = this.slide; if (this.showed.array.getLast() != n) this.showed.array.push(n); while (this.slide == n) this.slide = $random(0, this.data.images.length - 1); } else this.slide = this.showed.array[this.showed.i]; } else this.slide = (this.slide + 1) % this.data.images.length; if (this.image.getStyle('visibility') != 'visible') (function(){ this.image.setStyle('visibility', 'visible'); }).delay(1, this); if (this.preloader) this.preloader = this.preloader.destroy(); this._preload(); }, /** Private method: center Center an image. */ _center: function(img){ if (this.options.center){ var size = img.getSize(); img.set('styles', {'left': (size.x - this.width) / -2, 'top': (size.y - this.height) / -2}); } }, /** Private method: resize Resizes an image. */ _resize: function(img){ if (this.options.resize){ var h = this.preloader.get('height'), w = this.preloader.get('width'); var dh = this.height / h, dw = this.width / w, d; if (this.options.resize == 'length') d = (dh > dw) ? dw : dh; else d = (dh > dw) ? dh : dw; img.set('styles', {height: Math.ceil(h * d), width: Math.ceil(w * d)}); } }, /** Private method: start Callback on start of slide change. */ _start: function(){ this.fireEvent('start'); }, /** Private method: complete Callback on start of slide change. */ _complete: function(){ if (this.firstrun && this.options.paused){ this.firstrun = false; this.pause(1); } this.fireEvent('complete'); }, /** Private method: captions Builds the optional caption element, adds interactivity. This method can safely be removed if the captions option is not enabled. */ _captions: function(){ if (this.options.captions === true) this.options.captions = {}; var el = this.slideshow.getElement(this.classes.get('captions')); var captions = (el) ? el.empty() : new Element('div', {'class': this.classes.get('captions').substr(1)}).inject(this.slideshow); captions.set({ 'events': { 'update': function(fast){ var captions = this.slideshow.retrieve('captions'); var empty = (this.data.captions[this.slide] === ''); if (fast){ var p = (empty) ? 'hidden' : 'visible'; captions.set('html', this.data.captions[this.slide]).get('morph').cancel().set(this.classes.get('captions', p)); } else { var fn = (empty) ? $empty : function(n){ this.slideshow.retrieve('captions').set('html', this.data.captions[n]).morph(this.classes.get('captions', 'visible')) }.pass(this.slide, this); captions.get('morph').cancel().start(this.classes.get('captions', 'hidden')).chain(fn); } }.bind(this) }, 'morph': $merge(this.options.captions, {'link': 'chain'}) }); this.slideshow.store('captions', captions); }, /** Private method: controller Builds the optional controller element, adds interactivity. This method can safely be removed if the controller option is not enabled. */ _controller: function(){ if (this.options.controller === true) this.options.controller = {}; var el = this.slideshow.getElement(this.classes.get('controller')); var controller = (el) ? el.empty() : new Element('div', {'class': this.classes.get('controller').substr(1)}).inject(this.slideshow); var ul = new Element('ul').inject(controller); $H({'first': 'Shift + Leftwards Arrow', 'prev': 'Leftwards Arrow', 'pause': 'P', 'next': 'Rightwards Arrow', 'last': 'Shift + Rightwards Arrow'}).each(function(accesskey, action){ var li = new Element('li', { 'class': (action == 'pause' && this.options.paused) ? this.classes.play + ' ' + this.classes[action] : this.classes[action] }).inject(ul); var a = this.slideshow.retrieve(action, new Element('a', { 'title': ((action == 'pause') ? this.classes.play.capitalize() + ' / ' : '') + this.classes[action].capitalize() + ' [' + accesskey + ']' }).inject(li)); a.set('events', { 'click': function(action){this[action]();}.pass(action, this), 'mouseenter': function(active){this.addClass(active);}.pass(this.classes.active, a), 'mouseleave': function(active){this.removeClass(active);}.pass(this.classes.active, a) }); }, this); controller.set({ 'events': { 'hide': function(hidden){ if (!this.retrieve('hidden')) this.store('hidden', true).morph(hidden); }.pass(this.classes.get('controller', 'hidden'), controller), 'show': function(visible){ if (this.retrieve('hidden')) this.store('hidden', false).morph(visible); }.pass(this.classes.get('controller', 'visible'), controller) }, 'morph': $merge(this.options.controller, {'link': 'cancel'}) }).store('hidden', false); var keydown = function(e){ if (['left', 'right', 'p'].contains(e.key)){ var controller = this.slideshow.retrieve('controller'); if (controller.retrieve('hidden')) controller.get('morph').set(this.classes.get('controller', 'visible')); switch(e.key){ case 'left': this.slideshow.retrieve((e.shift) ? 'first' : 'prev').fireEvent('mouseenter'); break; case 'right': this.slideshow.retrieve((e.shift) ? 'last' : 'next').fireEvent('mouseenter'); break; default: this.slideshow.retrieve('pause').fireEvent('mouseenter'); break; } } }.bind(this); this.events.keydown.push(keydown); var keyup = function(e){ if (['left', 'right', 'p'].contains(e.key)){ var controller = this.slideshow.retrieve('controller'); if (controller.retrieve('hidden')) controller.store('hidden', false).fireEvent('hide'); switch(e.key){ case 'left': this.slideshow.retrieve((e.shift) ? 'first' : 'prev').fireEvent('mouseleave'); break; case 'right': this.slideshow.retrieve((e.shift) ? 'last' : 'next').fireEvent('mouseleave'); break; default: this.slideshow.retrieve('pause').fireEvent('mouseleave'); break; } } }.bind(this); this.events.keyup.push(keyup); var mousemove = function(e){ var images = this.slideshow.retrieve('images').getCoordinates(); if (e.page.x > images.left && e.page.x < images.right && e.page.y > images.top && e.page.y < images.bottom) this.slideshow.retrieve('controller').fireEvent('show'); else this.slideshow.retrieve('controller').fireEvent('hide'); }.bind(this); this.events.mousemove.push(mousemove); document.addEvents({'keydown': keydown, 'keyup': keyup, 'mousemove': mousemove}); this.slideshow.retrieve('controller', controller).fireEvent('hide'); }, /** Private method: loader Builds the optional loader element, adds interactivity. This method can safely be removed if the loader option is not enabled. */ _loader: function(){ if (this.options.loader === true) this.options.loader = {}; var loader = new Element('div', { 'class': this.classes.get('loader').substr(1), 'morph': $merge(this.options.loader, {'link': 'cancel'}) }).store('hidden', false).store('i', 1).inject(this.slideshow.retrieve('images')); if (this.options.loader.animate){ for (var i = 0; i < this.options.loader.animate[1]; i++) img = new Asset.image(this.options.loader.animate[0].replace(/#/, i)); if (Browser.Engine.trident4 && this.options.loader.animate[0].contains('png')) loader.setStyle('backgroundImage', 'none'); } loader.set('events', { 'animate': function(){ var loader = this.slideshow.retrieve('loader'); var i = (loader.retrieve('i').toInt() + 1) % this.options.loader.animate[1]; loader.store('i', i); var img = this.options.loader.animate[0].replace(/#/, i); if (Browser.Engine.trident4 && this.options.loader.animate[0].contains('png')) loader.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + img + '", sizingMethod="scale")'; else loader.setStyle('backgroundImage', 'url(' + img + ')'); }.bind(this), 'hide': function(){ var loader = this.slideshow.retrieve('loader'); if (!loader.retrieve('hidden')){ loader.store('hidden', true).morph(this.classes.get('loader', 'hidden')); if (this.options.loader.animate) $clear(loader.retrieve('timer')); } }.bind(this), 'show': function(){ var loader = this.slideshow.retrieve('loader'); if (loader.retrieve('hidden')){ loader.store('hidden', false).morph(this.classes.get('loader', 'visible')); if (this.options.loader.animate) loader.store('timer', function(){this.fireEvent('animate');}.periodical(50, loader)); } }.bind(this) }); this.slideshow.retrieve('loader', loader).fireEvent('hide'); }, /** Private method: thumbnails Builds the optional thumbnails element, adds interactivity. This method can safely be removed if the thumbnails option is not enabled. */ _thumbnails: function(){ if (this.options.thumbnails === true) this.options.thumbnails = {}; var el = this.slideshow.getElement(this.classes.get('thumbnails')); var thumbnails = (el) ? el.empty() : new Element('div', {'class': this.classes.get('thumbnails').substr(1)}).inject(this.slideshow); thumbnails.setStyle('overflow', 'hidden'); var ul = new Element('ul', {'tween': {'link': 'cancel'}}).inject(thumbnails); this.data.thumbnails.each(function(thumbnail, i){ var li = new Element('li').inject(ul); var a = new Element('a', { 'events': { 'click': function(i){ this.go(i); return false; }.pass(i, this), 'loaded': function(){ this.data.thumbnails.pop(); if (!this.data.thumbnails.length){ var div = thumbnails.getCoordinates(); var props = thumbnails.retrieve('props'); var limit = 0, pos = props[1], size = props[2]; thumbnails.getElements('li').each(function(li){ var li = li.getCoordinates(); if (li[pos] > limit) limit = li[pos]; }, this); thumbnails.store('limit', div[size] + div[props[0]] - limit); } }.bind(this) }, 'href': this.options.hu + this.data.images[i], 'morph': $merge(this.options.thumbnails, {'link': 'cancel'}) }).inject(li); if (this.data.captions[i] && this.options.titles) a.set('title', this.data.captions[i].replace(/<.+?>/gm, '').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, "'")); var img = new Asset.image(this.options.hu + thumbnail, { 'onload': function(){this.fireEvent('loaded');}.bind(a) }).inject(a); }, this); thumbnails.set('events', { 'scroll': function(n, fast){ var div = this.getCoordinates(); var ul = this.getElement('ul').getPosition(); var props = this.retrieve('props'); var axis = props[3], delta, pos = props[0], size = props[2], value; var tween = this.getElement('ul').get('tween', {'property': pos}); if ($chk(n)){ var li = this.getElements('li')[n].getCoordinates(); delta = div[pos] + (div[size] / 2) - (li[size] / 2) - li[pos] value = (ul[axis] - div[pos] + delta).limit(this.retrieve('limit'), 0); if (fast) tween.set(value); else tween.start(value); } else{ var area = div[props[2]] / 3, page = this.retrieve('page'), velocity = -0.2; if (page[axis] < (div[pos] + area)) delta = (page[axis] - div[pos] - area) * velocity; else if (page[axis] > (div[pos] + div[size] - area)) delta = (page[axis] - div[pos] - div[size] + area) * velocity; if (delta){ value = (ul[axis] - div[pos] + delta).limit(this.retrieve('limit'), 0); tween.set(value); } } }.bind(thumbnails), 'update': function(fast){ var thumbnails = this.slideshow.retrieve('thumbnails'); thumbnails.getElements('a').each(function(a, i){ if (i == this.slide){ if (!a.retrieve('active', false)){ a.store('active', true); var active = this.classes.get('thumbnails', 'active'); if (fast) a.get('morph').set(active); else a.morph(active); } } else { if (a.retrieve('active', true)){ a.store('active', false); var inactive = this.classes.get('thumbnails', 'inactive'); if (fast) a.get('morph').set(inactive); else a.morph(inactive); } } }, this); if (!thumbnails.retrieve('mouseover')) thumbnails.fireEvent('scroll', [this.slide, fast]); }.bind(this) }) var div = thumbnails.getCoordinates(); thumbnails.store('props', (div.height > div.width) ? ['top', 'bottom', 'height', 'y'] : ['left', 'right', 'width', 'x']); var mousemove = function(e){ var div = this.getCoordinates(); if (e.page.x > div.left && e.page.x < div.right && e.page.y > div.top && e.page.y < div.bottom){ this.store('page', e.page); if (!this.retrieve('mouseover')){ this.store('mouseover', true); this.store('timer', function(){this.fireEvent('scroll');}.periodical(50, this)); } } else { if (this.retrieve('mouseover')){ this.store('mouseover', false); $clear(this.retrieve('timer')); } } }.bind(thumbnails); this.events.mousemove.push(mousemove); document.addEvent('mousemove', mousemove); this.slideshow.store('thumbnails', thumbnails); } });
JavaScript
// ----------------------------------------------------------------------------------- // // Lightbox v2.04 // by Lokesh Dhakar - http://www.lokeshdhakar.com // Last Modification: 2/9/08 // // For more information, visit: // http://lokeshdhakar.com/projects/lightbox2/ // // Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/ // - Free for use in both personal and commercial projects // - Attribution requires leaving author name, author link, and the license info intact. // // Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets. // Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous. // // ----------------------------------------------------------------------------------- /* Table of Contents ----------------- Configuration Lightbox Class Declaration - initialize() - updateImageList() - start() - changeImage() - resizeImageContainer() - showImage() - updateDetails() - updateNav() - enableKeyboardNav() - disableKeyboardNav() - keyboardAction() - preloadNeighborImages() - end() Function Calls - document.observe() */ // ----------------------------------------------------------------------------------- // // Configurationl // LightboxOptions = Object.extend({ fileLoadingImage: 'images/loading.gif', fileBottomNavCloseImage: 'images/closelabel.gif', overlayOpacity: 0.8, // controls transparency of shadow overlay animate: true, // toggles resizing animations resizeSpeed: 7, // controls the speed of the image resizing animations (1=slowest and 10=fastest) borderSize: 10, //if you adjust the padding in the CSS, you will need to update this variable // When grouping images this is used to write: Image # of #. // Change it for non-english localization labelImage: "Image", labelOf: "of" }, window.LightboxOptions || {}); // ----------------------------------------------------------------------------------- var Lightbox = Class.create(); Lightbox.prototype = { imageArray: [], activeImage: undefined, // initialize() // Constructor runs on completion of the DOM loading. Calls updateImageList and then // the function inserts html at the bottom of the page which is used to display the shadow // overlay and the image container. // initialize: function() { this.updateImageList(); this.keyboardAction = this.keyboardAction.bindAsEventListener(this); if (LightboxOptions.resizeSpeed > 10) LightboxOptions.resizeSpeed = 10; if (LightboxOptions.resizeSpeed < 1) LightboxOptions.resizeSpeed = 1; this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0; this.overlayDuration = LightboxOptions.animate ? 0.2 : 0; // shadow fade in/out duration // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension. // If animations are turned off, it will be hidden as to prevent a flicker of a // white 250 by 250 box. var size = (LightboxOptions.animate ? 250 : 1) + 'px'; // Code inserts html at the bottom of the page that looks similar to this: // // <div id="overlay"></div> // <div id="lightbox"> // <div id="outerImageContainer"> // <div id="imageContainer"> // <img id="lightboxImage"> // <div style="" id="hoverNav"> // <a href="#" id="prevLink"></a> // <a href="#" id="nextLink"></a> // </div> // <div id="loading"> // <a href="#" id="loadingLink"> // <img src="images/loading.gif"> // </a> // </div> // </div> // </div> // <div id="imageDataContainer"> // <div id="imageData"> // <div id="imageDetails"> // <span id="caption"></span> // <span id="numberDisplay"></span> // </div> // <div id="bottomNav"> // <a href="#" id="bottomNavClose"> // <img src="images/close.gif"> // </a> // </div> // </div> // </div> // </div> var objBody = $$('body')[0]; objBody.appendChild(Builder.node('div',{id:'overlay'})); objBody.appendChild(Builder.node('div',{id:'lightbox'}, [ Builder.node('div',{id:'outerImageContainer'}, Builder.node('div',{id:'imageContainer'}, [ Builder.node('img',{id:'lightboxImage'}), Builder.node('div',{id:'hoverNav'}, [ Builder.node('a',{id:'prevLink', href: '#' }), Builder.node('a',{id:'nextLink', href: '#' }) ]), Builder.node('div',{id:'loading'}, Builder.node('a',{id:'loadingLink', href: '#' }, Builder.node('img', {src: LightboxOptions.fileLoadingImage}) ) ) ]) ), Builder.node('div', {id:'imageDataContainer'}, Builder.node('div',{id:'imageData'}, [ Builder.node('div',{id:'imageDetails'}, [ Builder.node('span',{id:'caption'}), Builder.node('span',{id:'numberDisplay'}) ]), Builder.node('div',{id:'bottomNav'}, Builder.node('a',{id:'bottomNavClose', href: '#' }, Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage }) ) ) ]) ) ])); $('overlay').hide().observe('click', (function() { this.end(); }).bind(this)); $('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this)); $('outerImageContainer').setStyle({ width: size, height: size }); $('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this)); $('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this)); $('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); $('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); var th = this; (function(){ var ids = 'overlay lightbox outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose'; $w(ids).each(function(id){ th[id] = $(id); }); }).defer(); }, // // updateImageList() // Loops through anchor tags looking for 'lightbox' references and applies onclick // events to appropriate links. You can rerun after dynamically adding images w/ajax. // updateImageList: function() { this.updateImageList = Prototype.emptyFunction; document.observe('click', (function(event){ var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]'); if (target) { event.stop(); this.start(target); } }).bind(this)); }, // // start() // Display overlay and lightbox. If image is part of a set, add siblings to imageArray. // start: function(imageLink) { $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' }); // stretch overlay to fill page and fade in var arrayPageSize = this.getPageSize(); $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' }); new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity }); this.imageArray = []; var imageNum = 0; if ((imageLink.rel == 'lightbox')){ // if image is NOT part of a set, add single image to imageArray this.imageArray.push([imageLink.href, imageLink.title]); } else { // if image is part of a set.. this.imageArray = $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]'). collect(function(anchor){ return [anchor.href, anchor.title]; }). uniq(); while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; } } // calculate top and left offset for the lightbox var arrayPageScroll = document.viewport.getScrollOffsets(); var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10); var lightboxLeft = arrayPageScroll[0]; this.lightbox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show(); this.changeImage(imageNum); }, // // changeImage() // Hide most elements and preload image in preparation for resizing image container. // changeImage: function(imageNum) { this.activeImage = imageNum; // update global var // hide elements during transition if (LightboxOptions.animate) this.loading.show(); this.lightboxImage.hide(); this.hoverNav.hide(); this.prevLink.hide(); this.nextLink.hide(); // HACK: Opera9 does not currently support scriptaculous opacity and appear fx this.imageDataContainer.setStyle({opacity: .0001}); this.numberDisplay.hide(); var imgPreloader = new Image(); // once image is preloaded, resize image container imgPreloader.onload = (function(){ this.lightboxImage.src = this.imageArray[this.activeImage][0]; this.resizeImageContainer(imgPreloader.width, imgPreloader.height); }).bind(this); imgPreloader.src = this.imageArray[this.activeImage][0]; }, // // resizeImageContainer() // resizeImageContainer: function(imgWidth, imgHeight) { // get current width and height var widthCurrent = this.outerImageContainer.getWidth(); var heightCurrent = this.outerImageContainer.getHeight(); // get new width and height var widthNew = (imgWidth + LightboxOptions.borderSize * 2); var heightNew = (imgHeight + LightboxOptions.borderSize * 2); // scalars based on change from old to new var xScale = (widthNew / widthCurrent) * 100; var yScale = (heightNew / heightCurrent) * 100; // calculate size difference between new and old image, and resize if necessary var wDiff = widthCurrent - widthNew; var hDiff = heightCurrent - heightNew; if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); // if new and old image are same size and no scaling transition is necessary, // do a quick pause to prevent image flicker. var timeout = 0; if ((hDiff == 0) && (wDiff == 0)){ timeout = 100; if (Prototype.Browser.IE) timeout = 250; } (function(){ this.prevLink.setStyle({ height: imgHeight + 'px' }); this.nextLink.setStyle({ height: imgHeight + 'px' }); this.imageDataContainer.setStyle({ width: widthNew + 'px' }); this.showImage(); }).bind(this).delay(timeout / 1000); }, // // showImage() // Display image and begin preloading neighbors. // showImage: function(){ this.loading.hide(); new Effect.Appear(this.lightboxImage, { duration: this.resizeDuration, queue: 'end', afterFinish: (function(){ this.updateDetails(); }).bind(this) }); this.preloadNeighborImages(); }, // // updateDetails() // Display caption, image number, and bottom nav. // updateDetails: function() { // if caption is not null if (this.imageArray[this.activeImage][1] != ""){ this.caption.update(this.imageArray[this.activeImage][1]).show(); } // if image is part of set display 'Image x of x' if (this.imageArray.length > 1){ this.numberDisplay.update( LightboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + LightboxOptions.labelOf + ' ' + this.imageArray.length).show(); } new Effect.Parallel( [ new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration }) ], { duration: this.resizeDuration, afterFinish: (function() { // update overlay size and update nav var arrayPageSize = this.getPageSize(); this.overlay.setStyle({ height: arrayPageSize[1] + 'px' }); this.updateNav(); }).bind(this) } ); }, // // updateNav() // Display appropriate previous and next hover navigation. // updateNav: function() { this.hoverNav.show(); // if not first image in set, display prev image button if (this.activeImage > 0) this.prevLink.show(); // if not last image in set, display next image button if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show(); this.enableKeyboardNav(); }, // // enableKeyboardNav() // enableKeyboardNav: function() { document.observe('keydown', this.keyboardAction); }, // // disableKeyboardNav() // disableKeyboardNav: function() { document.stopObserving('keydown', this.keyboardAction); }, // // keyboardAction() // keyboardAction: function(event) { var keycode = event.keyCode; var escapeKey; if (event.DOM_VK_ESCAPE) { // mozilla escapeKey = event.DOM_VK_ESCAPE; } else { // ie escapeKey = 27; } var key = String.fromCharCode(keycode).toLowerCase(); if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox this.end(); } else if ((key == 'p') || (keycode == 37)){ // display previous image if (this.activeImage != 0){ this.disableKeyboardNav(); this.changeImage(this.activeImage - 1); } } else if ((key == 'n') || (keycode == 39)){ // display next image if (this.activeImage != (this.imageArray.length - 1)){ this.disableKeyboardNav(); this.changeImage(this.activeImage + 1); } } }, // // preloadNeighborImages() // Preload previous and next images. // preloadNeighborImages: function(){ var preloadNextImage, preloadPrevImage; if (this.imageArray.length > this.activeImage + 1){ preloadNextImage = new Image(); preloadNextImage.src = this.imageArray[this.activeImage + 1][0]; } if (this.activeImage > 0){ preloadPrevImage = new Image(); preloadPrevImage.src = this.imageArray[this.activeImage - 1][0]; } }, // // end() // end: function() { this.disableKeyboardNav(); this.lightbox.hide(); new Effect.Fade(this.overlay, { duration: this.overlayDuration }); $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' }); }, // // getPageSize() // getPageSize: function() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } var windowWidth, windowHeight; if (self.innerHeight) { // all except Explorer if(document.documentElement.clientWidth){ windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } // for small pages with total height less then height of the viewport if(yScroll < windowHeight){ pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if(xScroll < windowWidth){ pageWidth = xScroll; } else { pageWidth = windowWidth; } return [pageWidth,pageHeight]; } } document.observe('dom:loaded', function () { new Lightbox(); });
JavaScript
// script.aculo.us scriptaculous.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008 // Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // For details, see the script.aculo.us web site: http://script.aculo.us/ var Scriptaculous = { Version: '1.8.1', require: function(libraryName) { // inserting via DOM fails in Safari 2.0, so brute force approach document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>'); }, REQUIRED_PROTOTYPE: '1.6.0', load: function() { function convertVersionString(versionString){ var r = versionString.split('.'); return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]); } if((typeof Prototype=='undefined') || (typeof Element == 'undefined') || (typeof Element.Methods=='undefined') || (convertVersionString(Prototype.Version) < convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE))) throw("script.aculo.us requires the Prototype JavaScript framework >= " + Scriptaculous.REQUIRED_PROTOTYPE); $A(document.getElementsByTagName("script")).findAll( function(s) { return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/)) }).each( function(s) { var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,''); var includes = s.src.match(/\?.*load=([a-z,]*)/); (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each( function(include) { Scriptaculous.require(path+include+'.js') }); }); } } Scriptaculous.load();
JavaScript
// script.aculo.us builder.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008 // Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ var Builder = { NODEMAP: { AREA: 'map', CAPTION: 'table', COL: 'table', COLGROUP: 'table', LEGEND: 'fieldset', OPTGROUP: 'select', OPTION: 'select', PARAM: 'object', TBODY: 'table', TD: 'table', TFOOT: 'table', TH: 'table', THEAD: 'table', TR: 'table' }, // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken, // due to a Firefox bug node: function(elementName) { elementName = elementName.toUpperCase(); // try innerHTML approach var parentTag = this.NODEMAP[elementName] || 'div'; var parentElement = document.createElement(parentTag); try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" + elementName + "></" + elementName + ">"; } catch(e) {} var element = parentElement.firstChild || null; // see if browser added wrapping tags if(element && (element.tagName.toUpperCase() != elementName)) element = element.getElementsByTagName(elementName)[0]; // fallback to createElement approach if(!element) element = document.createElement(elementName); // abort if nothing could be created if(!element) return; // attributes (or text) if(arguments[1]) if(this._isStringOrNumber(arguments[1]) || (arguments[1] instanceof Array) || arguments[1].tagName) { this._children(element, arguments[1]); } else { var attrs = this._attributes(arguments[1]); if(attrs.length) { try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" +elementName + " " + attrs + "></" + elementName + ">"; } catch(e) {} element = parentElement.firstChild || null; // workaround firefox 1.0.X bug if(!element) { element = document.createElement(elementName); for(attr in arguments[1]) element[attr == 'class' ? 'className' : attr] = arguments[1][attr]; } if(element.tagName.toUpperCase() != elementName) element = parentElement.getElementsByTagName(elementName)[0]; } } // text, or array of children if(arguments[2]) this._children(element, arguments[2]); return element; }, _text: function(text) { return document.createTextNode(text); }, ATTR_MAP: { 'className': 'class', 'htmlFor': 'for' }, _attributes: function(attributes) { var attrs = []; for(attribute in attributes) attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) + '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"'); return attrs.join(" "); }, _children: function(element, children) { if(children.tagName) { element.appendChild(children); return; } if(typeof children=='object') { // array can hold nodes and text children.flatten().each( function(e) { if(typeof e=='object') element.appendChild(e) else if(Builder._isStringOrNumber(e)) element.appendChild(Builder._text(e)); }); } else if(Builder._isStringOrNumber(children)) element.appendChild(Builder._text(children)); }, _isStringOrNumber: function(param) { return(typeof param=='string' || typeof param=='number'); }, build: function(html) { var element = this.node('div'); $(element).update(html.strip()); return element.down(); }, dump: function(scope) { if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " + "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " + "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+ "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+ "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+ "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/); tags.each( function(tag){ scope[tag] = function() { return Builder.node.apply(Builder, [tag].concat($A(arguments))); } }); } }
JavaScript
var Slate = function () { var chartColors, nav, navTop; chartColors = ["#263849", "#F90", "#666", "#BBB"]; return { start: start, chartColors: chartColors }; function start () { nav = $('#nav'); navTop = nav.offset ().top; bindNavEvents (); bindWidgetEvents (); bindAccordionEvents (); enableAutoPlugins (); } function enableAutoPlugins () { if ($.fn.tooltip) { $('.ui-tooltip').tooltip (); } if ($.fn.popover) { $('.ui-popover').popover (); } if ($.fn.lightbox) { $('.ui-lightbox').lightbox(); } if ($.fn.dataTable) { $('.data-table').dataTable( { sDom: "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>", sPaginationType: "bootstrap", oLanguage: { "sLengthMenu": "_MENU_ records per page" } }); } } function bindNavEvents () { var msie8 = $.browser.version === '8.0' && $.browser.msie; if (!msie8) { $(window).bind ('scroll', navScroll); } $('#info-trigger').live ('click', function (e) { e.preventDefault (); $('#info-menu').toggleClass ('toggle-menu-show'); $(document).bind ('click.info', function (e) { if ($(e.target).is ('#info-menu')) { return false; } if ($(e.target).parents ('#info-menu').length == 1) { return false; } $('#info-menu').removeClass ('toggle-menu-show'); $(document).unbind ('click.info'); }); }); } function navScroll () { var p = $(window).scrollTop (); ((p)>navTop) ? $('body').addClass ('nav-fixed') : $('body').removeClass ('nav-fixed'); } function bindWidgetEvents () { $('.widget-tabs .nav-tabs a').live ('click', widgetTabClickHandler); } function bindAccordionEvents () { $('.widget-accordion .accordion').on('show', function (e) { $(e.target).prev('.accordion-heading').parent ().addClass('open'); }); $('.widget-accordion .accordion').on('hide', function (e) { $(this).find('.accordion-toggle').not($(e.target)).parents ('.accordion-group').removeClass('open'); }); $('.widget-accordion .accordion').each (function () { $(this).find ('.accordion-body.in').parent ().addClass ('open'); }); } function widgetTabClickHandler (e) { e.preventDefault(); $(this).tab('show'); } }(); $(function () { Slate.start (); });
JavaScript
//Gradual Elements Fader- By Dynamic Drive at http://www.dynamicdrive.com //Last updated: Nov 8th, 07' var gfader={} gfader.baseopacity=0 //set base opacity when mouse isn't over element (decimal below 1) gfader.increment=0.2 //amount of opacity to increase after each iteration (suggestion: 0.1 or 0.2) document.write('<style type="text/css">\n') //write out CSS to enable opacity on "gfader" class document.write('.gfader{filter:progid:DXImageTransform.Microsoft.alpha(opacity='+gfader.baseopacity*100+'); -moz-opacity:'+gfader.baseopacity+'; opacity:'+gfader.baseopacity+';}\n') document.write('</style>') gfader.setopacity=function(obj, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between) var targetobject=obj if (targetobject && targetobject.filters && targetobject.filters[0]){ //IE syntax if (typeof targetobject.filters[0].opacity=="number") //IE6 targetobject.filters[0].opacity=value*100 else //IE 5.5 targetobject.style.filter="alpha(opacity="+value*100+")" } else if (targetobject && typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax targetobject.style.MozOpacity=value else if (targetobject && typeof targetobject.style.opacity!="undefined") //Standard opacity syntax targetobject.style.opacity=value targetobject.currentopacity=value } gfader.fadeupdown=function(obj, direction){ var targetobject=obj var fadeamount=(direction=="fadeup")? this.increment : -this.increment if (targetobject && (direction=="fadeup" && targetobject.currentopacity<1 || direction=="fadedown" && targetobject.currentopacity>this.baseopacity)){ this.setopacity(obj, targetobject.currentopacity+fadeamount) window["opacityfader"+obj._fadeorder]=setTimeout(function(){gfader.fadeupdown(obj, direction)}, 50) } } gfader.clearTimer=function(obj){ if (typeof window["opacityfader"+obj._fadeorder]!="undefined") clearTimeout(window["opacityfader"+obj._fadeorder]) } gfader.isContained=function(m, e){ var e=window.event || e var c=e.relatedTarget || ((e.type=="mouseover")? e.fromElement : e.toElement) while (c && c!=m)try {c=c.parentNode} catch(e){c=m} if (c==m) return true else return false } gfader.fadeinterface=function(obj, e, direction){ if (!this.isContained(obj, e)){ gfader.clearTimer(obj) gfader.fadeupdown(obj, direction) } } gfader.collectElementbyClass=function(classname){ //Returns an array containing DIVs with specified classname var classnameRE=new RegExp("(^|\\s+)"+classname+"($|\\s+)", "i") //regular expression to screen for classname within element var pieces=[] var alltags=document.all? document.all : document.getElementsByTagName("*") for (var i=0; i<alltags.length; i++){ if (typeof alltags[i].className=="string" && alltags[i].className.search(classnameRE)!=-1) pieces[pieces.length]=alltags[i] } return pieces } gfader.init=function(){ var targetobjects=this.collectElementbyClass("gfader") for (var i=0; i<targetobjects.length; i++){ targetobjects[i]._fadeorder=i this.setopacity(targetobjects[i], this.baseopacity) targetobjects[i].onmouseover=function(e){gfader.fadeinterface(this, e, "fadeup")} targetobjects[i].onmouseout=function(e){gfader.fadeinterface(this, e, "fadedown")} } } /*********************************************** * Cool DHTML tooltip script II- ? Dynamic Drive DHTML code library (www.dynamicdrive.com) ***********************************************/ var offsetfromcursorX=12 //Customize x offset of tooltip var offsetfromcursorY=10 //Customize y offset of tooltip var offsetdivfrompointerX=10 //Customize x offset of tooltip DIV relative to pointer image var offsetdivfrompointerY=14 //Customize y offset of tooltip DIV relative to pointer image. Tip: Set it to (height_of_pointer_image-1). document.write('<div id="gfitooltip"></div>') //write out tooltip DIV document.write('<img id="gfipointer" src="images/arrow.gif">') //write out pointer image var ie=document.all var ns6=document.getElementById && !document.all var enabletip=false if (ie||ns6) var tipobj=document.all? document.all["gfitooltip"] : document.getElementById? document.getElementById("gfitooltip") : "" var pointerobj=document.all? document.all["gfipointer"] : document.getElementById? document.getElementById("gfipointer") : "" function ietruebody(){ return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body } function tip(thetext, thewidth, thecolor){ if (ns6||ie){ if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px" if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor tipobj.innerHTML=thetext enabletip=true return false } } function positiontip(e){ if (enabletip){ var nondefaultpos=false var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft; var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop; //Find out how close the mouse is to the corner of the window var winwidth=ie&&!window.opera? ietruebody().clientWidth : window.innerWidth-20 var winheight=ie&&!window.opera? ietruebody().clientHeight : window.innerHeight-20 var rightedge=ie&&!window.opera? winwidth-event.clientX-offsetfromcursorX : winwidth-e.clientX-offsetfromcursorX var bottomedge=ie&&!window.opera? winheight-event.clientY-offsetfromcursorY : winheight-e.clientY-offsetfromcursorY var leftedge=(offsetfromcursorX<0)? offsetfromcursorX*(-1) : -1000 //if the horizontal distance isn't enough to accomodate the width of the context menu if (rightedge<tipobj.offsetWidth){ //move the horizontal position of the menu to the left by it's width tipobj.style.left=curX-tipobj.offsetWidth+"px" nondefaultpos=true } else if (curX<leftedge) tipobj.style.left="5px" else{ //position the horizontal position of the menu where the mouse is positioned tipobj.style.left=curX+offsetfromcursorX-offsetdivfrompointerX+"px" pointerobj.style.left=curX+offsetfromcursorX+"px" } //same concept with the vertical position if (bottomedge<tipobj.offsetHeight){ tipobj.style.top=curY-tipobj.offsetHeight-offsetfromcursorY+"px" nondefaultpos=true } else{ tipobj.style.top=curY+offsetfromcursorY+offsetdivfrompointerY+"px" pointerobj.style.top=curY+offsetfromcursorY+"px" } tipobj.style.visibility="visible" if (!nondefaultpos) pointerobj.style.visibility="visible" else pointerobj.style.visibility="hidden" } } function hidetip(){ if (ns6||ie){ enabletip=false tipobj.style.visibility="hidden" pointerobj.style.visibility="hidden" tipobj.style.left="-1000px" tipobj.style.backgroundColor='' tipobj.style.width='' } } document.onmousemove=positiontip
JavaScript
//Gradual Elements Fader- By Dynamic Drive at http://www.dynamicdrive.com //Last updated: Nov 8th, 07' var gfader={} gfader.baseopacity=0 //set base opacity when mouse isn't over element (decimal below 1) gfader.increment=0.2 //amount of opacity to increase after each iteration (suggestion: 0.1 or 0.2) document.write('<style type="text/css">\n') //write out CSS to enable opacity on "gfader" class document.write('.gfader{filter:progid:DXImageTransform.Microsoft.alpha(opacity='+gfader.baseopacity*100+'); -moz-opacity:'+gfader.baseopacity+'; opacity:'+gfader.baseopacity+';}\n') document.write('</style>') gfader.setopacity=function(obj, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between) var targetobject=obj if (targetobject && targetobject.filters && targetobject.filters[0]){ //IE syntax if (typeof targetobject.filters[0].opacity=="number") //IE6 targetobject.filters[0].opacity=value*100 else //IE 5.5 targetobject.style.filter="alpha(opacity="+value*100+")" } else if (targetobject && typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax targetobject.style.MozOpacity=value else if (targetobject && typeof targetobject.style.opacity!="undefined") //Standard opacity syntax targetobject.style.opacity=value targetobject.currentopacity=value } gfader.fadeupdown=function(obj, direction){ var targetobject=obj var fadeamount=(direction=="fadeup")? this.increment : -this.increment if (targetobject && (direction=="fadeup" && targetobject.currentopacity<1 || direction=="fadedown" && targetobject.currentopacity>this.baseopacity)){ this.setopacity(obj, targetobject.currentopacity+fadeamount) window["opacityfader"+obj._fadeorder]=setTimeout(function(){gfader.fadeupdown(obj, direction)}, 50) } } gfader.clearTimer=function(obj){ if (typeof window["opacityfader"+obj._fadeorder]!="undefined") clearTimeout(window["opacityfader"+obj._fadeorder]) } gfader.isContained=function(m, e){ var e=window.event || e var c=e.relatedTarget || ((e.type=="mouseover")? e.fromElement : e.toElement) while (c && c!=m)try {c=c.parentNode} catch(e){c=m} if (c==m) return true else return false } gfader.fadeinterface=function(obj, e, direction){ if (!this.isContained(obj, e)){ gfader.clearTimer(obj) gfader.fadeupdown(obj, direction) } } gfader.collectElementbyClass=function(classname){ //Returns an array containing DIVs with specified classname var classnameRE=new RegExp("(^|\\s+)"+classname+"($|\\s+)", "i") //regular expression to screen for classname within element var pieces=[] var alltags=document.all? document.all : document.getElementsByTagName("*") for (var i=0; i<alltags.length; i++){ if (typeof alltags[i].className=="string" && alltags[i].className.search(classnameRE)!=-1) pieces[pieces.length]=alltags[i] } return pieces } gfader.init=function(){ var targetobjects=this.collectElementbyClass("gfader") for (var i=0; i<targetobjects.length; i++){ targetobjects[i]._fadeorder=i this.setopacity(targetobjects[i], this.baseopacity) targetobjects[i].onmouseover=function(e){gfader.fadeinterface(this, e, "fadeup")} targetobjects[i].onmouseout=function(e){gfader.fadeinterface(this, e, "fadedown")} } } /*********************************************** * Cool DHTML tooltip script II- ? Dynamic Drive DHTML code library (www.dynamicdrive.com) ***********************************************/ var offsetfromcursorX=12 //Customize x offset of tooltip var offsetfromcursorY=10 //Customize y offset of tooltip var offsetdivfrompointerX=10 //Customize x offset of tooltip DIV relative to pointer image var offsetdivfrompointerY=14 //Customize y offset of tooltip DIV relative to pointer image. Tip: Set it to (height_of_pointer_image-1). document.write('<div id="gfitooltip"></div>') //write out tooltip DIV document.write('<img id="gfipointer" src="images/arrow.gif">') //write out pointer image var ie=document.all var ns6=document.getElementById && !document.all var enabletip=false if (ie||ns6) var tipobj=document.all? document.all["gfitooltip"] : document.getElementById? document.getElementById("gfitooltip") : "" var pointerobj=document.all? document.all["gfipointer"] : document.getElementById? document.getElementById("gfipointer") : "" function ietruebody(){ return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body } function tip(thetext, thewidth, thecolor){ if (ns6||ie){ if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px" if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor tipobj.innerHTML=thetext enabletip=true return false } } function positiontip(e){ if (enabletip){ var nondefaultpos=false var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft; var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop; //Find out how close the mouse is to the corner of the window var winwidth=ie&&!window.opera? ietruebody().clientWidth : window.innerWidth-20 var winheight=ie&&!window.opera? ietruebody().clientHeight : window.innerHeight-20 var rightedge=ie&&!window.opera? winwidth-event.clientX-offsetfromcursorX : winwidth-e.clientX-offsetfromcursorX var bottomedge=ie&&!window.opera? winheight-event.clientY-offsetfromcursorY : winheight-e.clientY-offsetfromcursorY var leftedge=(offsetfromcursorX<0)? offsetfromcursorX*(-1) : -1000 //if the horizontal distance isn't enough to accomodate the width of the context menu if (rightedge<tipobj.offsetWidth){ //move the horizontal position of the menu to the left by it's width tipobj.style.left=curX-tipobj.offsetWidth+"px" nondefaultpos=true } else if (curX<leftedge) tipobj.style.left="5px" else{ //position the horizontal position of the menu where the mouse is positioned tipobj.style.left=curX+offsetfromcursorX-offsetdivfrompointerX+"px" pointerobj.style.left=curX+offsetfromcursorX+"px" } //same concept with the vertical position if (bottomedge<tipobj.offsetHeight){ tipobj.style.top=curY-tipobj.offsetHeight-offsetfromcursorY+"px" nondefaultpos=true } else{ tipobj.style.top=curY+offsetfromcursorY+offsetdivfrompointerY+"px" pointerobj.style.top=curY+offsetfromcursorY+"px" } tipobj.style.visibility="visible" if (!nondefaultpos) pointerobj.style.visibility="visible" else pointerobj.style.visibility="hidden" } } function hidetip(){ if (ns6||ie){ enabletip=false tipobj.style.visibility="hidden" pointerobj.style.visibility="hidden" tipobj.style.left="-1000px" tipobj.style.backgroundColor='' tipobj.style.width='' } } document.onmousemove=positiontip
JavaScript
/* Set the defaults for DataTables initialisation */ $.extend( true, $.fn.dataTable.defaults, { "sDom": "<'row'<'col-sm-6'l><'col-sm-6'f>r>t<'row'<'col-sm-6'i><'col-sm-6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page", "sSearch": "" } }); /* Default class modification */ $.extend( $.fn.dataTableExt.oStdClasses, { "sWrapper": "dataTables_wrapper" } ); /* API method to get paging information */ $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ), "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength ) }; }; /* Bootstrap style pagination control */ $.extend( $.fn.dataTableExt.oPagination, { "bootstrap": { "fnInit": function( oSettings, nPaging, fnDraw ) { var oLang = oSettings.oLanguage.oPaginate; var fnClickHandler = function ( e ) { e.preventDefault(); if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) { fnDraw( oSettings ); } }; $(nPaging).append( '<ol class="pagination">' + '<li class="prev disabled"><a href="#"><i class="fa fa-long-arrow-left"></i> '+oLang.sPrevious+'</a></li>'+ '<li class="next disabled"><a href="#">'+oLang.sNext+' <i class="fa fa-long-arrow-right"></i></a></li>'+ '</ol>' ); var els = $('a', nPaging); $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler ); $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler ); }, "fnUpdate": function ( oSettings, fnDraw ) { var iListLength = 5; var oPaging = oSettings.oInstance.fnPagingInfo(); var an = oSettings.aanFeatures.p; var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2); if ( oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if ( oPaging.iPage <= iHalf ) { iStart = 1; iEnd = iListLength; } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; } for ( i=0, ien=an.length ; i<ien ; i++ ) { // Remove the middle elements $('li:gt(0)', an[i]).filter(':not(:last)').remove(); // Add the new list items and their event handlers for ( j=iStart ; j<=iEnd ; j++ ) { sClass = (j==oPaging.iPage+1) ? 'class="active"' : ''; $('<li '+sClass+'><a href="#">'+j+'</a></li>') .insertBefore( $('li:last', an[i])[0] ) .bind('click', function (e) { e.preventDefault(); oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength; fnDraw( oSettings ); } ); } // Add / remove disabled classes from the static elements if ( oPaging.iPage === 0 ) { $('li:first', an[i]).addClass('disabled'); } else { $('li:first', an[i]).removeClass('disabled'); } if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { $('li:last', an[i]).addClass('disabled'); } else { $('li:last', an[i]).removeClass('disabled'); } } } } } ); /* * TableTools Bootstrap compatibility * Required TableTools 2.1+ */ if ( $.fn.DataTable.TableTools ) { // Set the classes that TableTools uses to something suitable for Bootstrap $.extend( true, $.fn.DataTable.TableTools.classes, { "container": "btn-group", "buttons": { "normal": "btn btn-default", "disabled": "disabled" }, "collection": { "container": "", "buttons": { "normal": "", "disabled": "disabled" } }, "print": { "info": "modal" }, "select": { "row": "active" } } ); // Have the collection use a bootstrap compatible dropdown $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, { "collection": { "container": "ul", "button": "li", "liner": "a" } } ); }
JavaScript
/* * Set the default display controller to be our bootstrap control */ $.fn.dataTable.Editor.defaults.display = "bootstrap"; /* * Alter the buttons that Editor adds to TableTools so they are suitable for bootstrap */ var i18nDefaults = $.fn.dataTable.Editor.defaults.i18n; i18nDefaults.create.title = "<h3>"+i18nDefaults.create.title+"</h3>"; i18nDefaults.edit.title = "<h3>"+i18nDefaults.edit.title+"</h3>"; i18nDefaults.remove.title = "<h3>"+i18nDefaults.remove.title+"</h3>"; if ( window.TableTools ) { TableTools.BUTTONS.editor_create.formButtons[0].className = "btn btn-primary"; TableTools.BUTTONS.editor_edit.formButtons[0].className = "btn btn-primary"; TableTools.BUTTONS.editor_remove.formButtons[0].className = "btn btn-danger"; } /* * Change the default classes from Editor to be classes for Bootstrap */ $.extend( true, $.fn.dataTable.Editor.classes, { "wrapper": "DTE modal-dialog", "header": { "wrapper": "modal-header" }, "body": { "wrapper": "modal-body" }, "footer": { "wrapper": "modal-footer" }, "form": { "tag": "form-horizontal" }, "field": { "wrapper": "form-group", "label": "col-sm-4 control-label", "input": "col-sm-8", "error": "error", "msg-labelInfo": "help-block", "msg-info": "help-block", "msg-message": "help-block", "msg-error": "help-block" } } ); /* * Bootstrap display controller - this is effectively a proxy to the Bootstrap * modal control. */ (function(window, document, $, DataTable) { var self; DataTable.Editor.display.bootstrap = $.extend( true, {}, DataTable.Editor.models.displayController, { /* * API methods */ "init": function ( dte ) { self._dom.content = $('<div class="modal fade">')[0]; self._dom.close = $('<button class="close">&times;</div>')[0]; // Bootstrap 3 needs an extra element in the modal $('<div class="modal-content"></div>') .append( $(dte.dom.wrapper).children() ) .appendTo( dte.dom.wrapper ); $(self._dom.close).click( function () { self._dte.close('icon'); } ); $(document).on('click', 'div.modal-backdrop', function () { self._dte.close('background'); } ); return self; }, "open": function ( dte, append, callback ) { if ( self._shown ) { if ( callback ) { callback(); } return; } self._dte = dte; self._shown = true; $(self._dom.content).children().detach(); self._dom.content.appendChild( append ); $('div.modal-header', append).prepend( self._dom.close ); $(self._dom.content) .one('shown', function () { if ( callback ) { callback(); } }) .one('hidden', function () { self._shown = false; }) .modal( { "backdrop": "static" } ); $('input[type=text], select', self._dom.content).addClass( 'form-control' ); }, "close": function ( dte, callback ) { if ( !self._shown ) { if ( callback ) { callback(); } return; } $(self._dom.content).modal('hide'); self._dte = dte; self._shown = false; if ( callback ) { callback(); } }, /* * Private properties */ "_shown": false, "_dte": null, "_dom": {} } ); self = DataTable.Editor.display.bootstrap; }(window, document, jQuery, jQuery.fn.dataTable));
JavaScript
/** * * index.html scripts * */ !function(root, $) { /** * Fetch latest commits from Github API and cache them * @link https://gist.github.com/4520294 * */ root["ghcommits"] = { "repo_name": "xaguilars/bootstrap-colorpicker", "cache_enabled": true, //cache api responses? "cache_ttl": (2 * 60 * 60), // 2h (in seconds) "onload": {}, "callback": function() { }, "load": function(count, onload) { var $self = this; count = count || 10; $self.onload = onload || function() { }; if ($self.cache_enabled && root["localStorage"]) { var cache_key = "repo_commits"; var expiration = localStorage.getItem(cache_key + "_expiration"); if (expiration && (expiration < +new Date())) { localStorage.removeItem(cache_key); localStorage.removeItem(cache_key + "_expiration"); expiration = false; } var commits = localStorage.getItem(cache_key); if (commits) { if (root["console"]) console.info("Commit data feched from localStorage"); $self.store(JSON.parse(commits), false); $self.onload($self.data); return; } } $self.query(count); }, "store": function(commitsJson, cache) { var $self = this; $self.data = commitsJson; if (cache && root["localStorage"]) { localStorage.setItem("repo_commits", JSON.stringify(commitsJson)); localStorage.setItem("repo_commits_expiration", +new Date() + 1000 * $self.cache_ttl); } }, "query": function(count) { var $self = this; var query_url = 'https://api.github.com/repos/' + $self.repo_name + '/commits?per_page=' + count; console.info("Fetching commit data from " + query_url); $.ajax({'dataType': "jsonp", 'url': query_url, 'jsonpCallback': 'ghcommits._jsonpcb'}); }, "_jsonpcb": function(jsonpresp) { ghcommits.store(jsonpresp.data, ghcommits.cache_enabled); ghcommits.onload(ghcommits.data); } } // App $(function() { root.prettyPrint && prettyPrint(); var _createColorpickers = function(){ $('#cp1').colorpicker({ format: 'hex' }); $('#cp2').colorpicker(); $('#cp3').colorpicker(); var bodyStyle = $('body')[0].style; $('#cp4').colorpicker().on('changeColor', function(ev) { bodyStyle.backgroundColor = ev.color.toHex(); }); } _createColorpickers(); $('.bscp-destroy').click(function(e){ e.preventDefault(); $('.bscp').colorpicker('destroy'); }); $('.bscp-create').click(function(e){ e.preventDefault(); _createColorpickers(); }); try { // load latest commits under a try to not paralize the app ghcommits.load(10, function(data) { if (data && (data.length > 0)) { $(data).each(function(i, item) { $("#changelog ul").append($('<li>').html("<b>" + item.commit.author .date.replace("T", " ").replace("Z", "") + ":</b> " + item.commit.message)); }); } }); } catch (err) { } }); }(window, window.jQuery);
JavaScript
/*jshint undef: true, unused:true */ /*global jQuery: true */ /*!========================================================================= * Bootstrap Dual Listbox * v2.0.1 * * Responsive dual multiple select with filtering. Designed to work on * small touch devices. * * https://github.com/istvan-meszaros/bootstrap-duallistbox * http://www.virtuosoft.eu/code/bootstrap-duallistbox/ * * Copyright 2013 István Ujj-Mészáros * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ====================================================================== */ (function($) { "use strict"; $.fn.bootstrapDualListbox = function(options) { return this.each(function() { var $this = $(this); if (!$this.is("select")) { return $this.find("select").each(function(index, item) { $(item).bootstrapDualListbox(options); }); } if ($this.data('duallistbox_generated')) { return this; } var settings = $.extend( { bootstrap2compatible : false, preserveselectiononmove : false, // 'all' / 'moved' / false moveonselect : true, // true/false (forced true on androids, see the comment later) initialfilterfrom : '', // string, filter selectables list on init initialfilterto : '', // string, filter selected list on init helperselectnamepostfix : '_helper', // 'string_of_postfix' / false infotext : 'Showing all {0}',// text when all options are visible / false for no info text infotextfiltered : '<span class="label label-warning">Filtered</span> {0} from {1}',// when not all of the options are visible due to the filter infotextempty : 'Empty list', // when there are no options present in the list selectorminimalheight : 100, showfilterinputs : true, filterplaceholder : 'Filter', filtertextclear : 'show all', nonselectedlistlabel : false, // 'string', false selectedlistlabel : false // 'string', false }, options); var container; if (settings.bootstrap2compatible) { container = $('<div class="row-fluid bootstrap-duallistbox-container bs2compatible"><div class="span6 box1"><span class="info-container"><span class="info"></span><button type="button" class="btn btn-mini clear1 pull-right">' + settings.filtertextclear + '</button></span><input placeholder="' + settings.filterplaceholder + '" class="filter" type="text"><div class="btn-group buttons"><button type="button" class="btn moveall" title="Move all"><i class="fa fa-arrow-right"></i><i class="fa fa-arrow-right"></i></button><button type="button" class="btn move" title="Move selected"><i class="fa fa-arrow-right"></i></button></div><select multiple="multiple" data-duallistbox_generated="true"></select></div><div class="span6 box2"><span class="info-container"><span class="info"></span><button type="button" class="btn btn-mini clear2 pull-right">' + settings.filtertextclear + '</button></span><input placeholder="' + settings.filterplaceholder + '" class="filter" type="text"><div class="btn-group buttons"><button type="button" class="btn remove" title="Remove selected"><i class="fa fa-arrow-left"></i></button><button type="button" class="btn removeall" title="Remove all"><i class="fa fa-arrow-left"></i><i class="fa fa-arrow-left"></i></button></div><select multiple="multiple" data-duallistbox_generated="true"></select></div></div>').insertBefore($this); } else { container = $('<div class="row bootstrap-duallistbox-container"><div class="col-md-6 box1"><span class="info-container"><span class="info"></span><button type="button" class="btn btn-primary btn-xs clear1 pull-right">' + settings.filtertextclear + '</button></span><input placeholder="' + settings.filterplaceholder + '" class="filter" type="text"><div class="btn-group buttons"><button type="button" class="btn btn-primary moveall" title="Move all"><i class="fa fa-arrow-right"></i><i class="fa fa-arrow-right"></i></button><button type="button" class="btn btn-primary move" title="Move selected"><i class="fa fa-arrow-right"></i></button></div><select multiple="multiple" data-duallistbox_generated="true"></select></div><div class="col-md-6 box2"><span class="info-container"><span class="info"></span><button type="button" class="btn btn-primary btn-xs clear2 pull-right">' + settings.filtertextclear + '</button></span><input placeholder="' + settings.filterplaceholder + '" class="filter" type="text"><div class="btn-group buttons"><button type="button" class="btn btn-primary remove" title="Remove selected"><i class="fa fa-arrow-left"></i></button><button type="button" class="btn btn-primary removeall" title="Remove all"><i class="fa fa-arrow-left"></i><i class="fa fa-arrow-left"></i></button></div><select multiple="multiple" data-duallistbox_generated="true"></select></div></div>').insertBefore($this); } var elements = { originalselect: $this, box1: $('.box1', container), box2: $('.box2', container), filterinput1: $('.box1 .filter', container), filterinput2: $('.box2 .filter', container), filter1clear: $('.box1 .clear1', container), filter2clear: $('.box2 .clear2', container), info1: $('.box1 .info', container), info2: $('.box2 .info', container), select1: $('.box1 select', container), select2: $('.box2 select', container), movebutton: $('.box1 .move', container), removebutton: $('.box2 .remove', container), moveallbutton: $('.box1 .moveall', container), removeallbutton: $('.box2 .removeall', container), form: $($('.box1 .filter', container)[0].form) }, i = 0, selectedelements = 0, // Selections are invisible on android if the containing select is styled with CSS // http://code.google.com/p/android/issues/detail?id=16922 isbuggyandroid = /android/i.test(navigator.userAgent.toLowerCase()); init(); function init() { // We are forcing to move on select and disabling preserveselection on Android if (isbuggyandroid) { settings.moveonselect = true; settings.preserveselectiononmove = false; } if (settings.moveonselect) { container.addClass('moveonselect'); } var originalselectname = elements.originalselect.attr('name') || ''; if (settings.nonselectedlistlabel) { var nonselectedlistid = 'bootstrap-duallistbox-nonselected-list_' + originalselectname; elements.box1.prepend('<label for="' + nonselectedlistid + '">' + settings.nonselectedlistlabel + '</label>'); elements.select1.prop('id', nonselectedlistid); } if (settings.selectedlistlabel) { var selectedlistid = 'bootstrap-duallistbox-selected-list_' + originalselectname; elements.box2.prepend('<label for="' + selectedlistid + '">' + settings.selectedlistlabel + '</label>'); elements.select2.prop('id', selectedlistid); } if (!!settings.helperselectnamepostfix) { elements.select1.attr('name', originalselectname + settings.helperselectnamepostfix + '1'); elements.select2.attr('name', originalselectname + settings.helperselectnamepostfix + '2'); } var c = elements.originalselect.attr('class'); if (typeof c !== 'undefined' && c) { c = c.match(/\bspan[1-9][0-2]?/); if (!c) { c = elements.originalselect.attr('class'); c = c.match(/\bcol-md-[1-9][0-2]?/); } } if (!!c) { container.addClass(c.toString()); } var height = (elements.originalselect.height() < settings.selectorminimalheight) ? settings.selectorminimalheight : elements.originalselect.height(); elements.select1.height(height); elements.select2.height(height); elements.originalselect.addClass('hide'); updateselectionstates(); if (!settings.showfilterinputs) { elements.filterinput1.hide(); elements.filterinput2.hide(); } else { elements.filterinput1.val(settings.initialfilterfrom); elements.filterinput2.val(settings.initialfilterto); } bindevents(); refreshselects(); } function updateselectionstates() { elements.originalselect.find('option').each(function(index, item) { var $item = $(item); if (typeof($item.data('original-index')) === 'undefined') { $item.data('original-index', i++); } if (typeof($item.data('_selected')) === 'undefined') { $item.data('_selected', false); } }); } function refreshselects() { selectedelements = 0; elements.select1.empty(); elements.select2.empty(); elements.originalselect.find('option').each(function(index, item) { var $item = $(item); if ($item.prop('selected')) { selectedelements++; elements.select2.append($item.clone(true).prop('selected', $item.data('_selected'))); } else { elements.select1.append($item.clone(true).prop('selected', $item.data('_selected'))); } }); filter1(); filter2(); refreshinfo(); } function formatstring(s, args) { return s.replace(/\{(\d+)\}/g, function(match, number) { return typeof args[number] !== 'undefined' ? args[number] : match; }); } function refreshinfo() { if (!settings.infotext) { return; } var visible1 = elements.select1.find('option').length, visible2 = elements.select2.find('option').length, all1 = elements.originalselect.find('option').length - selectedelements, all2 = selectedelements, content = ''; if (all1 === 0) { content = settings.infotextempty; } else if (visible1 === all1) { content = formatstring(settings.infotext, [visible1, all1]); } else { content = formatstring(settings.infotextfiltered, [visible1, all1]); } elements.info1.html(content); elements.box1.toggleClass('filtered', !(visible1 === all1 || all1 === 0)); if (all2 === 0) { content = settings.infotextempty; } else if (visible2 === all2) { content = formatstring(settings.infotext, [visible2, all2]); } else { content = formatstring(settings.infotextfiltered, [visible2, all2]); } elements.info2.html(content); elements.box2.toggleClass('filtered', !(visible2 === all2 || all2 === 0)); } function bindevents() { elements.form.submit(function(e) { if (elements.filterinput1.is(":focus")) { e.preventDefault(); elements.filterinput1.focusout(); } else if (elements.filterinput2.is(":focus")) { e.preventDefault(); elements.filterinput2.focusout(); } }); elements.originalselect.on('bootstrapduallistbox.refresh', function(e, clearselections){ updateselectionstates(); if (!clearselections) { saveselections1(); saveselections2(); } else { clearselections12(); } refreshselects(); }); elements.filter1clear.on('click', function() { elements.filterinput1.val(''); refreshselects(); }); elements.filter2clear.on('click', function() { elements.filterinput2.val(''); refreshselects(); }); elements.movebutton.on('click', function() { move(); }); elements.moveallbutton.on('click', function() { moveall(); }); elements.removebutton.on('click', function() { remove(); }); elements.removeallbutton.on('click', function() { removeall(); }); elements.filterinput1.on('change keyup', function() { filter1(); }); elements.filterinput2.on('change keyup', function() { filter2(); }); if (settings.moveonselect) { settings.preserveselectiononmove = false; elements.select1.on('change', function() { move(); }); elements.select2.on('change', function() { remove(); }); } } function saveselections1() { elements.select1.find('option').each(function(index, item) { var $item = $(item); elements.originalselect.find('option').eq($item.data('original-index')).data('_selected', $item.prop('selected')); }); } function saveselections2() { elements.select2.find('option').each(function(index, item) { var $item = $(item); elements.originalselect.find('option').eq($item.data('original-index')).data('_selected', $item.prop('selected')); }); } function clearselections12() { elements.select1.find('option').each(function() { elements.originalselect.find('option').data('_selected', false); }); } function filter1() { saveselections1(); elements.select1.empty().scrollTop(0); var regex = new RegExp($.trim(elements.filterinput1.val()), "gi"); elements.originalselect.find('option').not(':selected').each(function(index, item) { var $item = $(item); var isFiltered = true; if (item.text.match(regex)) { isFiltered = false; elements.select1.append($item.clone(true).prop('selected', $item.data('_selected'))); } elements.originalselect.find('option').eq($item.data('original-index')).data('filtered1', isFiltered); }); refreshinfo(); } function filter2() { saveselections2(); elements.select2.empty().scrollTop(0); var regex = new RegExp($.trim(elements.filterinput2.val()), "gi"); elements.originalselect.find('option:selected').each(function(index, item) { var $item = $(item); var isFiltered = true; if (item.text.match(regex)) { isFiltered = false; elements.select2.append($item.clone(true).prop('selected', $item.data('_selected'))); } elements.originalselect.find('option').eq($item.data('original-index')).data('filtered2', isFiltered); }); refreshinfo(); } function sortoptions(select) { select.find('option').sort(function(a, b) { return ($(a).data('original-index') > $(b).data('original-index')) ? 1 : -1; }).appendTo(select); } function changeselectionstate(original_index, selected) { elements.originalselect.find('option').each(function(index, item) { var $item = $(item); if ($item.data('original-index') === original_index) { $item.prop('selected', selected); } }); } function move() { if (settings.preserveselectiononmove === 'all') { saveselections1(); saveselections2(); } else if (settings.preserveselectiononmove === 'moved') { saveselections1(); } elements.select1.find('option:selected').each(function(index, item) { var $item = $(item); if (!$item.data('filtered1')) { changeselectionstate($item.data('original-index'), true); } }); refreshselects(); sortoptions(elements.select2); } function remove() { if (settings.preserveselectiononmove === 'all') { saveselections1(); saveselections2(); } else if (settings.preserveselectiononmove === 'moved') { saveselections2(); } elements.select2.find('option:selected').each(function(index, item) { var $item = $(item); if (!$item.data('filtered2')) { changeselectionstate($item.data('original-index'), false); } }); refreshselects(); sortoptions(elements.select1); } function moveall() { if (settings.preserveselectiononmove === 'all') { saveselections1(); saveselections2(); } else if (settings.preserveselectiononmove === 'moved') { saveselections1(); } elements.originalselect.find('option').each(function(index, item) { var $item = $(item); if (!$item.data('filtered1')) { $item.prop('selected', true); } }); refreshselects(); } function removeall() { if (settings.preserveselectiononmove === 'all') { saveselections1(); saveselections2(); } else if (settings.preserveselectiononmove === 'moved') { saveselections2(); } elements.originalselect.find('option').each(function(index, item) { var $item = $(item); if (!$item.data('filtered2')) { $item.prop('selected', false); } }); refreshselects(); } }); }; })(jQuery);
JavaScript
/* * jQuery Iframe Transport Plugin 1.7 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint unparam: true, nomen: true */ /*global define, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; // Helper variable to create unique names for the transport iframes: var counter = 0; // The iframe transport accepts three additional options: // options.fileInput: a jQuery collection of file input fields // options.paramName: the parameter name for the file form data, // overrides the name property of the file input field(s), // can be a string or an array of strings. // options.formData: an array of objects with name and value properties, // equivalent to the return data of .serializeArray(), e.g.: // [{name: 'a', value: 1}, {name: 'b', value: 2}] $.ajaxTransport('iframe', function (options) { if (options.async) { var form, iframe, addParamChar; return { send: function (_, completeCallback) { form = $('<form style="display:none;"></form>'); form.attr('accept-charset', options.formAcceptCharset); addParamChar = /\?/.test(options.url) ? '&' : '?'; // XDomainRequest only supports GET and POST: if (options.type === 'DELETE') { options.url = options.url + addParamChar + '_method=DELETE'; options.type = 'POST'; } else if (options.type === 'PUT') { options.url = options.url + addParamChar + '_method=PUT'; options.type = 'POST'; } else if (options.type === 'PATCH') { options.url = options.url + addParamChar + '_method=PATCH'; options.type = 'POST'; } // javascript:false as initial iframe src // prevents warning popups on HTTPS in IE6. // IE versions below IE8 cannot set the name property of // elements that have already been added to the DOM, // so we set the name along with the iframe HTML markup: counter += 1; iframe = $( '<iframe src="javascript:false;" name="iframe-transport-' + counter + '"></iframe>' ).bind('load', function () { var fileInputClones, paramNames = $.isArray(options.paramName) ? options.paramName : [options.paramName]; iframe .unbind('load') .bind('load', function () { var response; // Wrap in a try/catch block to catch exceptions thrown // when trying to access cross-domain iframe contents: try { response = iframe.contents(); // Google Chrome and Firefox do not throw an // exception when calling iframe.contents() on // cross-domain requests, so we unify the response: if (!response.length || !response[0].firstChild) { throw new Error(); } } catch (e) { response = undefined; } // The complete callback returns the // iframe content document as response object: completeCallback( 200, 'success', {'iframe': response} ); // Fix for IE endless progress bar activity bug // (happens on form submits to iframe targets): $('<iframe src="javascript:false;"></iframe>') .appendTo(form); window.setTimeout(function () { // Removing the form in a setTimeout call // allows Chrome's developer tools to display // the response result form.remove(); }, 0); }); form .prop('target', iframe.prop('name')) .prop('action', options.url) .prop('method', options.type); if (options.formData) { $.each(options.formData, function (index, field) { $('<input type="hidden"/>') .prop('name', field.name) .val(field.value) .appendTo(form); }); } if (options.fileInput && options.fileInput.length && options.type === 'POST') { fileInputClones = options.fileInput.clone(); // Insert a clone for each file input field: options.fileInput.after(function (index) { return fileInputClones[index]; }); if (options.paramName) { options.fileInput.each(function (index) { $(this).prop( 'name', paramNames[index] || options.paramName ); }); } // Appending the file input fields to the hidden form // removes them from their original location: form .append(options.fileInput) .prop('enctype', 'multipart/form-data') // enctype must be set as encoding for IE: .prop('encoding', 'multipart/form-data'); } form.submit(); // Insert the file input fields at their original location // by replacing the clones with the originals: if (fileInputClones && fileInputClones.length) { options.fileInput.each(function (index, input) { var clone = $(fileInputClones[index]); $(input).prop('name', clone.prop('name')); clone.replaceWith(input); }); } }); form.append(iframe).appendTo(document.body); }, abort: function () { if (iframe) { // javascript:false as iframe src aborts the request // and prevents warning popups on HTTPS in IE6. // concat is used to avoid the "Script URL" JSLint error: iframe .unbind('load') .prop('src', 'javascript'.concat(':false;')); } if (form) { form.remove(); } } }; } }); // The iframe transport returns the iframe content document as response. // The following adds converters from iframe to text, json, html, xml // and script. // Please note that the Content-Type for JSON responses has to be text/plain // or text/html, if the browser doesn't include application/json in the // Accept header, else IE will show a download dialog. // The Content-Type for XML responses on the other hand has to be always // application/xml or text/xml, so IE properly parses the XML response. // See also // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation $.ajaxSetup({ converters: { 'iframe text': function (iframe) { return iframe && $(iframe[0].body).text(); }, 'iframe json': function (iframe) { return iframe && $.parseJSON($(iframe[0].body).text()); }, 'iframe html': function (iframe) { return iframe && $(iframe[0].body).html(); }, 'iframe xml': function (iframe) { var xmlDoc = iframe && iframe[0]; return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc : $.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) || $(xmlDoc.body).html()); }, 'iframe script': function (iframe) { return iframe && $.globalEval($(iframe[0].body).text()); } } }); }));
JavaScript
/* * jQuery File Upload jQuery UI Plugin 8.7.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true */ /*global define, window */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery', './jquery.fileupload-ui'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; $.widget('blueimp.fileupload', $.blueimp.fileupload, { options: { progress: function (e, data) { if (data.context) { data.context.find('.progress').progressbar( 'option', 'value', parseInt(data.loaded / data.total * 100, 10) ); } }, progressall: function (e, data) { var $this = $(this); $this.find('.fileupload-progress') .find('.progress').progressbar( 'option', 'value', parseInt(data.loaded / data.total * 100, 10) ).end() .find('.progress-extended').each(function () { $(this).html( ($this.data('blueimp-fileupload') || $this.data('fileupload')) ._renderExtendedProgress(data) ); }); } }, _renderUpload: function (func, files) { var node = this._super(func, files), showIconText = $(window).width() > 480; node.find('.progress').empty().progressbar(); node.find('.start').button({ icons: {primary: 'ui-fa fa-circle-arrow-e'}, text: showIconText }); node.find('.cancel').button({ icons: {primary: 'ui-fa fa-cancel'}, text: showIconText }); return node; }, _renderDownload: function (func, files) { var node = this._super(func, files), showIconText = $(window).width() > 480; node.find('.delete').button({ icons: {primary: 'ui-fa fa-trash'}, text: showIconText }); return node; }, _transition: function (node) { var deferred = $.Deferred(); if (node.hasClass('fade')) { node.fadeToggle( this.options.transitionDuration, this.options.transitionEasing, function () { deferred.resolveWith(node); } ); } else { deferred.resolveWith(node); } return deferred; }, _create: function () { this._super(); this.element .find('.fileupload-buttonbar') .find('.fileinput-button').each(function () { var input = $(this).find('input:file').detach(); $(this) .button({icons: {primary: 'ui-fa fa-plusthick'}}) .append(input); }) .end().find('.start') .button({icons: {primary: 'ui-fa fa-circle-arrow-e'}}) .end().find('.cancel') .button({icons: {primary: 'ui-fa fa-cancel'}}) .end().find('.delete') .button({icons: {primary: 'ui-fa fa-trash'}}) .end().find('.progress').progressbar(); }, _destroy: function () { this.element .find('.fileupload-buttonbar') .find('.fileinput-button').each(function () { var input = $(this).find('input:file').detach(); $(this) .button('destroy') .append(input); }) .end().find('.start') .button('destroy') .end().find('.cancel') .button('destroy') .end().find('.delete') .button('destroy') .end().find('.progress').progressbar('destroy'); this._super(); } }); }));
JavaScript
/* * jQuery postMessage Transport Plugin 1.1.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint unparam: true, nomen: true */ /*global define, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; var counter = 0, names = [ 'accepts', 'cache', 'contents', 'contentType', 'crossDomain', 'data', 'dataType', 'headers', 'ifModified', 'mimeType', 'password', 'processData', 'timeout', 'traditional', 'type', 'url', 'username' ], convert = function (p) { return p; }; $.ajaxSetup({ converters: { 'postmessage text': convert, 'postmessage json': convert, 'postmessage html': convert } }); $.ajaxTransport('postmessage', function (options) { if (options.postMessage && window.postMessage) { var iframe, loc = $('<a>').prop('href', options.postMessage)[0], target = loc.protocol + '//' + loc.host, xhrUpload = options.xhr().upload; return { send: function (_, completeCallback) { counter += 1; var message = { id: 'postmessage-transport-' + counter }, eventName = 'message.' + message.id; iframe = $( '<iframe style="display:none;" src="' + options.postMessage + '" name="' + message.id + '"></iframe>' ).bind('load', function () { $.each(names, function (i, name) { message[name] = options[name]; }); message.dataType = message.dataType.replace('postmessage ', ''); $(window).bind(eventName, function (e) { e = e.originalEvent; var data = e.data, ev; if (e.origin === target && data.id === message.id) { if (data.type === 'progress') { ev = document.createEvent('Event'); ev.initEvent(data.type, false, true); $.extend(ev, data); xhrUpload.dispatchEvent(ev); } else { completeCallback( data.status, data.statusText, {postmessage: data.result}, data.headers ); iframe.remove(); $(window).unbind(eventName); } } }); iframe[0].contentWindow.postMessage( message, target ); }).appendTo(document.body); }, abort: function () { if (iframe) { iframe.remove(); } } }; } }); }));
JavaScript
/* * jQuery XDomainRequest Transport Plugin 1.1.3 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on Julian Aubourg's ajaxHooks xdr.js: * https://github.com/jaubourg/ajaxHooks/ */ /*jslint unparam: true */ /*global define, window, XDomainRequest */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; if (window.XDomainRequest && !$.support.cors) { $.ajaxTransport(function (s) { if (s.crossDomain && s.async) { if (s.timeout) { s.xdrTimeout = s.timeout; delete s.timeout; } var xdr; return { send: function (headers, completeCallback) { var addParamChar = /\?/.test(s.url) ? '&' : '?'; function callback(status, statusText, responses, responseHeaders) { xdr.onload = xdr.onerror = xdr.ontimeout = $.noop; xdr = null; completeCallback(status, statusText, responses, responseHeaders); } xdr = new XDomainRequest(); // XDomainRequest only supports GET and POST: if (s.type === 'DELETE') { s.url = s.url + addParamChar + '_method=DELETE'; s.type = 'POST'; } else if (s.type === 'PUT') { s.url = s.url + addParamChar + '_method=PUT'; s.type = 'POST'; } else if (s.type === 'PATCH') { s.url = s.url + addParamChar + '_method=PATCH'; s.type = 'POST'; } xdr.open(s.type, s.url); xdr.onload = function () { callback( 200, 'OK', {text: xdr.responseText}, 'Content-Type: ' + xdr.contentType ); }; xdr.onerror = function () { callback(404, 'Not Found'); }; if (s.xdrTimeout) { xdr.ontimeout = function () { callback(0, 'timeout'); }; xdr.timeout = s.xdrTimeout; } xdr.send((s.hasContent && s.data) || null); }, abort: function () { if (xdr) { xdr.onerror = $.noop(); xdr.abort(); } } }; } }); } }));
JavaScript
#!/usr/bin/env node /* * jQuery File Upload Plugin Node.js Example 2.1.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2012, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, regexp: true, unparam: true, stupid: true */ /*global require, __dirname, unescape, console */ (function (port) { 'use strict'; var path = require('path'), fs = require('fs'), // Since Node 0.8, .existsSync() moved from path to fs: _existsSync = fs.existsSync || path.existsSync, formidable = require('formidable'), nodeStatic = require('node-static'), imageMagick = require('imagemagick'), options = { tmpDir: __dirname + '/tmp', publicDir: __dirname + '/public', uploadDir: __dirname + '/public/files', uploadUrl: '/files/', maxPostSize: 11000000000, // 11 GB minFileSize: 1, maxFileSize: 10000000000, // 10 GB acceptFileTypes: /.+/i, // Files not matched by this regular expression force a download dialog, // to prevent executing any scripts in the context of the service domain: inlineFileTypes: /\.(gif|jpe?g|png)$/i, imageTypes: /\.(gif|jpe?g|png)$/i, imageVersions: { 'thumbnail': { width: 80, height: 80 } }, accessControl: { allowOrigin: '*', allowMethods: 'OPTIONS, HEAD, GET, POST, PUT, DELETE', allowHeaders: 'Content-Type, Content-Range, Content-Disposition' }, /* Uncomment and edit this section to provide the service via HTTPS: ssl: { key: fs.readFileSync('/Applications/XAMPP/etc/ssl.key/server.key'), cert: fs.readFileSync('/Applications/XAMPP/etc/ssl.crt/server.crt') }, */ nodeStatic: { cache: 3600 // seconds to cache served files } }, utf8encode = function (str) { return unescape(encodeURIComponent(str)); }, fileServer = new nodeStatic.Server(options.publicDir, options.nodeStatic), nameCountRegexp = /(?:(?: \(([\d]+)\))?(\.[^.]+))?$/, nameCountFunc = function (s, index, ext) { return ' (' + ((parseInt(index, 10) || 0) + 1) + ')' + (ext || ''); }, FileInfo = function (file) { this.name = file.name; this.size = file.size; this.type = file.type; this.deleteType = 'DELETE'; }, UploadHandler = function (req, res, callback) { this.req = req; this.res = res; this.callback = callback; }, serve = function (req, res) { res.setHeader( 'Access-Control-Allow-Origin', options.accessControl.allowOrigin ); res.setHeader( 'Access-Control-Allow-Methods', options.accessControl.allowMethods ); res.setHeader( 'Access-Control-Allow-Headers', options.accessControl.allowHeaders ); var handleResult = function (result, redirect) { if (redirect) { res.writeHead(302, { 'Location': redirect.replace( /%s/, encodeURIComponent(JSON.stringify(result)) ) }); res.end(); } else { res.writeHead(200, { 'Content-Type': req.headers.accept .indexOf('application/json') !== -1 ? 'application/json' : 'text/plain' }); res.end(JSON.stringify(result)); } }, setNoCacheHeaders = function () { res.setHeader('Pragma', 'no-cache'); res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate'); res.setHeader('Content-Disposition', 'inline; filename="files.json"'); }, handler = new UploadHandler(req, res, handleResult); switch (req.method) { case 'OPTIONS': res.end(); break; case 'HEAD': case 'GET': if (req.url === '/') { setNoCacheHeaders(); if (req.method === 'GET') { handler.get(); } else { res.end(); } } else { fileServer.serve(req, res); } break; case 'POST': setNoCacheHeaders(); handler.post(); break; case 'DELETE': handler.destroy(); break; default: res.statusCode = 405; res.end(); } }; fileServer.respond = function (pathname, status, _headers, files, stat, req, res, finish) { // Prevent browsers from MIME-sniffing the content-type: _headers['X-Content-Type-Options'] = 'nosniff'; if (!options.inlineFileTypes.test(files[0])) { // Force a download dialog for unsafe file extensions: _headers['Content-Type'] = 'application/octet-stream'; _headers['Content-Disposition'] = 'attachment; filename="' + utf8encode(path.basename(files[0])) + '"'; } nodeStatic.Server.prototype.respond .call(this, pathname, status, _headers, files, stat, req, res, finish); }; FileInfo.prototype.validate = function () { if (options.minFileSize && options.minFileSize > this.size) { this.error = 'File is too small'; } else if (options.maxFileSize && options.maxFileSize < this.size) { this.error = 'File is too big'; } else if (!options.acceptFileTypes.test(this.name)) { this.error = 'Filetype not allowed'; } return !this.error; }; FileInfo.prototype.safeName = function () { // Prevent directory traversal and creating hidden system files: this.name = path.basename(this.name).replace(/^\.+/, ''); // Prevent overwriting existing files: while (_existsSync(options.uploadDir + '/' + this.name)) { this.name = this.name.replace(nameCountRegexp, nameCountFunc); } }; FileInfo.prototype.initUrls = function (req) { if (!this.error) { var that = this, baseUrl = (options.ssl ? 'https:' : 'http:') + '//' + req.headers.host + options.uploadUrl; this.url = this.deleteUrl = baseUrl + encodeURIComponent(this.name); Object.keys(options.imageVersions).forEach(function (version) { if (_existsSync( options.uploadDir + '/' + version + '/' + that.name )) { that[version + 'Url'] = baseUrl + version + '/' + encodeURIComponent(that.name); } }); } }; UploadHandler.prototype.get = function () { var handler = this, files = []; fs.readdir(options.uploadDir, function (err, list) { list.forEach(function (name) { var stats = fs.statSync(options.uploadDir + '/' + name), fileInfo; if (stats.isFile() && name[0] !== '.') { fileInfo = new FileInfo({ name: name, size: stats.size }); fileInfo.initUrls(handler.req); files.push(fileInfo); } }); handler.callback({files: files}); }); }; UploadHandler.prototype.post = function () { var handler = this, form = new formidable.IncomingForm(), tmpFiles = [], files = [], map = {}, counter = 1, redirect, finish = function () { counter -= 1; if (!counter) { files.forEach(function (fileInfo) { fileInfo.initUrls(handler.req); }); handler.callback({files: files}, redirect); } }; form.uploadDir = options.tmpDir; form.on('fileBegin', function (name, file) { tmpFiles.push(file.path); var fileInfo = new FileInfo(file, handler.req, true); fileInfo.safeName(); map[path.basename(file.path)] = fileInfo; files.push(fileInfo); }).on('field', function (name, value) { if (name === 'redirect') { redirect = value; } }).on('file', function (name, file) { var fileInfo = map[path.basename(file.path)]; fileInfo.size = file.size; if (!fileInfo.validate()) { fs.unlink(file.path); return; } fs.renameSync(file.path, options.uploadDir + '/' + fileInfo.name); if (options.imageTypes.test(fileInfo.name)) { Object.keys(options.imageVersions).forEach(function (version) { counter += 1; var opts = options.imageVersions[version]; imageMagick.resize({ width: opts.width, height: opts.height, srcPath: options.uploadDir + '/' + fileInfo.name, dstPath: options.uploadDir + '/' + version + '/' + fileInfo.name }, finish); }); } }).on('aborted', function () { tmpFiles.forEach(function (file) { fs.unlink(file); }); }).on('error', function (e) { console.log(e); }).on('progress', function (bytesReceived, bytesExpected) { if (bytesReceived > options.maxPostSize) { handler.req.connection.destroy(); } }).on('end', finish).parse(handler.req); }; UploadHandler.prototype.destroy = function () { var handler = this, fileName; if (handler.req.url.slice(0, options.uploadUrl.length) === options.uploadUrl) { fileName = path.basename(decodeURIComponent(handler.req.url)); if (fileName[0] !== '.') { fs.unlink(options.uploadDir + '/' + fileName, function (ex) { Object.keys(options.imageVersions).forEach(function (version) { fs.unlink(options.uploadDir + '/' + version + '/' + fileName); }); handler.callback({success: !ex}); }); return; } } handler.callback({success: false}); }; if (options.ssl) { require('https').createServer(options.ssl, serve).listen(port); } else { require('http').createServer(serve).listen(port); } }(8888));
JavaScript
/* =========================================================== * Bootstrap: fileinput.js v3.1.1 * http://jasny.github.com/bootstrap/javascript/#fileinput * =========================================================== * Copyright 2012-2014 Arnold Daniels * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ +function ($) { "use strict"; var isIE = window.navigator.appName == 'Microsoft Internet Explorer' // FILEUPLOAD PUBLIC CLASS DEFINITION // ================================= var Fileinput = function (element, options) { this.$element = $(element) this.$input = this.$element.find(':file') if (this.$input.length === 0) return this.name = this.$input.attr('name') || options.name this.$hidden = this.$element.find('input[type=hidden][name="' + this.name + '"]') if (this.$hidden.length === 0) { this.$hidden = $('<input type="hidden" />') this.$element.prepend(this.$hidden) } this.$preview = this.$element.find('.fileinput-preview') var height = this.$preview.css('height') if (this.$preview.css('display') != 'inline' && height != '0px' && height != 'none') this.$preview.css('line-height', height) this.original = { exists: this.$element.hasClass('fileinput-exists'), preview: this.$preview.html(), hiddenVal: this.$hidden.val() } this.listen() } Fileinput.prototype.listen = function() { this.$input.on('change.bs.fileinput', $.proxy(this.change, this)) $(this.$input[0].form).on('reset.bs.fileinput', $.proxy(this.reset, this)) this.$element.find('[data-trigger="fileinput"]').on('click.bs.fileinput', $.proxy(this.trigger, this)) this.$element.find('[data-dismiss="fileinput"]').on('click.bs.fileinput', $.proxy(this.clear, this)) }, Fileinput.prototype.change = function(e) { var files = e.target.files === undefined ? (e.target && e.target.value ? [{ name: e.target.value.replace(/^.+\\/, '')}] : []) : e.target.files e.stopPropagation() if (files.length === 0) { this.clear() return } this.$hidden.val('') this.$hidden.attr('name', '') this.$input.attr('name', this.name) var file = files[0] if (this.$preview.length > 0 && (typeof file.type !== "undefined" ? file.type.match(/^image\/(gif|png|jpeg)$/) : file.name.match(/\.(gif|png|jpe?g)$/i)) && typeof FileReader !== "undefined") { var reader = new FileReader() var preview = this.$preview var element = this.$element reader.onload = function(re) { var $img = $('<img>') $img[0].src = re.target.result files[0].result = re.target.result element.find('.fileinput-filename').text(file.name) // if parent has max-height, using `(max-)height: 100%` on child doesn't take padding and border into account if (preview.css('max-height') != 'none') $img.css('max-height', parseInt(preview.css('max-height'), 10) - parseInt(preview.css('padding-top'), 10) - parseInt(preview.css('padding-bottom'), 10) - parseInt(preview.css('border-top'), 10) - parseInt(preview.css('border-bottom'), 10)) preview.html($img) element.addClass('fileinput-exists').removeClass('fileinput-new') element.trigger('change.bs.fileinput', files) } reader.readAsDataURL(file) } else { this.$element.find('.fileinput-filename').text(file.name) this.$preview.text(file.name) this.$element.addClass('fileinput-exists').removeClass('fileinput-new') this.$element.trigger('change.bs.fileinput') } }, Fileinput.prototype.clear = function(e) { if (e) e.preventDefault() this.$hidden.val('') this.$hidden.attr('name', this.name) this.$input.attr('name', '') //ie8+ doesn't support changing the value of input with type=file so clone instead if (isIE) { var inputClone = this.$input.clone(true); this.$input.after(inputClone); this.$input.remove(); this.$input = inputClone; } else { this.$input.val('') } this.$preview.html('') this.$element.find('.fileinput-filename').text('') this.$element.addClass('fileinput-new').removeClass('fileinput-exists') if (e !== false) { this.$input.trigger('change') this.$element.trigger('clear.bs.fileinput') } }, Fileinput.prototype.reset = function() { this.clear(false) this.$hidden.val(this.original.hiddenVal) this.$preview.html(this.original.preview) this.$element.find('.fileinput-filename').text('') if (this.original.exists) this.$element.addClass('fileinput-exists').removeClass('fileinput-new') else this.$element.addClass('fileinput-new').removeClass('fileinput-exists') this.$element.trigger('reset.bs.fileinput') }, Fileinput.prototype.trigger = function(e) { this.$input.trigger('click') e.preventDefault() } // FILEUPLOAD PLUGIN DEFINITION // =========================== var old = $.fn.fileinput $.fn.fileinput = function (options) { return this.each(function () { var $this = $(this), data = $this.data('fileinput') if (!data) $this.data('fileinput', (data = new Fileinput(this, options))) if (typeof options == 'string') data[options]() }) } $.fn.fileinput.Constructor = Fileinput // FILEINPUT NO CONFLICT // ==================== $.fn.fileinput.noConflict = function () { $.fn.fileinput = old return this } // FILEUPLOAD DATA-API // ================== $(document).on('click.fileinput.data-api', '[data-provides="fileinput"]', function (e) { var $this = $(this) if ($this.data('fileinput')) return $this.fileinput($this.data()) var $target = $(e.target).closest('[data-dismiss="fileinput"],[data-trigger="fileinput"]'); if ($target.length > 0) { e.preventDefault() $target.trigger('click.bs.fileinput') } }) }(window.jQuery);
JavaScript
var select; var msContainer; beforeEach(function() { $('<select id="multi-select" multiple="multiple" name="test[]"></select>').appendTo('body'); for (var i=1; i <= 10; i++) { $('<option value="value'+i+'">text'+i+'</option>').appendTo($("#multi-select")); }; select = $("#multi-select"); }); afterEach(function () { $("#multi-select, #multi-select-optgroup, .ms-container").remove(); }); sanitize = function(value){ reg = new RegExp("\\W+", 'gi'); return value.replace(reg, '_'); }
JavaScript
describe("multiSelect", function() { describe('init', function(){ it ('should be chainable', function(){ select.multiSelect().addClass('chainable'); expect(select.hasClass('chainable')).toBeTruthy(); }); describe('without options', function(){ beforeEach(function() { select.multiSelect(); msContainer = select.next(); }); it('should hide the original select', function(){ expect(select.css('position')).toBe('absolute'); expect(select.css('left')).toBe('-9999px'); }); it('should create a container', function(){ expect(msContainer).toBe('div.ms-container'); }); it ('should create a selectable and a selection container', function(){ expect(msContainer).toContain('div.ms-selectable, div.ms-selection'); }); it ('should create a list for both selectable and selection container', function(){ expect(msContainer).toContain('div.ms-selectable ul.ms-list, div.ms-selection ul.ms-list'); }); it ('should populate the selectable list', function(){ expect($('.ms-selectable ul.ms-list li').length).toEqual(10); }); it ('should populate the selection list', function(){ expect($('.ms-selectable ul.ms-list li').length).toEqual(10); }); }); describe('with pre-selected options', function(){ var selectedValues = []; beforeEach(function() { var firstOption = select.children('option').first(); var lastOption = select.children('option').last(); firstOption.prop('selected', true); lastOption.prop('selected', true); selectedValues.push(firstOption.val(), lastOption.val()); select.multiSelect(); msContainer = select.next(); }); it ('should select the pre-selected options', function(){ $.each(selectedValues, function(index, value){ expect($('.ms-selectable ul.ms-list li#'+sanitize(value)+'-selectable')).toBe('.ms-selected'); }); expect($('.ms-selectable ul.ms-list li.ms-selected').length).toEqual(2); }); }); }); describe('optgroup', function(){ var optgroupMsContainer, optgroupSelect, optgroupLabels; beforeEach(function() { $('<select id="multi-select-optgroup" multiple="multiple" name="testy[]"></select>').appendTo('body'); for (var o=1; o <= 10; o++) { var optgroup = $('<optgroup label="opgroup'+o+'"></optgroup>') for (var i=1; i <= 10; i++) { var value = i + (o * 10); $('<option value="value'+value+'">text'+value+'</option>').appendTo(optgroup); }; optgroup.appendTo($("#multi-select-optgroup")); } optgroupSelect = $("#multi-select-optgroup"); }); describe('init', function(){ describe('with selectableOptgroup option set to false', function(){ beforeEach(function(){ optgroupSelect.multiSelect({ selectableOptgroup: false }); optgroupMsContainer = optgroupSelect.next(); optgroupLabels = optgroupMsContainer.find('.ms-selectable .ms-optgroup-label'); }); it ('sould display all optgroups', function(){ expect(optgroupLabels.length).toEqual(10); }); it ('should do nothing when clicking on optgroup', function(){ var clickedOptGroupLabel = optgroupLabels.first(); clickedOptGroupLabel.trigger('click'); expect(optgroupSelect.val()).toBeNull(); }); }); describe('with selectableOptgroup option set to true', function(){ beforeEach(function(){ optgroupSelect.multiSelect({ selectableOptgroup: true }); optgroupMsContainer = optgroupSelect.next(); optgroupLabels = optgroupMsContainer.find('.ms-selectable .ms-optgroup-label'); }); it ('should select all nested options when clicking on optgroup', function(){ var clickedOptGroupLabel = optgroupLabels.first(); clickedOptGroupLabel.trigger('click'); expect(optgroupSelect.val().length).toBe(10); }); }); }); }); describe('select', function(){ describe('multiple values (Array)', function(){ var values = ['value1', 'value2', 'value7']; beforeEach(function(){ $('#multi-select').multiSelect(); $('#multi-select').multiSelect('select', values); }); it('should select corresponding option', function(){ expect(select.val()).toEqual(values); }); }); describe('single value (String)', function(){ var value = 'value1'; beforeEach(function(){ $('#multi-select').multiSelect(); $('#multi-select').multiSelect('select', value); }); it('should select corresponding option', function(){ expect($.inArray(value, select.val()) > -1).toBeTruthy(); }); }); describe("on click", function(){ var clickedItem, value; beforeEach(function() { $('#multi-select').multiSelect(); clickedItem = $('.ms-selectable ul.ms-list li').first(); value = clickedItem.data('ms-value'); spyOnEvent(select, 'change'); spyOnEvent(select, 'focus'); clickedItem.trigger('click'); }); it('should hide selected item', function(){ expect(clickedItem).toBeHidden(); }); it('should add the .ms-selected class to the selected item', function(){ expect(clickedItem.hasClass('ms-selected')).toBeTruthy(); }); it('should select corresponding option', function(){ expect(select.find('option[value="'+value+'"]')).toBeSelected(); }); it('should show the associated selected item', function(){ expect($('#'+sanitize(value)+'-selection')).toBe(':visible'); }); it('should trigger the original select change event', function(){ expect('change').toHaveBeenTriggeredOn("#multi-select"); }); afterEach(function(){ select.multiSelect('deselect_all'); }); }); }); describe('deselect', function(){ describe('multiple values (Array)', function(){ var selectedValues = ['value1', 'value2', 'value7'], deselectValues = ['value1', 'value2']; beforeEach(function(){ $('#multi-select').multiSelect(); $('#multi-select').multiSelect('select', selectedValues); $('#multi-select').multiSelect('deselect', deselectValues); }); it('should select corresponding option', function(){ expect(select.val()).toEqual(['value7']); }); }); describe('single value (String)', function(){ var selectedValues = ['value1', 'value2', 'value7'], deselectValue = 'value2'; beforeEach(function(){ $('#multi-select').multiSelect(); $('#multi-select').multiSelect('select', selectedValues); $('#multi-select').multiSelect('deselect', deselectValue); }); it('should select corresponding option', function(){ expect($.inArray(deselectValue, select.val()) > -1).toBeFalsy(); }); }); describe("on click", function(){ var clickedItem, value; var correspondingSelectableItem; beforeEach(function() { $('#multi-select').find('option').first().prop('selected', true); $('#multi-select').multiSelect(); clickedItem = $('.ms-selection ul.ms-list li').first(); value = clickedItem.attr('id').replace('-selection', ''); correspondingSelectableItem = $('.ms-selection ul.ms-list li').first(); spyOnEvent(select, 'change'); spyOnEvent(select, 'focus'); clickedItem.trigger('click'); }); it ('should hide clicked item', function(){ expect(clickedItem).toBe(':hidden'); }); it('should show associated selectable item', function(){ expect($('#'+value+'-selectable')).toBe(':visible'); }); it('should remove the .ms-selected class to the corresponding selectable item', function(){ expect(correspondingSelectableItem.hasClass('ms-selected')).toBeFalsy(); }); it('should deselect corresponding option', function(){ expect(select.find('option[value="'+value+'"]')).not.toBeSelected(); }); it('should trigger the original select change event', function(){ expect('change').toHaveBeenTriggeredOn("#multi-select"); }); afterEach(function(){ select.multiSelect('deselect_all'); }); }); }); });
JavaScript
jasmine.HtmlReporterHelpers = {}; jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) { var el = document.createElement(type); for (var i = 2; i < arguments.length; i++) { var child = arguments[i]; if (typeof child === 'string') { el.appendChild(document.createTextNode(child)); } else { if (child) { el.appendChild(child); } } } for (var attr in attrs) { if (attr == "className") { el[attr] = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } } return el; }; jasmine.HtmlReporterHelpers.getSpecStatus = function(child) { var results = child.results(); var status = results.passed() ? 'passed' : 'failed'; if (results.skipped) { status = 'skipped'; } return status; }; jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) { var parentDiv = this.dom.summary; var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite'; var parent = child[parentSuite]; if (parent) { if (typeof this.views.suites[parent.id] == 'undefined') { this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views); } parentDiv = this.views.suites[parent.id].element; } parentDiv.appendChild(childElement); }; jasmine.HtmlReporterHelpers.addHelpers = function(ctor) { for(var fn in jasmine.HtmlReporterHelpers) { ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn]; } }; jasmine.HtmlReporter = function(_doc) { var self = this; var doc = _doc || window.document; var reporterView; var dom = {}; // Jasmine Reporter Public Interface self.logRunningSpecs = false; self.reportRunnerStarting = function(runner) { var specs = runner.specs() || []; if (specs.length == 0) { return; } createReporterDom(runner.env.versionString()); doc.body.appendChild(dom.reporter); reporterView = new jasmine.HtmlReporter.ReporterView(dom); reporterView.addSpecs(specs, self.specFilter); }; self.reportRunnerResults = function(runner) { reporterView && reporterView.complete(); }; self.reportSuiteResults = function(suite) { reporterView.suiteComplete(suite); }; self.reportSpecStarting = function(spec) { if (self.logRunningSpecs) { self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); } }; self.reportSpecResults = function(spec) { reporterView.specComplete(spec); }; self.log = function() { var console = jasmine.getGlobal().console; if (console && console.log) { if (console.log.apply) { console.log.apply(console, arguments); } else { console.log(arguments); // ie fix: console.log.apply doesn't exist on ie } } }; self.specFilter = function(spec) { if (!focusedSpecName()) { return true; } return spec.getFullName().indexOf(focusedSpecName()) === 0; }; return self; function focusedSpecName() { var specName; (function memoizeFocusedSpec() { if (specName) { return; } var paramMap = []; var params = doc.location.search.substring(1).split('&'); for (var i = 0; i < params.length; i++) { var p = params[i].split('='); paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); } specName = paramMap.spec; })(); return specName; } function createReporterDom(version) { dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' }, dom.banner = self.createDom('div', { className: 'banner' }, self.createDom('span', { className: 'title' }, "Jasmine "), self.createDom('span', { className: 'version' }, version)), dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}), dom.alert = self.createDom('div', {className: 'alert'}), dom.results = self.createDom('div', {className: 'results'}, dom.summary = self.createDom('div', { className: 'summary' }), dom.details = self.createDom('div', { id: 'details' })) ); } }; jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter);jasmine.HtmlReporter.ReporterView = function(dom) { this.startedAt = new Date(); this.runningSpecCount = 0; this.completeSpecCount = 0; this.passedCount = 0; this.failedCount = 0; this.skippedCount = 0; this.createResultsMenu = function() { this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'}, this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'), ' | ', this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing')); this.summaryMenuItem.onclick = function() { dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, ''); }; this.detailsMenuItem.onclick = function() { showDetails(); }; }; this.addSpecs = function(specs, specFilter) { this.totalSpecCount = specs.length; this.views = { specs: {}, suites: {} }; for (var i = 0; i < specs.length; i++) { var spec = specs[i]; this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views); if (specFilter(spec)) { this.runningSpecCount++; } } }; this.specComplete = function(spec) { this.completeSpecCount++; if (isUndefined(this.views.specs[spec.id])) { this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom); } var specView = this.views.specs[spec.id]; switch (specView.status()) { case 'passed': this.passedCount++; break; case 'failed': this.failedCount++; break; case 'skipped': this.skippedCount++; break; } specView.refresh(); this.refresh(); }; this.suiteComplete = function(suite) { var suiteView = this.views.suites[suite.id]; if (isUndefined(suiteView)) { return; } suiteView.refresh(); }; this.refresh = function() { if (isUndefined(this.resultsMenu)) { this.createResultsMenu(); } // currently running UI if (isUndefined(this.runningAlert)) { this.runningAlert = this.createDom('a', {href: "?", className: "runningAlert bar"}); dom.alert.appendChild(this.runningAlert); } this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount); // skipped specs UI if (isUndefined(this.skippedAlert)) { this.skippedAlert = this.createDom('a', {href: "?", className: "skippedAlert bar"}); } this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; if (this.skippedCount === 1 && isDefined(dom.alert)) { dom.alert.appendChild(this.skippedAlert); } // passing specs UI if (isUndefined(this.passedAlert)) { this.passedAlert = this.createDom('span', {href: "?", className: "passingAlert bar"}); } this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount); // failing specs UI if (isUndefined(this.failedAlert)) { this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"}); } this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount); if (this.failedCount === 1 && isDefined(dom.alert)) { dom.alert.appendChild(this.failedAlert); dom.alert.appendChild(this.resultsMenu); } // summary info this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount); this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing"; }; this.complete = function() { dom.alert.removeChild(this.runningAlert); this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; if (this.failedCount === 0) { dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount))); } else { showDetails(); } dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s")); }; return this; function showDetails() { if (dom.reporter.className.search(/showDetails/) === -1) { dom.reporter.className += " showDetails"; } } function isUndefined(obj) { return typeof obj === 'undefined'; } function isDefined(obj) { return !isUndefined(obj); } function specPluralizedFor(count) { var str = count + " spec"; if (count > 1) { str += "s" } return str; } }; jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView); jasmine.HtmlReporter.SpecView = function(spec, dom, views) { this.spec = spec; this.dom = dom; this.views = views; this.symbol = this.createDom('li', { className: 'pending' }); this.dom.symbolSummary.appendChild(this.symbol); this.summary = this.createDom('div', { className: 'specSummary' }, this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(this.spec.getFullName()), title: this.spec.getFullName() }, this.spec.description) ); this.detail = this.createDom('div', { className: 'specDetail' }, this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(this.spec.getFullName()), title: this.spec.getFullName() }, this.spec.getFullName()) ); }; jasmine.HtmlReporter.SpecView.prototype.status = function() { return this.getSpecStatus(this.spec); }; jasmine.HtmlReporter.SpecView.prototype.refresh = function() { this.symbol.className = this.status(); switch (this.status()) { case 'skipped': break; case 'passed': this.appendSummaryToSuiteDiv(); break; case 'failed': this.appendSummaryToSuiteDiv(); this.appendFailureDetail(); break; } }; jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() { this.summary.className += ' ' + this.status(); this.appendToSummary(this.spec, this.summary); }; jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() { this.detail.className += ' ' + this.status(); var resultItems = this.spec.results().getItems(); var messagesDiv = this.createDom('div', { className: 'messages' }); for (var i = 0; i < resultItems.length; i++) { var result = resultItems[i]; if (result.type == 'log') { messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); } else if (result.type == 'expect' && result.passed && !result.passed()) { messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); if (result.trace.stack) { messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); } } } if (messagesDiv.childNodes.length > 0) { this.detail.appendChild(messagesDiv); this.dom.details.appendChild(this.detail); } }; jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);jasmine.HtmlReporter.SuiteView = function(suite, dom, views) { this.suite = suite; this.dom = dom; this.views = views; this.element = this.createDom('div', { className: 'suite' }, this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(this.suite.getFullName()) }, this.suite.description) ); this.appendToSummary(this.suite, this.element); }; jasmine.HtmlReporter.SuiteView.prototype.status = function() { return this.getSpecStatus(this.suite); }; jasmine.HtmlReporter.SuiteView.prototype.refresh = function() { this.element.className += " " + this.status(); }; jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView); /* @deprecated Use jasmine.HtmlReporter instead */ jasmine.TrivialReporter = function(doc) { this.document = doc || document; this.suiteDivs = {}; this.logRunningSpecs = false; }; jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { var el = document.createElement(type); for (var i = 2; i < arguments.length; i++) { var child = arguments[i]; if (typeof child === 'string') { el.appendChild(document.createTextNode(child)); } else { if (child) { el.appendChild(child); } } } for (var attr in attrs) { if (attr == "className") { el[attr] = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } } return el; }; jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { var showPassed, showSkipped; this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' }, this.createDom('div', { className: 'banner' }, this.createDom('div', { className: 'logo' }, this.createDom('span', { className: 'title' }, "Jasmine"), this.createDom('span', { className: 'version' }, runner.env.versionString())), this.createDom('div', { className: 'options' }, "Show ", showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") ) ), this.runnerDiv = this.createDom('div', { className: 'runner running' }, this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), this.runnerMessageSpan = this.createDom('span', {}, "Running..."), this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) ); this.document.body.appendChild(this.outerDiv); var suites = runner.suites(); for (var i = 0; i < suites.length; i++) { var suite = suites[i]; var suiteDiv = this.createDom('div', { className: 'suite' }, this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); this.suiteDivs[suite.id] = suiteDiv; var parentDiv = this.outerDiv; if (suite.parentSuite) { parentDiv = this.suiteDivs[suite.parentSuite.id]; } parentDiv.appendChild(suiteDiv); } this.startedAt = new Date(); var self = this; showPassed.onclick = function(evt) { if (showPassed.checked) { self.outerDiv.className += ' show-passed'; } else { self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); } }; showSkipped.onclick = function(evt) { if (showSkipped.checked) { self.outerDiv.className += ' show-skipped'; } else { self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); } }; }; jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { var results = runner.results(); var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; this.runnerDiv.setAttribute("class", className); //do it twice for IE this.runnerDiv.setAttribute("className", className); var specs = runner.specs(); var specCount = 0; for (var i = 0; i < specs.length; i++) { if (this.specFilter(specs[i])) { specCount++; } } var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); }; jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { var results = suite.results(); var status = results.passed() ? 'passed' : 'failed'; if (results.totalCount === 0) { // todo: change this to check results.skipped status = 'skipped'; } this.suiteDivs[suite.id].className += " " + status; }; jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { if (this.logRunningSpecs) { this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); } }; jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { var results = spec.results(); var status = results.passed() ? 'passed' : 'failed'; if (results.skipped) { status = 'skipped'; } var specDiv = this.createDom('div', { className: 'spec ' + status }, this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(spec.getFullName()), title: spec.getFullName() }, spec.description)); var resultItems = results.getItems(); var messagesDiv = this.createDom('div', { className: 'messages' }); for (var i = 0; i < resultItems.length; i++) { var result = resultItems[i]; if (result.type == 'log') { messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); } else if (result.type == 'expect' && result.passed && !result.passed()) { messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); if (result.trace.stack) { messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); } } } if (messagesDiv.childNodes.length > 0) { specDiv.appendChild(messagesDiv); } this.suiteDivs[spec.suite.id].appendChild(specDiv); }; jasmine.TrivialReporter.prototype.log = function() { var console = jasmine.getGlobal().console; if (console && console.log) { if (console.log.apply) { console.log.apply(console, arguments); } else { console.log(arguments); // ie fix: console.log.apply doesn't exist on ie } } }; jasmine.TrivialReporter.prototype.getLocation = function() { return this.document.location; }; jasmine.TrivialReporter.prototype.specFilter = function(spec) { var paramMap = {}; var params = this.getLocation().search.substring(1).split('&'); for (var i = 0; i < params.length; i++) { var p = params[i].split('='); paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); } if (!paramMap.spec) { return true; } return spec.getFullName().indexOf(paramMap.spec) === 0; };
JavaScript
var isCommonJS = typeof window == "undefined"; /** * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework. * * @namespace */ var jasmine = {}; if (isCommonJS) exports.jasmine = jasmine; /** * @private */ jasmine.unimplementedMethod_ = function() { throw new Error("unimplemented method"); }; /** * Use <code>jasmine.undefined</code> instead of <code>undefined</code>, since <code>undefined</code> is just * a plain old variable and may be redefined by somebody else. * * @private */ jasmine.undefined = jasmine.___undefined___; /** * Show diagnostic messages in the console if set to true * */ jasmine.VERBOSE = false; /** * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed. * */ jasmine.DEFAULT_UPDATE_INTERVAL = 250; /** * Default timeout interval in milliseconds for waitsFor() blocks. */ jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; jasmine.getGlobal = function() { function getGlobal() { return this; } return getGlobal(); }; /** * Allows for bound functions to be compared. Internal use only. * * @ignore * @private * @param base {Object} bound 'this' for the function * @param name {Function} function to find */ jasmine.bindOriginal_ = function(base, name) { var original = base[name]; if (original.apply) { return function() { return original.apply(base, arguments); }; } else { // IE support return jasmine.getGlobal()[name]; } }; jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout'); jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout'); jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval'); jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval'); jasmine.MessageResult = function(values) { this.type = 'log'; this.values = values; this.trace = new Error(); // todo: test better }; jasmine.MessageResult.prototype.toString = function() { var text = ""; for (var i = 0; i < this.values.length; i++) { if (i > 0) text += " "; if (jasmine.isString_(this.values[i])) { text += this.values[i]; } else { text += jasmine.pp(this.values[i]); } } return text; }; jasmine.ExpectationResult = function(params) { this.type = 'expect'; this.matcherName = params.matcherName; this.passed_ = params.passed; this.expected = params.expected; this.actual = params.actual; this.message = this.passed_ ? 'Passed.' : params.message; var trace = (params.trace || new Error(this.message)); this.trace = this.passed_ ? '' : trace; }; jasmine.ExpectationResult.prototype.toString = function () { return this.message; }; jasmine.ExpectationResult.prototype.passed = function () { return this.passed_; }; /** * Getter for the Jasmine environment. Ensures one gets created */ jasmine.getEnv = function() { var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env(); return env; }; /** * @ignore * @private * @param value * @returns {Boolean} */ jasmine.isArray_ = function(value) { return jasmine.isA_("Array", value); }; /** * @ignore * @private * @param value * @returns {Boolean} */ jasmine.isString_ = function(value) { return jasmine.isA_("String", value); }; /** * @ignore * @private * @param value * @returns {Boolean} */ jasmine.isNumber_ = function(value) { return jasmine.isA_("Number", value); }; /** * @ignore * @private * @param {String} typeName * @param value * @returns {Boolean} */ jasmine.isA_ = function(typeName, value) { return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; }; /** * Pretty printer for expecations. Takes any object and turns it into a human-readable string. * * @param value {Object} an object to be outputted * @returns {String} */ jasmine.pp = function(value) { var stringPrettyPrinter = new jasmine.StringPrettyPrinter(); stringPrettyPrinter.format(value); return stringPrettyPrinter.string; }; /** * Returns true if the object is a DOM Node. * * @param {Object} obj object to check * @returns {Boolean} */ jasmine.isDomNode = function(obj) { return obj.nodeType > 0; }; /** * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter. * * @example * // don't care about which function is passed in, as long as it's a function * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function)); * * @param {Class} clazz * @returns matchable object of the type clazz */ jasmine.any = function(clazz) { return new jasmine.Matchers.Any(clazz); }; /** * Returns a matchable subset of a JSON object. For use in expectations when you don't care about all of the * attributes on the object. * * @example * // don't care about any other attributes than foo. * expect(mySpy).toHaveBeenCalledWith(jasmine.objectContaining({foo: "bar"}); * * @param sample {Object} sample * @returns matchable object for the sample */ jasmine.objectContaining = function (sample) { return new jasmine.Matchers.ObjectContaining(sample); }; /** * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks. * * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine * expectation syntax. Spies can be checked if they were called or not and what the calling params were. * * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs). * * Spies are torn down at the end of every spec. * * Note: Do <b>not</b> call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj. * * @example * // a stub * var myStub = jasmine.createSpy('myStub'); // can be used anywhere * * // spy example * var foo = { * not: function(bool) { return !bool; } * } * * // actual foo.not will not be called, execution stops * spyOn(foo, 'not'); // foo.not spied upon, execution will continue to implementation * spyOn(foo, 'not').andCallThrough(); * * // fake example * var foo = { * not: function(bool) { return !bool; } * } * * // foo.not(val) will return val * spyOn(foo, 'not').andCallFake(function(value) {return value;}); * * // mock example * foo.not(7 == 7); * expect(foo.not).toHaveBeenCalled(); * expect(foo.not).toHaveBeenCalledWith(true); * * @constructor * @see spyOn, jasmine.createSpy, jasmine.createSpyObj * @param {String} name */ jasmine.Spy = function(name) { /** * The name of the spy, if provided. */ this.identity = name || 'unknown'; /** * Is this Object a spy? */ this.isSpy = true; /** * The actual function this spy stubs. */ this.plan = function() { }; /** * Tracking of the most recent call to the spy. * @example * var mySpy = jasmine.createSpy('foo'); * mySpy(1, 2); * mySpy.mostRecentCall.args = [1, 2]; */ this.mostRecentCall = {}; /** * Holds arguments for each call to the spy, indexed by call count * @example * var mySpy = jasmine.createSpy('foo'); * mySpy(1, 2); * mySpy(7, 8); * mySpy.mostRecentCall.args = [7, 8]; * mySpy.argsForCall[0] = [1, 2]; * mySpy.argsForCall[1] = [7, 8]; */ this.argsForCall = []; this.calls = []; }; /** * Tells a spy to call through to the actual implemenatation. * * @example * var foo = { * bar: function() { // do some stuff } * } * * // defining a spy on an existing property: foo.bar * spyOn(foo, 'bar').andCallThrough(); */ jasmine.Spy.prototype.andCallThrough = function() { this.plan = this.originalValue; return this; }; /** * For setting the return value of a spy. * * @example * // defining a spy from scratch: foo() returns 'baz' * var foo = jasmine.createSpy('spy on foo').andReturn('baz'); * * // defining a spy on an existing property: foo.bar() returns 'baz' * spyOn(foo, 'bar').andReturn('baz'); * * @param {Object} value */ jasmine.Spy.prototype.andReturn = function(value) { this.plan = function() { return value; }; return this; }; /** * For throwing an exception when a spy is called. * * @example * // defining a spy from scratch: foo() throws an exception w/ message 'ouch' * var foo = jasmine.createSpy('spy on foo').andThrow('baz'); * * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch' * spyOn(foo, 'bar').andThrow('baz'); * * @param {String} exceptionMsg */ jasmine.Spy.prototype.andThrow = function(exceptionMsg) { this.plan = function() { throw exceptionMsg; }; return this; }; /** * Calls an alternate implementation when a spy is called. * * @example * var baz = function() { * // do some stuff, return something * } * // defining a spy from scratch: foo() calls the function baz * var foo = jasmine.createSpy('spy on foo').andCall(baz); * * // defining a spy on an existing property: foo.bar() calls an anonymnous function * spyOn(foo, 'bar').andCall(function() { return 'baz';} ); * * @param {Function} fakeFunc */ jasmine.Spy.prototype.andCallFake = function(fakeFunc) { this.plan = fakeFunc; return this; }; /** * Resets all of a spy's the tracking variables so that it can be used again. * * @example * spyOn(foo, 'bar'); * * foo.bar(); * * expect(foo.bar.callCount).toEqual(1); * * foo.bar.reset(); * * expect(foo.bar.callCount).toEqual(0); */ jasmine.Spy.prototype.reset = function() { this.wasCalled = false; this.callCount = 0; this.argsForCall = []; this.calls = []; this.mostRecentCall = {}; }; jasmine.createSpy = function(name) { var spyObj = function() { spyObj.wasCalled = true; spyObj.callCount++; var args = jasmine.util.argsToArray(arguments); spyObj.mostRecentCall.object = this; spyObj.mostRecentCall.args = args; spyObj.argsForCall.push(args); spyObj.calls.push({object: this, args: args}); return spyObj.plan.apply(this, arguments); }; var spy = new jasmine.Spy(name); for (var prop in spy) { spyObj[prop] = spy[prop]; } spyObj.reset(); return spyObj; }; /** * Determines whether an object is a spy. * * @param {jasmine.Spy|Object} putativeSpy * @returns {Boolean} */ jasmine.isSpy = function(putativeSpy) { return putativeSpy && putativeSpy.isSpy; }; /** * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something * large in one call. * * @param {String} baseName name of spy class * @param {Array} methodNames array of names of methods to make spies */ jasmine.createSpyObj = function(baseName, methodNames) { if (!jasmine.isArray_(methodNames) || methodNames.length === 0) { throw new Error('createSpyObj requires a non-empty array of method names to create spies for'); } var obj = {}; for (var i = 0; i < methodNames.length; i++) { obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]); } return obj; }; /** * All parameters are pretty-printed and concatenated together, then written to the current spec's output. * * Be careful not to leave calls to <code>jasmine.log</code> in production code. */ jasmine.log = function() { var spec = jasmine.getEnv().currentSpec; spec.log.apply(spec, arguments); }; /** * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy. * * @example * // spy example * var foo = { * not: function(bool) { return !bool; } * } * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops * * @see jasmine.createSpy * @param obj * @param methodName * @returns a Jasmine spy that can be chained with all spy methods */ var spyOn = function(obj, methodName) { return jasmine.getEnv().currentSpec.spyOn(obj, methodName); }; if (isCommonJS) exports.spyOn = spyOn; /** * Creates a Jasmine spec that will be added to the current suite. * * // TODO: pending tests * * @example * it('should be true', function() { * expect(true).toEqual(true); * }); * * @param {String} desc description of this specification * @param {Function} func defines the preconditions and expectations of the spec */ var it = function(desc, func) { return jasmine.getEnv().it(desc, func); }; if (isCommonJS) exports.it = it; /** * Creates a <em>disabled</em> Jasmine spec. * * A convenience method that allows existing specs to be disabled temporarily during development. * * @param {String} desc description of this specification * @param {Function} func defines the preconditions and expectations of the spec */ var xit = function(desc, func) { return jasmine.getEnv().xit(desc, func); }; if (isCommonJS) exports.xit = xit; /** * Starts a chain for a Jasmine expectation. * * It is passed an Object that is the actual value and should chain to one of the many * jasmine.Matchers functions. * * @param {Object} actual Actual value to test against and expected value */ var expect = function(actual) { return jasmine.getEnv().currentSpec.expect(actual); }; if (isCommonJS) exports.expect = expect; /** * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs. * * @param {Function} func Function that defines part of a jasmine spec. */ var runs = function(func) { jasmine.getEnv().currentSpec.runs(func); }; if (isCommonJS) exports.runs = runs; /** * Waits a fixed time period before moving to the next block. * * @deprecated Use waitsFor() instead * @param {Number} timeout milliseconds to wait */ var waits = function(timeout) { jasmine.getEnv().currentSpec.waits(timeout); }; if (isCommonJS) exports.waits = waits; /** * Waits for the latchFunction to return true before proceeding to the next block. * * @param {Function} latchFunction * @param {String} optional_timeoutMessage * @param {Number} optional_timeout */ var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments); }; if (isCommonJS) exports.waitsFor = waitsFor; /** * A function that is called before each spec in a suite. * * Used for spec setup, including validating assumptions. * * @param {Function} beforeEachFunction */ var beforeEach = function(beforeEachFunction) { jasmine.getEnv().beforeEach(beforeEachFunction); }; if (isCommonJS) exports.beforeEach = beforeEach; /** * A function that is called after each spec in a suite. * * Used for restoring any state that is hijacked during spec execution. * * @param {Function} afterEachFunction */ var afterEach = function(afterEachFunction) { jasmine.getEnv().afterEach(afterEachFunction); }; if (isCommonJS) exports.afterEach = afterEach; /** * Defines a suite of specifications. * * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization * of setup in some tests. * * @example * // TODO: a simple suite * * // TODO: a simple suite with a nested describe block * * @param {String} description A string, usually the class under test. * @param {Function} specDefinitions function that defines several specs. */ var describe = function(description, specDefinitions) { return jasmine.getEnv().describe(description, specDefinitions); }; if (isCommonJS) exports.describe = describe; /** * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development. * * @param {String} description A string, usually the class under test. * @param {Function} specDefinitions function that defines several specs. */ var xdescribe = function(description, specDefinitions) { return jasmine.getEnv().xdescribe(description, specDefinitions); }; if (isCommonJS) exports.xdescribe = xdescribe; // Provide the XMLHttpRequest class for IE 5.x-6.x: jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() { function tryIt(f) { try { return f(); } catch(e) { } return null; } var xhr = tryIt(function() { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }) || tryIt(function() { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }) || tryIt(function() { return new ActiveXObject("Msxml2.XMLHTTP"); }) || tryIt(function() { return new ActiveXObject("Microsoft.XMLHTTP"); }); if (!xhr) throw new Error("This browser does not support XMLHttpRequest."); return xhr; } : XMLHttpRequest; /** * @namespace */ jasmine.util = {}; /** * Declare that a child class inherit it's prototype from the parent class. * * @private * @param {Function} childClass * @param {Function} parentClass */ jasmine.util.inherit = function(childClass, parentClass) { /** * @private */ var subclass = function() { }; subclass.prototype = parentClass.prototype; childClass.prototype = new subclass(); }; jasmine.util.formatException = function(e) { var lineNumber; if (e.line) { lineNumber = e.line; } else if (e.lineNumber) { lineNumber = e.lineNumber; } var file; if (e.sourceURL) { file = e.sourceURL; } else if (e.fileName) { file = e.fileName; } var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString(); if (file && lineNumber) { message += ' in ' + file + ' (line ' + lineNumber + ')'; } return message; }; jasmine.util.htmlEscape = function(str) { if (!str) return str; return str.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); }; jasmine.util.argsToArray = function(args) { var arrayOfArgs = []; for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]); return arrayOfArgs; }; jasmine.util.extend = function(destination, source) { for (var property in source) destination[property] = source[property]; return destination; }; /** * Environment for Jasmine * * @constructor */ jasmine.Env = function() { this.currentSpec = null; this.currentSuite = null; this.currentRunner_ = new jasmine.Runner(this); this.reporter = new jasmine.MultiReporter(); this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL; this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL; this.lastUpdate = 0; this.specFilter = function() { return true; }; this.nextSpecId_ = 0; this.nextSuiteId_ = 0; this.equalityTesters_ = []; // wrap matchers this.matchersClass = function() { jasmine.Matchers.apply(this, arguments); }; jasmine.util.inherit(this.matchersClass, jasmine.Matchers); jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass); }; jasmine.Env.prototype.setTimeout = jasmine.setTimeout; jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout; jasmine.Env.prototype.setInterval = jasmine.setInterval; jasmine.Env.prototype.clearInterval = jasmine.clearInterval; /** * @returns an object containing jasmine version build info, if set. */ jasmine.Env.prototype.version = function () { if (jasmine.version_) { return jasmine.version_; } else { throw new Error('Version not set'); } }; /** * @returns string containing jasmine version build info, if set. */ jasmine.Env.prototype.versionString = function() { if (!jasmine.version_) { return "version unknown"; } var version = this.version(); var versionString = version.major + "." + version.minor + "." + version.build; if (version.release_candidate) { versionString += ".rc" + version.release_candidate; } versionString += " revision " + version.revision; return versionString; }; /** * @returns a sequential integer starting at 0 */ jasmine.Env.prototype.nextSpecId = function () { return this.nextSpecId_++; }; /** * @returns a sequential integer starting at 0 */ jasmine.Env.prototype.nextSuiteId = function () { return this.nextSuiteId_++; }; /** * Register a reporter to receive status updates from Jasmine. * @param {jasmine.Reporter} reporter An object which will receive status updates. */ jasmine.Env.prototype.addReporter = function(reporter) { this.reporter.addReporter(reporter); }; jasmine.Env.prototype.execute = function() { this.currentRunner_.execute(); }; jasmine.Env.prototype.describe = function(description, specDefinitions) { var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite); var parentSuite = this.currentSuite; if (parentSuite) { parentSuite.add(suite); } else { this.currentRunner_.add(suite); } this.currentSuite = suite; var declarationError = null; try { specDefinitions.call(suite); } catch(e) { declarationError = e; } if (declarationError) { this.it("encountered a declaration exception", function() { throw declarationError; }); } this.currentSuite = parentSuite; return suite; }; jasmine.Env.prototype.beforeEach = function(beforeEachFunction) { if (this.currentSuite) { this.currentSuite.beforeEach(beforeEachFunction); } else { this.currentRunner_.beforeEach(beforeEachFunction); } }; jasmine.Env.prototype.currentRunner = function () { return this.currentRunner_; }; jasmine.Env.prototype.afterEach = function(afterEachFunction) { if (this.currentSuite) { this.currentSuite.afterEach(afterEachFunction); } else { this.currentRunner_.afterEach(afterEachFunction); } }; jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) { return { execute: function() { } }; }; jasmine.Env.prototype.it = function(description, func) { var spec = new jasmine.Spec(this, this.currentSuite, description); this.currentSuite.add(spec); this.currentSpec = spec; if (func) { spec.runs(func); } return spec; }; jasmine.Env.prototype.xit = function(desc, func) { return { id: this.nextSpecId(), runs: function() { } }; }; jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) { if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) { return true; } a.__Jasmine_been_here_before__ = b; b.__Jasmine_been_here_before__ = a; var hasKey = function(obj, keyName) { return obj !== null && obj[keyName] !== jasmine.undefined; }; for (var property in b) { if (!hasKey(a, property) && hasKey(b, property)) { mismatchKeys.push("expected has key '" + property + "', but missing from actual."); } } for (property in a) { if (!hasKey(b, property) && hasKey(a, property)) { mismatchKeys.push("expected missing key '" + property + "', but present in actual."); } } for (property in b) { if (property == '__Jasmine_been_here_before__') continue; if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) { mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual."); } } if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) { mismatchValues.push("arrays were not the same length"); } delete a.__Jasmine_been_here_before__; delete b.__Jasmine_been_here_before__; return (mismatchKeys.length === 0 && mismatchValues.length === 0); }; jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) { mismatchKeys = mismatchKeys || []; mismatchValues = mismatchValues || []; for (var i = 0; i < this.equalityTesters_.length; i++) { var equalityTester = this.equalityTesters_[i]; var result = equalityTester(a, b, this, mismatchKeys, mismatchValues); if (result !== jasmine.undefined) return result; } if (a === b) return true; if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) { return (a == jasmine.undefined && b == jasmine.undefined); } if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) { return a === b; } if (a instanceof Date && b instanceof Date) { return a.getTime() == b.getTime(); } if (a.jasmineMatches) { return a.jasmineMatches(b); } if (b.jasmineMatches) { return b.jasmineMatches(a); } if (a instanceof jasmine.Matchers.ObjectContaining) { return a.matches(b); } if (b instanceof jasmine.Matchers.ObjectContaining) { return b.matches(a); } if (jasmine.isString_(a) && jasmine.isString_(b)) { return (a == b); } if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) { return (a == b); } if (typeof a === "object" && typeof b === "object") { return this.compareObjects_(a, b, mismatchKeys, mismatchValues); } //Straight check return (a === b); }; jasmine.Env.prototype.contains_ = function(haystack, needle) { if (jasmine.isArray_(haystack)) { for (var i = 0; i < haystack.length; i++) { if (this.equals_(haystack[i], needle)) return true; } return false; } return haystack.indexOf(needle) >= 0; }; jasmine.Env.prototype.addEqualityTester = function(equalityTester) { this.equalityTesters_.push(equalityTester); }; /** No-op base class for Jasmine reporters. * * @constructor */ jasmine.Reporter = function() { }; //noinspection JSUnusedLocalSymbols jasmine.Reporter.prototype.reportRunnerStarting = function(runner) { }; //noinspection JSUnusedLocalSymbols jasmine.Reporter.prototype.reportRunnerResults = function(runner) { }; //noinspection JSUnusedLocalSymbols jasmine.Reporter.prototype.reportSuiteResults = function(suite) { }; //noinspection JSUnusedLocalSymbols jasmine.Reporter.prototype.reportSpecStarting = function(spec) { }; //noinspection JSUnusedLocalSymbols jasmine.Reporter.prototype.reportSpecResults = function(spec) { }; //noinspection JSUnusedLocalSymbols jasmine.Reporter.prototype.log = function(str) { }; /** * Blocks are functions with executable code that make up a spec. * * @constructor * @param {jasmine.Env} env * @param {Function} func * @param {jasmine.Spec} spec */ jasmine.Block = function(env, func, spec) { this.env = env; this.func = func; this.spec = spec; }; jasmine.Block.prototype.execute = function(onComplete) { try { this.func.apply(this.spec); } catch (e) { this.spec.fail(e); } onComplete(); }; /** JavaScript API reporter. * * @constructor */ jasmine.JsApiReporter = function() { this.started = false; this.finished = false; this.suites_ = []; this.results_ = {}; }; jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) { this.started = true; var suites = runner.topLevelSuites(); for (var i = 0; i < suites.length; i++) { var suite = suites[i]; this.suites_.push(this.summarize_(suite)); } }; jasmine.JsApiReporter.prototype.suites = function() { return this.suites_; }; jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) { var isSuite = suiteOrSpec instanceof jasmine.Suite; var summary = { id: suiteOrSpec.id, name: suiteOrSpec.description, type: isSuite ? 'suite' : 'spec', children: [] }; if (isSuite) { var children = suiteOrSpec.children(); for (var i = 0; i < children.length; i++) { summary.children.push(this.summarize_(children[i])); } } return summary; }; jasmine.JsApiReporter.prototype.results = function() { return this.results_; }; jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) { return this.results_[specId]; }; //noinspection JSUnusedLocalSymbols jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) { this.finished = true; }; //noinspection JSUnusedLocalSymbols jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) { }; //noinspection JSUnusedLocalSymbols jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) { this.results_[spec.id] = { messages: spec.results().getItems(), result: spec.results().failedCount > 0 ? "failed" : "passed" }; }; //noinspection JSUnusedLocalSymbols jasmine.JsApiReporter.prototype.log = function(str) { }; jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){ var results = {}; for (var i = 0; i < specIds.length; i++) { var specId = specIds[i]; results[specId] = this.summarizeResult_(this.results_[specId]); } return results; }; jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ var summaryMessages = []; var messagesLength = result.messages.length; for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) { var resultMessage = result.messages[messageIndex]; summaryMessages.push({ text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined, passed: resultMessage.passed ? resultMessage.passed() : true, type: resultMessage.type, message: resultMessage.message, trace: { stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined } }); } return { result : result.result, messages : summaryMessages }; }; /** * @constructor * @param {jasmine.Env} env * @param actual * @param {jasmine.Spec} spec */ jasmine.Matchers = function(env, actual, spec, opt_isNot) { this.env = env; this.actual = actual; this.spec = spec; this.isNot = opt_isNot || false; this.reportWasCalled_ = false; }; // todo: @deprecated as of Jasmine 0.11, remove soon [xw] jasmine.Matchers.pp = function(str) { throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!"); }; // todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw] jasmine.Matchers.prototype.report = function(result, failing_message, details) { throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs"); }; jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) { for (var methodName in prototype) { if (methodName == 'report') continue; var orig = prototype[methodName]; matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig); } }; jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) { return function() { var matcherArgs = jasmine.util.argsToArray(arguments); var result = matcherFunction.apply(this, arguments); if (this.isNot) { result = !result; } if (this.reportWasCalled_) return result; var message; if (!result) { if (this.message) { message = this.message.apply(this, arguments); if (jasmine.isArray_(message)) { message = message[this.isNot ? 1 : 0]; } } else { var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate; if (matcherArgs.length > 0) { for (var i = 0; i < matcherArgs.length; i++) { if (i > 0) message += ","; message += " " + jasmine.pp(matcherArgs[i]); } } message += "."; } } var expectationResult = new jasmine.ExpectationResult({ matcherName: matcherName, passed: result, expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0], actual: this.actual, message: message }); this.spec.addMatcherResult(expectationResult); return jasmine.undefined; }; }; /** * toBe: compares the actual to the expected using === * @param expected */ jasmine.Matchers.prototype.toBe = function(expected) { return this.actual === expected; }; /** * toNotBe: compares the actual to the expected using !== * @param expected * @deprecated as of 1.0. Use not.toBe() instead. */ jasmine.Matchers.prototype.toNotBe = function(expected) { return this.actual !== expected; }; /** * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc. * * @param expected */ jasmine.Matchers.prototype.toEqual = function(expected) { return this.env.equals_(this.actual, expected); }; /** * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual * @param expected * @deprecated as of 1.0. Use not.toEqual() instead. */ jasmine.Matchers.prototype.toNotEqual = function(expected) { return !this.env.equals_(this.actual, expected); }; /** * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes * a pattern or a String. * * @param expected */ jasmine.Matchers.prototype.toMatch = function(expected) { return new RegExp(expected).test(this.actual); }; /** * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch * @param expected * @deprecated as of 1.0. Use not.toMatch() instead. */ jasmine.Matchers.prototype.toNotMatch = function(expected) { return !(new RegExp(expected).test(this.actual)); }; /** * Matcher that compares the actual to jasmine.undefined. */ jasmine.Matchers.prototype.toBeDefined = function() { return (this.actual !== jasmine.undefined); }; /** * Matcher that compares the actual to jasmine.undefined. */ jasmine.Matchers.prototype.toBeUndefined = function() { return (this.actual === jasmine.undefined); }; /** * Matcher that compares the actual to null. */ jasmine.Matchers.prototype.toBeNull = function() { return (this.actual === null); }; /** * Matcher that boolean not-nots the actual. */ jasmine.Matchers.prototype.toBeTruthy = function() { return !!this.actual; }; /** * Matcher that boolean nots the actual. */ jasmine.Matchers.prototype.toBeFalsy = function() { return !this.actual; }; /** * Matcher that checks to see if the actual, a Jasmine spy, was called. */ jasmine.Matchers.prototype.toHaveBeenCalled = function() { if (arguments.length > 0) { throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); } if (!jasmine.isSpy(this.actual)) { throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); } this.message = function() { return [ "Expected spy " + this.actual.identity + " to have been called.", "Expected spy " + this.actual.identity + " not to have been called." ]; }; return this.actual.wasCalled; }; /** @deprecated Use expect(xxx).toHaveBeenCalled() instead */ jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled; /** * Matcher that checks to see if the actual, a Jasmine spy, was not called. * * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead */ jasmine.Matchers.prototype.wasNotCalled = function() { if (arguments.length > 0) { throw new Error('wasNotCalled does not take arguments'); } if (!jasmine.isSpy(this.actual)) { throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); } this.message = function() { return [ "Expected spy " + this.actual.identity + " to not have been called.", "Expected spy " + this.actual.identity + " to have been called." ]; }; return !this.actual.wasCalled; }; /** * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters. * * @example * */ jasmine.Matchers.prototype.toHaveBeenCalledWith = function() { var expectedArgs = jasmine.util.argsToArray(arguments); if (!jasmine.isSpy(this.actual)) { throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); } this.message = function() { if (this.actual.callCount === 0) { // todo: what should the failure message for .not.toHaveBeenCalledWith() be? is this right? test better. [xw] return [ "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.", "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was." ]; } else { return [ "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall), "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall) ]; } }; return this.env.contains_(this.actual.argsForCall, expectedArgs); }; /** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */ jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith; /** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */ jasmine.Matchers.prototype.wasNotCalledWith = function() { var expectedArgs = jasmine.util.argsToArray(arguments); if (!jasmine.isSpy(this.actual)) { throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); } this.message = function() { return [ "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was", "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was" ]; }; return !this.env.contains_(this.actual.argsForCall, expectedArgs); }; /** * Matcher that checks that the expected item is an element in the actual Array. * * @param {Object} expected */ jasmine.Matchers.prototype.toContain = function(expected) { return this.env.contains_(this.actual, expected); }; /** * Matcher that checks that the expected item is NOT an element in the actual Array. * * @param {Object} expected * @deprecated as of 1.0. Use not.toContain() instead. */ jasmine.Matchers.prototype.toNotContain = function(expected) { return !this.env.contains_(this.actual, expected); }; jasmine.Matchers.prototype.toBeLessThan = function(expected) { return this.actual < expected; }; jasmine.Matchers.prototype.toBeGreaterThan = function(expected) { return this.actual > expected; }; /** * Matcher that checks that the expected item is equal to the actual item * up to a given level of decimal precision (default 2). * * @param {Number} expected * @param {Number} precision */ jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) { if (!(precision === 0)) { precision = precision || 2; } var multiplier = Math.pow(10, precision); var actual = Math.round(this.actual * multiplier); expected = Math.round(expected * multiplier); return expected == actual; }; /** * Matcher that checks that the expected exception was thrown by the actual. * * @param {String} expected */ jasmine.Matchers.prototype.toThrow = function(expected) { var result = false; var exception; if (typeof this.actual != 'function') { throw new Error('Actual is not a function'); } try { this.actual(); } catch (e) { exception = e; } if (exception) { result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)); } var not = this.isNot ? "not " : ""; this.message = function() { if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) { return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' '); } else { return "Expected function to throw an exception."; } }; return result; }; jasmine.Matchers.Any = function(expectedClass) { this.expectedClass = expectedClass; }; jasmine.Matchers.Any.prototype.jasmineMatches = function(other) { if (this.expectedClass == String) { return typeof other == 'string' || other instanceof String; } if (this.expectedClass == Number) { return typeof other == 'number' || other instanceof Number; } if (this.expectedClass == Function) { return typeof other == 'function' || other instanceof Function; } if (this.expectedClass == Object) { return typeof other == 'object'; } return other instanceof this.expectedClass; }; jasmine.Matchers.Any.prototype.jasmineToString = function() { return '<jasmine.any(' + this.expectedClass + ')>'; }; jasmine.Matchers.ObjectContaining = function (sample) { this.sample = sample; }; jasmine.Matchers.ObjectContaining.prototype.jasmineMatches = function(other, mismatchKeys, mismatchValues) { mismatchKeys = mismatchKeys || []; mismatchValues = mismatchValues || []; var env = jasmine.getEnv(); var hasKey = function(obj, keyName) { return obj != null && obj[keyName] !== jasmine.undefined; }; for (var property in this.sample) { if (!hasKey(other, property) && hasKey(this.sample, property)) { mismatchKeys.push("expected has key '" + property + "', but missing from actual."); } else if (!env.equals_(this.sample[property], other[property], mismatchKeys, mismatchValues)) { mismatchValues.push("'" + property + "' was '" + (other[property] ? jasmine.util.htmlEscape(other[property].toString()) : other[property]) + "' in expected, but was '" + (this.sample[property] ? jasmine.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in actual."); } } return (mismatchKeys.length === 0 && mismatchValues.length === 0); }; jasmine.Matchers.ObjectContaining.prototype.jasmineToString = function () { return "<jasmine.objectContaining(" + jasmine.pp(this.sample) + ")>"; }; // Mock setTimeout, clearTimeout // Contributed by Pivotal Computer Systems, www.pivotalsf.com jasmine.FakeTimer = function() { this.reset(); var self = this; self.setTimeout = function(funcToCall, millis) { self.timeoutsMade++; self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false); return self.timeoutsMade; }; self.setInterval = function(funcToCall, millis) { self.timeoutsMade++; self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true); return self.timeoutsMade; }; self.clearTimeout = function(timeoutKey) { self.scheduledFunctions[timeoutKey] = jasmine.undefined; }; self.clearInterval = function(timeoutKey) { self.scheduledFunctions[timeoutKey] = jasmine.undefined; }; }; jasmine.FakeTimer.prototype.reset = function() { this.timeoutsMade = 0; this.scheduledFunctions = {}; this.nowMillis = 0; }; jasmine.FakeTimer.prototype.tick = function(millis) { var oldMillis = this.nowMillis; var newMillis = oldMillis + millis; this.runFunctionsWithinRange(oldMillis, newMillis); this.nowMillis = newMillis; }; jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) { var scheduledFunc; var funcsToRun = []; for (var timeoutKey in this.scheduledFunctions) { scheduledFunc = this.scheduledFunctions[timeoutKey]; if (scheduledFunc != jasmine.undefined && scheduledFunc.runAtMillis >= oldMillis && scheduledFunc.runAtMillis <= nowMillis) { funcsToRun.push(scheduledFunc); this.scheduledFunctions[timeoutKey] = jasmine.undefined; } } if (funcsToRun.length > 0) { funcsToRun.sort(function(a, b) { return a.runAtMillis - b.runAtMillis; }); for (var i = 0; i < funcsToRun.length; ++i) { try { var funcToRun = funcsToRun[i]; this.nowMillis = funcToRun.runAtMillis; funcToRun.funcToCall(); if (funcToRun.recurring) { this.scheduleFunction(funcToRun.timeoutKey, funcToRun.funcToCall, funcToRun.millis, true); } } catch(e) { } } this.runFunctionsWithinRange(oldMillis, nowMillis); } }; jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) { this.scheduledFunctions[timeoutKey] = { runAtMillis: this.nowMillis + millis, funcToCall: funcToCall, recurring: recurring, timeoutKey: timeoutKey, millis: millis }; }; /** * @namespace */ jasmine.Clock = { defaultFakeTimer: new jasmine.FakeTimer(), reset: function() { jasmine.Clock.assertInstalled(); jasmine.Clock.defaultFakeTimer.reset(); }, tick: function(millis) { jasmine.Clock.assertInstalled(); jasmine.Clock.defaultFakeTimer.tick(millis); }, runFunctionsWithinRange: function(oldMillis, nowMillis) { jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis); }, scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) { jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring); }, useMock: function() { if (!jasmine.Clock.isInstalled()) { var spec = jasmine.getEnv().currentSpec; spec.after(jasmine.Clock.uninstallMock); jasmine.Clock.installMock(); } }, installMock: function() { jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer; }, uninstallMock: function() { jasmine.Clock.assertInstalled(); jasmine.Clock.installed = jasmine.Clock.real; }, real: { setTimeout: jasmine.getGlobal().setTimeout, clearTimeout: jasmine.getGlobal().clearTimeout, setInterval: jasmine.getGlobal().setInterval, clearInterval: jasmine.getGlobal().clearInterval }, assertInstalled: function() { if (!jasmine.Clock.isInstalled()) { throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()"); } }, isInstalled: function() { return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer; }, installed: null }; jasmine.Clock.installed = jasmine.Clock.real; //else for IE support jasmine.getGlobal().setTimeout = function(funcToCall, millis) { if (jasmine.Clock.installed.setTimeout.apply) { return jasmine.Clock.installed.setTimeout.apply(this, arguments); } else { return jasmine.Clock.installed.setTimeout(funcToCall, millis); } }; jasmine.getGlobal().setInterval = function(funcToCall, millis) { if (jasmine.Clock.installed.setInterval.apply) { return jasmine.Clock.installed.setInterval.apply(this, arguments); } else { return jasmine.Clock.installed.setInterval(funcToCall, millis); } }; jasmine.getGlobal().clearTimeout = function(timeoutKey) { if (jasmine.Clock.installed.clearTimeout.apply) { return jasmine.Clock.installed.clearTimeout.apply(this, arguments); } else { return jasmine.Clock.installed.clearTimeout(timeoutKey); } }; jasmine.getGlobal().clearInterval = function(timeoutKey) { if (jasmine.Clock.installed.clearTimeout.apply) { return jasmine.Clock.installed.clearInterval.apply(this, arguments); } else { return jasmine.Clock.installed.clearInterval(timeoutKey); } }; /** * @constructor */ jasmine.MultiReporter = function() { this.subReporters_ = []; }; jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter); jasmine.MultiReporter.prototype.addReporter = function(reporter) { this.subReporters_.push(reporter); }; (function() { var functionNames = [ "reportRunnerStarting", "reportRunnerResults", "reportSuiteResults", "reportSpecStarting", "reportSpecResults", "log" ]; for (var i = 0; i < functionNames.length; i++) { var functionName = functionNames[i]; jasmine.MultiReporter.prototype[functionName] = (function(functionName) { return function() { for (var j = 0; j < this.subReporters_.length; j++) { var subReporter = this.subReporters_[j]; if (subReporter[functionName]) { subReporter[functionName].apply(subReporter, arguments); } } }; })(functionName); } })(); /** * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults * * @constructor */ jasmine.NestedResults = function() { /** * The total count of results */ this.totalCount = 0; /** * Number of passed results */ this.passedCount = 0; /** * Number of failed results */ this.failedCount = 0; /** * Was this suite/spec skipped? */ this.skipped = false; /** * @ignore */ this.items_ = []; }; /** * Roll up the result counts. * * @param result */ jasmine.NestedResults.prototype.rollupCounts = function(result) { this.totalCount += result.totalCount; this.passedCount += result.passedCount; this.failedCount += result.failedCount; }; /** * Adds a log message. * @param values Array of message parts which will be concatenated later. */ jasmine.NestedResults.prototype.log = function(values) { this.items_.push(new jasmine.MessageResult(values)); }; /** * Getter for the results: message & results. */ jasmine.NestedResults.prototype.getItems = function() { return this.items_; }; /** * Adds a result, tracking counts (total, passed, & failed) * @param {jasmine.ExpectationResult|jasmine.NestedResults} result */ jasmine.NestedResults.prototype.addResult = function(result) { if (result.type != 'log') { if (result.items_) { this.rollupCounts(result); } else { this.totalCount++; if (result.passed()) { this.passedCount++; } else { this.failedCount++; } } } this.items_.push(result); }; /** * @returns {Boolean} True if <b>everything</b> below passed */ jasmine.NestedResults.prototype.passed = function() { return this.passedCount === this.totalCount; }; /** * Base class for pretty printing for expectation results. */ jasmine.PrettyPrinter = function() { this.ppNestLevel_ = 0; }; /** * Formats a value in a nice, human-readable string. * * @param value */ jasmine.PrettyPrinter.prototype.format = function(value) { if (this.ppNestLevel_ > 40) { throw new Error('jasmine.PrettyPrinter: format() nested too deeply!'); } this.ppNestLevel_++; try { if (value === jasmine.undefined) { this.emitScalar('undefined'); } else if (value === null) { this.emitScalar('null'); } else if (value === jasmine.getGlobal()) { this.emitScalar('<global>'); } else if (value.jasmineToString) { this.emitScalar(value.jasmineToString()); } else if (typeof value === 'string') { this.emitString(value); } else if (jasmine.isSpy(value)) { this.emitScalar("spy on " + value.identity); } else if (value instanceof RegExp) { this.emitScalar(value.toString()); } else if (typeof value === 'function') { this.emitScalar('Function'); } else if (typeof value.nodeType === 'number') { this.emitScalar('HTMLNode'); } else if (value instanceof Date) { this.emitScalar('Date(' + value + ')'); } else if (value.__Jasmine_been_here_before__) { this.emitScalar('<circular reference: ' + (jasmine.isArray_(value) ? 'Array' : 'Object') + '>'); } else if (jasmine.isArray_(value) || typeof value == 'object') { value.__Jasmine_been_here_before__ = true; if (jasmine.isArray_(value)) { this.emitArray(value); } else { this.emitObject(value); } delete value.__Jasmine_been_here_before__; } else { this.emitScalar(value.toString()); } } finally { this.ppNestLevel_--; } }; jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) { for (var property in obj) { if (property == '__Jasmine_been_here_before__') continue; fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined && obj.__lookupGetter__(property) !== null) : false); } }; jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_; jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_; jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_; jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_; jasmine.StringPrettyPrinter = function() { jasmine.PrettyPrinter.call(this); this.string = ''; }; jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter); jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) { this.append(value); }; jasmine.StringPrettyPrinter.prototype.emitString = function(value) { this.append("'" + value + "'"); }; jasmine.StringPrettyPrinter.prototype.emitArray = function(array) { this.append('[ '); for (var i = 0; i < array.length; i++) { if (i > 0) { this.append(', '); } this.format(array[i]); } this.append(' ]'); }; jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) { var self = this; this.append('{ '); var first = true; this.iterateObject(obj, function(property, isGetter) { if (first) { first = false; } else { self.append(', '); } self.append(property); self.append(' : '); if (isGetter) { self.append('<getter>'); } else { self.format(obj[property]); } }); this.append(' }'); }; jasmine.StringPrettyPrinter.prototype.append = function(value) { this.string += value; }; jasmine.Queue = function(env) { this.env = env; this.blocks = []; this.running = false; this.index = 0; this.offset = 0; this.abort = false; }; jasmine.Queue.prototype.addBefore = function(block) { this.blocks.unshift(block); }; jasmine.Queue.prototype.add = function(block) { this.blocks.push(block); }; jasmine.Queue.prototype.insertNext = function(block) { this.blocks.splice((this.index + this.offset + 1), 0, block); this.offset++; }; jasmine.Queue.prototype.start = function(onComplete) { this.running = true; this.onComplete = onComplete; this.next_(); }; jasmine.Queue.prototype.isRunning = function() { return this.running; }; jasmine.Queue.LOOP_DONT_RECURSE = true; jasmine.Queue.prototype.next_ = function() { var self = this; var goAgain = true; while (goAgain) { goAgain = false; if (self.index < self.blocks.length && !this.abort) { var calledSynchronously = true; var completedSynchronously = false; var onComplete = function () { if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) { completedSynchronously = true; return; } if (self.blocks[self.index].abort) { self.abort = true; } self.offset = 0; self.index++; var now = new Date().getTime(); if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) { self.env.lastUpdate = now; self.env.setTimeout(function() { self.next_(); }, 0); } else { if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) { goAgain = true; } else { self.next_(); } } }; self.blocks[self.index].execute(onComplete); calledSynchronously = false; if (completedSynchronously) { onComplete(); } } else { self.running = false; if (self.onComplete) { self.onComplete(); } } } }; jasmine.Queue.prototype.results = function() { var results = new jasmine.NestedResults(); for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].results) { results.addResult(this.blocks[i].results()); } } return results; }; /** * Runner * * @constructor * @param {jasmine.Env} env */ jasmine.Runner = function(env) { var self = this; self.env = env; self.queue = new jasmine.Queue(env); self.before_ = []; self.after_ = []; self.suites_ = []; }; jasmine.Runner.prototype.execute = function() { var self = this; if (self.env.reporter.reportRunnerStarting) { self.env.reporter.reportRunnerStarting(this); } self.queue.start(function () { self.finishCallback(); }); }; jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) { beforeEachFunction.typeName = 'beforeEach'; this.before_.splice(0,0,beforeEachFunction); }; jasmine.Runner.prototype.afterEach = function(afterEachFunction) { afterEachFunction.typeName = 'afterEach'; this.after_.splice(0,0,afterEachFunction); }; jasmine.Runner.prototype.finishCallback = function() { this.env.reporter.reportRunnerResults(this); }; jasmine.Runner.prototype.addSuite = function(suite) { this.suites_.push(suite); }; jasmine.Runner.prototype.add = function(block) { if (block instanceof jasmine.Suite) { this.addSuite(block); } this.queue.add(block); }; jasmine.Runner.prototype.specs = function () { var suites = this.suites(); var specs = []; for (var i = 0; i < suites.length; i++) { specs = specs.concat(suites[i].specs()); } return specs; }; jasmine.Runner.prototype.suites = function() { return this.suites_; }; jasmine.Runner.prototype.topLevelSuites = function() { var topLevelSuites = []; for (var i = 0; i < this.suites_.length; i++) { if (!this.suites_[i].parentSuite) { topLevelSuites.push(this.suites_[i]); } } return topLevelSuites; }; jasmine.Runner.prototype.results = function() { return this.queue.results(); }; /** * Internal representation of a Jasmine specification, or test. * * @constructor * @param {jasmine.Env} env * @param {jasmine.Suite} suite * @param {String} description */ jasmine.Spec = function(env, suite, description) { if (!env) { throw new Error('jasmine.Env() required'); } if (!suite) { throw new Error('jasmine.Suite() required'); } var spec = this; spec.id = env.nextSpecId ? env.nextSpecId() : null; spec.env = env; spec.suite = suite; spec.description = description; spec.queue = new jasmine.Queue(env); spec.afterCallbacks = []; spec.spies_ = []; spec.results_ = new jasmine.NestedResults(); spec.results_.description = description; spec.matchersClass = null; }; jasmine.Spec.prototype.getFullName = function() { return this.suite.getFullName() + ' ' + this.description + '.'; }; jasmine.Spec.prototype.results = function() { return this.results_; }; /** * All parameters are pretty-printed and concatenated together, then written to the spec's output. * * Be careful not to leave calls to <code>jasmine.log</code> in production code. */ jasmine.Spec.prototype.log = function() { return this.results_.log(arguments); }; jasmine.Spec.prototype.runs = function (func) { var block = new jasmine.Block(this.env, func, this); this.addToQueue(block); return this; }; jasmine.Spec.prototype.addToQueue = function (block) { if (this.queue.isRunning()) { this.queue.insertNext(block); } else { this.queue.add(block); } }; /** * @param {jasmine.ExpectationResult} result */ jasmine.Spec.prototype.addMatcherResult = function(result) { this.results_.addResult(result); }; jasmine.Spec.prototype.expect = function(actual) { var positive = new (this.getMatchersClass_())(this.env, actual, this); positive.not = new (this.getMatchersClass_())(this.env, actual, this, true); return positive; }; /** * Waits a fixed time period before moving to the next block. * * @deprecated Use waitsFor() instead * @param {Number} timeout milliseconds to wait */ jasmine.Spec.prototype.waits = function(timeout) { var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this); this.addToQueue(waitsFunc); return this; }; /** * Waits for the latchFunction to return true before proceeding to the next block. * * @param {Function} latchFunction * @param {String} optional_timeoutMessage * @param {Number} optional_timeout */ jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { var latchFunction_ = null; var optional_timeoutMessage_ = null; var optional_timeout_ = null; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; switch (typeof arg) { case 'function': latchFunction_ = arg; break; case 'string': optional_timeoutMessage_ = arg; break; case 'number': optional_timeout_ = arg; break; } } var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this); this.addToQueue(waitsForFunc); return this; }; jasmine.Spec.prototype.fail = function (e) { var expectationResult = new jasmine.ExpectationResult({ passed: false, message: e ? jasmine.util.formatException(e) : 'Exception', trace: { stack: e.stack } }); this.results_.addResult(expectationResult); }; jasmine.Spec.prototype.getMatchersClass_ = function() { return this.matchersClass || this.env.matchersClass; }; jasmine.Spec.prototype.addMatchers = function(matchersPrototype) { var parent = this.getMatchersClass_(); var newMatchersClass = function() { parent.apply(this, arguments); }; jasmine.util.inherit(newMatchersClass, parent); jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass); this.matchersClass = newMatchersClass; }; jasmine.Spec.prototype.finishCallback = function() { this.env.reporter.reportSpecResults(this); }; jasmine.Spec.prototype.finish = function(onComplete) { this.removeAllSpies(); this.finishCallback(); if (onComplete) { onComplete(); } }; jasmine.Spec.prototype.after = function(doAfter) { if (this.queue.isRunning()) { this.queue.add(new jasmine.Block(this.env, doAfter, this)); } else { this.afterCallbacks.unshift(doAfter); } }; jasmine.Spec.prototype.execute = function(onComplete) { var spec = this; if (!spec.env.specFilter(spec)) { spec.results_.skipped = true; spec.finish(onComplete); return; } this.env.reporter.reportSpecStarting(this); spec.env.currentSpec = spec; spec.addBeforesAndAftersToQueue(); spec.queue.start(function () { spec.finish(onComplete); }); }; jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() { var runner = this.env.currentRunner(); var i; for (var suite = this.suite; suite; suite = suite.parentSuite) { for (i = 0; i < suite.before_.length; i++) { this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this)); } } for (i = 0; i < runner.before_.length; i++) { this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this)); } for (i = 0; i < this.afterCallbacks.length; i++) { this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this)); } for (suite = this.suite; suite; suite = suite.parentSuite) { for (i = 0; i < suite.after_.length; i++) { this.queue.add(new jasmine.Block(this.env, suite.after_[i], this)); } } for (i = 0; i < runner.after_.length; i++) { this.queue.add(new jasmine.Block(this.env, runner.after_[i], this)); } }; jasmine.Spec.prototype.explodes = function() { throw 'explodes function should not have been called'; }; jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) { if (obj == jasmine.undefined) { throw "spyOn could not find an object to spy upon for " + methodName + "()"; } if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) { throw methodName + '() method does not exist'; } if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) { throw new Error(methodName + ' has already been spied upon'); } var spyObj = jasmine.createSpy(methodName); this.spies_.push(spyObj); spyObj.baseObj = obj; spyObj.methodName = methodName; spyObj.originalValue = obj[methodName]; obj[methodName] = spyObj; return spyObj; }; jasmine.Spec.prototype.removeAllSpies = function() { for (var i = 0; i < this.spies_.length; i++) { var spy = this.spies_[i]; spy.baseObj[spy.methodName] = spy.originalValue; } this.spies_ = []; }; /** * Internal representation of a Jasmine suite. * * @constructor * @param {jasmine.Env} env * @param {String} description * @param {Function} specDefinitions * @param {jasmine.Suite} parentSuite */ jasmine.Suite = function(env, description, specDefinitions, parentSuite) { var self = this; self.id = env.nextSuiteId ? env.nextSuiteId() : null; self.description = description; self.queue = new jasmine.Queue(env); self.parentSuite = parentSuite; self.env = env; self.before_ = []; self.after_ = []; self.children_ = []; self.suites_ = []; self.specs_ = []; }; jasmine.Suite.prototype.getFullName = function() { var fullName = this.description; for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { fullName = parentSuite.description + ' ' + fullName; } return fullName; }; jasmine.Suite.prototype.finish = function(onComplete) { this.env.reporter.reportSuiteResults(this); this.finished = true; if (typeof(onComplete) == 'function') { onComplete(); } }; jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) { beforeEachFunction.typeName = 'beforeEach'; this.before_.unshift(beforeEachFunction); }; jasmine.Suite.prototype.afterEach = function(afterEachFunction) { afterEachFunction.typeName = 'afterEach'; this.after_.unshift(afterEachFunction); }; jasmine.Suite.prototype.results = function() { return this.queue.results(); }; jasmine.Suite.prototype.add = function(suiteOrSpec) { this.children_.push(suiteOrSpec); if (suiteOrSpec instanceof jasmine.Suite) { this.suites_.push(suiteOrSpec); this.env.currentRunner().addSuite(suiteOrSpec); } else { this.specs_.push(suiteOrSpec); } this.queue.add(suiteOrSpec); }; jasmine.Suite.prototype.specs = function() { return this.specs_; }; jasmine.Suite.prototype.suites = function() { return this.suites_; }; jasmine.Suite.prototype.children = function() { return this.children_; }; jasmine.Suite.prototype.execute = function(onComplete) { var self = this; this.queue.start(function () { self.finish(onComplete); }); }; jasmine.WaitsBlock = function(env, timeout, spec) { this.timeout = timeout; jasmine.Block.call(this, env, null, spec); }; jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block); jasmine.WaitsBlock.prototype.execute = function (onComplete) { if (jasmine.VERBOSE) { this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...'); } this.env.setTimeout(function () { onComplete(); }, this.timeout); }; /** * A block which waits for some condition to become true, with timeout. * * @constructor * @extends jasmine.Block * @param {jasmine.Env} env The Jasmine environment. * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true. * @param {Function} latchFunction A function which returns true when the desired condition has been met. * @param {String} message The message to display if the desired condition hasn't been met within the given time period. * @param {jasmine.Spec} spec The Jasmine spec. */ jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) { this.timeout = timeout || env.defaultTimeoutInterval; this.latchFunction = latchFunction; this.message = message; this.totalTimeSpentWaitingForLatch = 0; jasmine.Block.call(this, env, null, spec); }; jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block); jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10; jasmine.WaitsForBlock.prototype.execute = function(onComplete) { if (jasmine.VERBOSE) { this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen')); } var latchFunctionResult; try { latchFunctionResult = this.latchFunction.apply(this.spec); } catch (e) { this.spec.fail(e); onComplete(); return; } if (latchFunctionResult) { onComplete(); } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) { var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen'); this.spec.fail({ name: 'timeout', message: message }); this.abort = true; onComplete(); } else { this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT; var self = this; this.env.setTimeout(function() { self.execute(onComplete); }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT); } }; jasmine.version_= { "major": 1, "minor": 2, "build": 0, "revision": 1337005947 };
JavaScript
var readFixtures = function() { return jasmine.getFixtures().proxyCallTo_('read', arguments) } var preloadFixtures = function() { jasmine.getFixtures().proxyCallTo_('preload', arguments) } var loadFixtures = function() { jasmine.getFixtures().proxyCallTo_('load', arguments) } var appendLoadFixtures = function() { jasmine.getFixtures().proxyCallTo_('appendLoad', arguments) } var setFixtures = function(html) { jasmine.getFixtures().proxyCallTo_('set', arguments) } var appendSetFixtures = function() { jasmine.getFixtures().proxyCallTo_('appendSet', arguments) } var sandbox = function(attributes) { return jasmine.getFixtures().sandbox(attributes) } var spyOnEvent = function(selector, eventName) { return jasmine.JQuery.events.spyOn($(selector).selector, eventName) } jasmine.getFixtures = function() { return jasmine.currentFixtures_ = jasmine.currentFixtures_ || new jasmine.Fixtures() } jasmine.Fixtures = function() { this.containerId = 'jasmine-fixtures' this.fixturesCache_ = {} this.fixturesPath = 'spec/javascripts/fixtures' } jasmine.Fixtures.prototype.set = function(html) { this.cleanUp() this.createContainer_(html) } jasmine.Fixtures.prototype.appendSet= function(html) { this.addToContainer_(html) } jasmine.Fixtures.prototype.preload = function() { this.read.apply(this, arguments) } jasmine.Fixtures.prototype.load = function() { this.cleanUp() this.createContainer_(this.read.apply(this, arguments)) } jasmine.Fixtures.prototype.appendLoad = function() { this.addToContainer_(this.read.apply(this, arguments)) } jasmine.Fixtures.prototype.read = function() { var htmlChunks = [] var fixtureUrls = arguments for(var urlCount = fixtureUrls.length, urlIndex = 0; urlIndex < urlCount; urlIndex++) { htmlChunks.push(this.getFixtureHtml_(fixtureUrls[urlIndex])) } return htmlChunks.join('') } jasmine.Fixtures.prototype.clearCache = function() { this.fixturesCache_ = {} } jasmine.Fixtures.prototype.cleanUp = function() { jQuery('#' + this.containerId).remove() } jasmine.Fixtures.prototype.sandbox = function(attributes) { var attributesToSet = attributes || {} return jQuery('<div id="sandbox" />').attr(attributesToSet) } jasmine.Fixtures.prototype.createContainer_ = function(html) { var container if(html instanceof jQuery) { container = jQuery('<div id="' + this.containerId + '" />') container.html(html) } else { container = '<div id="' + this.containerId + '">' + html + '</div>' } jQuery('body').append(container) } jasmine.Fixtures.prototype.addToContainer_ = function(html){ var container = jQuery('body').find('#'+this.containerId).append(html) if(!container.length){ this.createContainer_(html) } } jasmine.Fixtures.prototype.getFixtureHtml_ = function(url) { if (typeof this.fixturesCache_[url] === 'undefined') { this.loadFixtureIntoCache_(url) } return this.fixturesCache_[url] } jasmine.Fixtures.prototype.loadFixtureIntoCache_ = function(relativeUrl) { var url = this.makeFixtureUrl_(relativeUrl) var request = new XMLHttpRequest() request.open("GET", url + "?" + new Date().getTime(), false) request.send(null) this.fixturesCache_[relativeUrl] = request.responseText } jasmine.Fixtures.prototype.makeFixtureUrl_ = function(relativeUrl){ return this.fixturesPath.match('/$') ? this.fixturesPath + relativeUrl : this.fixturesPath + '/' + relativeUrl } jasmine.Fixtures.prototype.proxyCallTo_ = function(methodName, passedArguments) { return this[methodName].apply(this, passedArguments) } jasmine.JQuery = function() {} jasmine.JQuery.browserTagCaseIndependentHtml = function(html) { return jQuery('<div/>').append(html).html() } jasmine.JQuery.elementToString = function(element) { var domEl = $(element).get(0) if (domEl == undefined || domEl.cloneNode) return jQuery('<div />').append($(element).clone()).html() else return element.toString() } jasmine.JQuery.matchersClass = {}; !function(namespace) { var data = { spiedEvents: {}, handlers: [] } namespace.events = { spyOn: function(selector, eventName) { var handler = function(e) { data.spiedEvents[[selector, eventName]] = e } jQuery(selector).bind(eventName, handler) data.handlers.push(handler) return { selector: selector, eventName: eventName, handler: handler, reset: function(){ delete data.spiedEvents[[this.selector, this.eventName]]; } } }, wasTriggered: function(selector, eventName) { return !!(data.spiedEvents[[selector, eventName]]) }, wasPrevented: function(selector, eventName) { return data.spiedEvents[[selector, eventName]].isDefaultPrevented() }, cleanUp: function() { data.spiedEvents = {} data.handlers = [] } } }(jasmine.JQuery) !function(){ var jQueryMatchers = { toHaveClass: function(className) { return this.actual.hasClass(className) }, toHaveCss: function(css){ for (var prop in css){ if (this.actual.css(prop) !== css[prop]) return false } return true }, toBeVisible: function() { return this.actual.is(':visible') }, toBeHidden: function() { return this.actual.is(':hidden') }, toBeSelected: function() { return this.actual.is(':selected') }, toBeChecked: function() { return this.actual.is(':checked') }, toBeEmpty: function() { return this.actual.is(':empty') }, toExist: function() { return $(document).find(this.actual).length }, toHaveAttr: function(attributeName, expectedAttributeValue) { return hasProperty(this.actual.attr(attributeName), expectedAttributeValue) }, toHaveProp: function(propertyName, expectedPropertyValue) { return hasProperty(this.actual.prop(propertyName), expectedPropertyValue) }, toHaveId: function(id) { return this.actual.attr('id') == id }, toHaveHtml: function(html) { return this.actual.html() == jasmine.JQuery.browserTagCaseIndependentHtml(html) }, toContainHtml: function(html){ var actualHtml = this.actual.html() var expectedHtml = jasmine.JQuery.browserTagCaseIndependentHtml(html) return (actualHtml.indexOf(expectedHtml) >= 0) }, toHaveText: function(text) { var trimmedText = $.trim(this.actual.text()) if (text && jQuery.isFunction(text.test)) { return text.test(trimmedText) } else { return trimmedText == text } }, toHaveValue: function(value) { return this.actual.val() == value }, toHaveData: function(key, expectedValue) { return hasProperty(this.actual.data(key), expectedValue) }, toBe: function(selector) { return this.actual.is(selector) }, toContain: function(selector) { return this.actual.find(selector).length }, toBeDisabled: function(selector){ return this.actual.is(':disabled') }, toBeFocused: function(selector) { return this.actual.is(':focus') }, toHandle: function(event) { var events = this.actual.data('events') if(!events || !event || typeof event !== "string") { return false } var namespaces = event.split(".") var eventType = namespaces.shift() var sortedNamespaces = namespaces.slice(0).sort() var namespaceRegExp = new RegExp("(^|\\.)" + sortedNamespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") if(events[eventType] && namespaces.length) { for(var i = 0; i < events[eventType].length; i++) { var namespace = events[eventType][i].namespace if(namespaceRegExp.test(namespace)) { return true } } } else { return events[eventType] && events[eventType].length > 0 } }, // tests the existence of a specific event binding + handler toHandleWith: function(eventName, eventHandler) { var stack = this.actual.data("events")[eventName] for (var i = 0; i < stack.length; i++) { if (stack[i].handler == eventHandler) return true } return false } } var hasProperty = function(actualValue, expectedValue) { if (expectedValue === undefined) return actualValue !== undefined return actualValue == expectedValue } var bindMatcher = function(methodName) { var builtInMatcher = jasmine.Matchers.prototype[methodName] jasmine.JQuery.matchersClass[methodName] = function() { if (this.actual && (this.actual instanceof jQuery || jasmine.isDomNode(this.actual))) { this.actual = $(this.actual) var result = jQueryMatchers[methodName].apply(this, arguments) var element; if (this.actual.get && (element = this.actual.get()[0]) && !$.isWindow(element) && element.tagName !== "HTML") this.actual = jasmine.JQuery.elementToString(this.actual) return result } if (builtInMatcher) { return builtInMatcher.apply(this, arguments) } return false } } for(var methodName in jQueryMatchers) { bindMatcher(methodName) } }() beforeEach(function() { this.addMatchers(jasmine.JQuery.matchersClass) this.addMatchers({ toHaveBeenTriggeredOn: function(selector) { this.message = function() { return [ "Expected event " + this.actual + " to have been triggered on " + selector, "Expected event " + this.actual + " not to have been triggered on " + selector ] } return jasmine.JQuery.events.wasTriggered($(selector).selector, this.actual) } }) this.addMatchers({ toHaveBeenTriggered: function(){ var eventName = this.actual.eventName, selector = this.actual.selector; this.message = function() { return [ "Expected event " + eventName + " to have been triggered on " + selector, "Expected event " + eventName + " not to have been triggered on " + selector ] } return jasmine.JQuery.events.wasTriggered(selector, eventName) } }) this.addMatchers({ toHaveBeenPreventedOn: function(selector) { this.message = function() { return [ "Expected event " + this.actual + " to have been prevented on " + selector, "Expected event " + this.actual + " not to have been prevented on " + selector ] } return jasmine.JQuery.events.wasPrevented($(selector).selector, this.actual) } }) this.addMatchers({ toHaveBeenPrevented: function() { var eventName = this.actual.eventName, selector = this.actual.selector; this.message = function() { return [ "Expected event " + eventName + " to have been prevented on " + selector, "Expected event " + eventName + " not to have been prevented on " + selector ] } return jasmine.JQuery.events.wasPrevented(selector, eventName) } }) }) afterEach(function() { jasmine.getFixtures().cleanUp() jasmine.JQuery.events.cleanUp() })
JavaScript
/* * MultiSelect v0.9.8 * Copyright (c) 2012 Louis Cuny * * This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What The Fuck You Want * To Public License, Version 2, as published by Sam Hocevar. See * http://sam.zoy.org/wtfpl/COPYING for more details. */ !function ($) { "use strict"; /* MULTISELECT CLASS DEFINITION * ====================== */ var MultiSelect = function (element, options) { this.options = options; this.$element = $(element); this.$container = $('<div/>', { 'class': "ms-container" }); this.$selectableContainer = $('<div/>', { 'class': 'ms-selectable' }); this.$selectionContainer = $('<div/>', { 'class': 'ms-selection' }); this.$selectableUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' }); this.$selectionUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' }); this.scrollTo = 0; this.sanitizeRegexp = new RegExp("\\W+", 'gi'); this.elemsSelector = 'li:visible:not(.ms-optgroup-label,.ms-optgroup-container,.'+options.disabledClass+')'; }; MultiSelect.prototype = { constructor: MultiSelect, init: function(){ var that = this, ms = this.$element; if (ms.next('.ms-container').length === 0){ ms.css({ position: 'absolute', left: '-9999px' }); ms.attr('id', ms.attr('id') ? ms.attr('id') : Math.ceil(Math.random()*1000)+'multiselect'); this.$container.attr('id', 'ms-'+ms.attr('id')); ms.find('option').each(function(){ that.generateLisFromOption(this); }); this.$selectionUl.find('.ms-optgroup-label').hide(); if (that.options.selectableHeader){ that.$selectableContainer.append(that.options.selectableHeader); } that.$selectableContainer.append(that.$selectableUl); if (that.options.selectableFooter){ that.$selectableContainer.append(that.options.selectableFooter); } if (that.options.selectionHeader){ that.$selectionContainer.append(that.options.selectionHeader); } that.$selectionContainer.append(that.$selectionUl); if (that.options.selectionFooter){ that.$selectionContainer.append(that.options.selectionFooter); } that.$container.append(that.$selectableContainer); that.$container.append(that.$selectionContainer); ms.after(that.$container); that.activeMouse(that.$selectableUl); that.activeKeyboard(that.$selectableUl); var action = that.options.dblClick ? 'dblclick' : 'click'; that.$selectableUl.on(action, '.ms-elem-selectable', function(){ that.select($(this).data('ms-value')); }); that.$selectionUl.on(action, '.ms-elem-selection', function(){ that.deselect($(this).data('ms-value')); }); that.activeMouse(that.$selectionUl); that.activeKeyboard(that.$selectionUl); ms.on('focus', function(){ that.$selectableUl.focus(); }) } var selectedValues = ms.find('option:selected').map(function(){ return $(this).val(); }).get(); that.select(selectedValues, 'init'); if (typeof that.options.afterInit === 'function') { that.options.afterInit.call(this, this.$container); } }, 'generateLisFromOption' : function(option){ var that = this, ms = that.$element, attributes = "", $option = $(option); for (var cpt = 0; cpt < option.attributes.length; cpt++){ var attr = option.attributes[cpt]; if(attr.name !== 'value'){ attributes += attr.name+'="'+attr.value+'" '; } } var selectableLi = $('<li '+attributes+'><span>'+$option.text()+'</span></li>'), selectedLi = selectableLi.clone(), value = $option.val(), elementId = that.sanitize(value, that.sanitizeRegexp); selectableLi .data('ms-value', value) .addClass('ms-elem-selectable') .attr('id', elementId+'-selectable'); selectedLi .data('ms-value', value) .addClass('ms-elem-selection') .attr('id', elementId+'-selection') .hide(); if ($option.prop('disabled') || ms.prop('disabled')){ selectedLi.addClass(that.options.disabledClass); selectableLi.addClass(that.options.disabledClass); } var $optgroup = $option.parent('optgroup'); if ($optgroup.length > 0){ var optgroupLabel = $optgroup.attr('label'), optgroupId = that.sanitize(optgroupLabel, that.sanitizeRegexp), $selectableOptgroup = that.$selectableUl.find('#optgroup-selectable-'+optgroupId), $selectionOptgroup = that.$selectionUl.find('#optgroup-selection-'+optgroupId); if ($selectableOptgroup.length === 0){ var optgroupContainerTpl = '<li class="ms-optgroup-container"></li>', optgroupTpl = '<ul class="ms-optgroup"><li class="ms-optgroup-label"><span>'+optgroupLabel+'</span></li></ul>'; $selectableOptgroup = $(optgroupContainerTpl); $selectionOptgroup = $(optgroupContainerTpl); $selectableOptgroup.attr('id', 'optgroup-selectable-'+optgroupId); $selectionOptgroup.attr('id', 'optgroup-selection-'+optgroupId); $selectableOptgroup.append($(optgroupTpl)); $selectionOptgroup.append($(optgroupTpl)); if (that.options.selectableOptgroup){ $selectableOptgroup.find('.ms-optgroup-label').on('click', function(){ var values = $optgroup.children(':not(:selected)').map(function(){ return $(this).val() }).get(); that.select(values); }); $selectionOptgroup.find('.ms-optgroup-label').on('click', function(){ var values = $optgroup.children(':selected').map(function(){ return $(this).val() }).get(); that.deselect(values); }); } that.$selectableUl.append($selectableOptgroup); that.$selectionUl.append($selectionOptgroup); } $selectableOptgroup.children().append(selectableLi); $selectionOptgroup.children().append(selectedLi); } else { that.$selectableUl.append(selectableLi); that.$selectionUl.append(selectedLi); } }, 'activeKeyboard' : function($list){ var that = this; $list.on('focus', function(){ $(this).addClass('ms-focus'); }) .on('blur', function(){ $(this).removeClass('ms-focus'); }) .on('keydown', function(e){ switch (e.which) { case 40: case 38: e.preventDefault(); e.stopPropagation(); that.moveHighlight($(this), (e.which === 38) ? -1 : 1); return; case 32: e.preventDefault(); e.stopPropagation(); that.selectHighlighted($list); return; case 37: case 39: e.preventDefault(); e.stopPropagation(); that.switchList($list); return; } }); }, 'moveHighlight': function($list, direction){ var $elems = $list.find(this.elemsSelector), $currElem = $elems.filter('.ms-hover'), $nextElem = null, elemHeight = $elems.first().outerHeight(), containerHeight = $list.height(), containerSelector = '#'+this.$container.prop('id'); // Deactive mouseenter event when move is active // It fixes a bug when mouse is over the list $elems.off('mouseenter'); $elems.removeClass('ms-hover'); if (direction === 1){ // DOWN $nextElem = $currElem.nextAll(this.elemsSelector).first(); if ($nextElem.length === 0){ var $optgroupUl = $currElem.parent(); if ($optgroupUl.hasClass('ms-optgroup')){ var $optgroupLi = $optgroupUl.parent(), $nextOptgroupLi = $optgroupLi.next(':visible'); if ($nextOptgroupLi.length > 0){ $nextElem = $nextOptgroupLi.find(this.elemsSelector).first(); } else { $nextElem = $elems.first(); } } else { $nextElem = $elems.first(); } } } else if (direction === -1){ // UP $nextElem = $currElem.prevAll(this.elemsSelector).first(); if ($nextElem.length === 0){ var $optgroupUl = $currElem.parent(); if ($optgroupUl.hasClass('ms-optgroup')){ var $optgroupLi = $optgroupUl.parent(), $prevOptgroupLi = $optgroupLi.prev(':visible'); if ($prevOptgroupLi.length > 0){ $nextElem = $prevOptgroupLi.find(this.elemsSelector).last(); } else { $nextElem = $elems.last(); } } else { $nextElem = $elems.last(); } } } if ($nextElem.length > 0){ $nextElem.addClass('ms-hover'); var scrollTo = $list.scrollTop() + $nextElem.position().top - containerHeight / 2 + elemHeight / 2; $list.scrollTop(scrollTo); } }, 'selectHighlighted' : function($list){ var $elems = $list.find(this.elemsSelector), $highlightedElem = $elems.filter('.ms-hover').first(); if ($highlightedElem.length > 0){ if ($list.parent().hasClass('ms-selectable')){ this.select($highlightedElem.data('ms-value')); } else { this.deselect($highlightedElem.data('ms-value')); } $elems.removeClass('ms-hover'); } }, 'switchList' : function($list){ $list.blur(); if ($list.parent().hasClass('ms-selectable')){ this.$selectionUl.focus(); } else { this.$selectableUl.focus(); } }, 'activeMouse' : function($list){ var that = this; $list.on('mousemove', function(){ var elems = $list.find(that.elemsSelector); elems.on('mouseenter', function(){ elems.removeClass('ms-hover'); $(this).addClass('ms-hover'); }); }); }, 'refresh' : function() { this.destroy(); this.$element.multiSelect(this.options); }, 'destroy' : function(){ $("#ms-"+this.$element.attr("id")).remove(); this.$element.removeData('multiselect'); }, 'select' : function(value, method){ if (typeof value === 'string'){ value = [value]; } var that = this, ms = this.$element, msIds = $.map(value, function(val){ return(that.sanitize(val, that.sanitizeRegexp)); }), selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable').filter(':not(.'+that.options.disabledClass+')'), selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection').filter(':not(.'+that.options.disabledClass+')'), options = ms.find('option:not(:disabled)').filter(function(){ return($.inArray(this.value, value) > -1); }); if (selectables.length > 0){ selectables.addClass('ms-selected').hide(); selections.addClass('ms-selected').show(); options.prop('selected', true); var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container'); if (selectableOptgroups.length > 0){ selectableOptgroups.each(function(){ var selectablesLi = $(this).find('.ms-elem-selectable'); if (selectablesLi.length === selectablesLi.filter('.ms-selected').length){ $(this).find('.ms-optgroup-label').hide(); } }); var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container'); selectionOptgroups.each(function(){ var selectionsLi = $(this).find('.ms-elem-selection'); if (selectionsLi.filter('.ms-selected').length > 0){ $(this).find('.ms-optgroup-label').show(); } }); } else { if (that.options.keepOrder){ var selectionLiLast = that.$selectionUl.find('.ms-selected'); if((selectionLiLast.length > 1) && (selectionLiLast.last().get(0) != selections.get(0))) { selections.insertAfter(selectionLiLast.last()); } } } if (method !== 'init'){ ms.trigger('change'); if (typeof that.options.afterSelect === 'function') { that.options.afterSelect.call(this, value); } } } }, 'deselect' : function(value){ if (typeof value === 'string'){ value = [value]; } var that = this, ms = this.$element, msIds = $.map(value, function(val){ return(that.sanitize(val, that.sanitizeRegexp)); }), selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'), selections = this.$selectionUl.find('#' + msIds.join('-selection, #')+'-selection').filter('.ms-selected'), options = ms.find('option').filter(function(){ return($.inArray(this.value, value) > -1); }); if (selections.length > 0){ selectables.removeClass('ms-selected').show(); selections.removeClass('ms-selected').hide(); options.prop('selected', false); var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container'); if (selectableOptgroups.length > 0){ selectableOptgroups.each(function(){ var selectablesLi = $(this).find('.ms-elem-selectable'); if (selectablesLi.filter(':not(.ms-selected)').length > 0){ $(this).find('.ms-optgroup-label').show(); } }); var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container'); selectionOptgroups.each(function(){ var selectionsLi = $(this).find('.ms-elem-selection'); if (selectionsLi.filter('.ms-selected').length === 0){ $(this).find('.ms-optgroup-label').hide(); } }); } ms.trigger('change'); if (typeof that.options.afterDeselect === 'function') { that.options.afterDeselect.call(this, value); } } }, 'select_all' : function(){ var ms = this.$element, values = ms.val(); ms.find('option:not(":disabled")').prop('selected', true); this.$selectableUl.find('.ms-elem-selectable').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').hide(); this.$selectionUl.find('.ms-optgroup-label').show(); this.$selectableUl.find('.ms-optgroup-label').hide(); this.$selectionUl.find('.ms-elem-selection').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').show(); this.$selectionUl.focus(); ms.trigger('change'); if (typeof this.options.afterSelect === 'function') { var selectedValues = $.grep(ms.val(), function(item){ return $.inArray(item, values) < 0; }); this.options.afterSelect.call(this, selectedValues); } }, 'deselect_all' : function(){ var ms = this.$element, values = ms.val(); ms.find('option').prop('selected', false); this.$selectableUl.find('.ms-elem-selectable').removeClass('ms-selected').show(); this.$selectionUl.find('.ms-optgroup-label').hide(); this.$selectableUl.find('.ms-optgroup-label').show(); this.$selectionUl.find('.ms-elem-selection').removeClass('ms-selected').hide(); this.$selectableUl.focus(); ms.trigger('change'); if (typeof this.options.afterDeselect === 'function') { this.options.afterDeselect.call(this, values); } }, sanitize: function(value, reg){ return(value.replace(reg, '_')); } }; /* MULTISELECT PLUGIN DEFINITION * ======================= */ $.fn.multiSelect = function () { var option = arguments[0], args = arguments; return this.each(function () { var $this = $(this), data = $this.data('multiselect'), options = $.extend({}, $.fn.multiSelect.defaults, $this.data(), typeof option === 'object' && option); if (!data){ $this.data('multiselect', (data = new MultiSelect(this, options))); } if (typeof option === 'string'){ data[option](args[1]); } else { data.init(); } }); }; $.fn.multiSelect.defaults = { selectableOptgroup: false, disabledClass : 'disabled', dblClick : false, keepOrder: false }; $.fn.multiSelect.Constructor = MultiSelect; }(window.jQuery);
JavaScript
/** * Select2 Brazilian Portuguese translation */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Nenhum resultado encontrado"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Informe " + n + " caractere" + (n == 1? "" : "s"); }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Apague " + n + " caractere" + (n == 1? "" : "s"); }, formatSelectionTooBig: function (limit) { return "Só é possível selecionar " + limit + " elemento" + (limit == 1 ? "" : "s"); }, formatLoadMore: function (pageNumber) { return "Carregando mais resultados..."; }, formatSearching: function () { return "Buscando..."; } }); })(jQuery);
JavaScript
/* Copyright 2012 Igor Vaynberg Version: 3.4.2 Timestamp: Mon Aug 12 15:04:12 PDT 2013 This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU General Public License version 2 (the "GPL License"). You may choose either license to govern your use of this software only upon the condition that you accept all of the terms of either the Apache License or the GPL License. You may obtain a copy of the Apache License and the GPL License at: http://www.apache.org/licenses/LICENSE-2.0 http://www.gnu.org/licenses/gpl-2.0.html Unless required by applicable law or agreed to in writing, software distributed under the Apache License or the GPL Licesnse is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Apache License and the GPL License for the specific language governing permissions and limitations under the Apache License and the GPL License. */ (function ($) { if(typeof $.fn.each2 == "undefined") { $.extend($.fn, { /* * 4-10 times faster .each replacement * use it carefully, as it overrides jQuery context of element on each iteration */ each2 : function (c) { var j = $([0]), i = -1, l = this.length; while ( ++i < l && (j.context = j[0] = this[i]) && c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object ); return this; } }); } })(jQuery); (function ($, undefined) { "use strict"; /*global document, window, jQuery, console */ if (window.Select2 !== undefined) { return; } var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer, lastMousePosition={x:0,y:0}, $document, scrollBarDimensions, KEY = { TAB: 9, ENTER: 13, ESC: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, SHIFT: 16, CTRL: 17, ALT: 18, PAGE_UP: 33, PAGE_DOWN: 34, HOME: 36, END: 35, BACKSPACE: 8, DELETE: 46, isArrow: function (k) { k = k.which ? k.which : k; switch (k) { case KEY.LEFT: case KEY.RIGHT: case KEY.UP: case KEY.DOWN: return true; } return false; }, isControl: function (e) { var k = e.which; switch (k) { case KEY.SHIFT: case KEY.CTRL: case KEY.ALT: return true; } if (e.metaKey) return true; return false; }, isFunctionKey: function (k) { k = k.which ? k.which : k; return k >= 112 && k <= 123; } }, MEASURE_SCROLLBAR_TEMPLATE = "<div class='select2-measure-scrollbar'></div>", DIACRITICS = {"\u24B6":"A","\uFF21":"A","\u00C0":"A","\u00C1":"A","\u00C2":"A","\u1EA6":"A","\u1EA4":"A","\u1EAA":"A","\u1EA8":"A","\u00C3":"A","\u0100":"A","\u0102":"A","\u1EB0":"A","\u1EAE":"A","\u1EB4":"A","\u1EB2":"A","\u0226":"A","\u01E0":"A","\u00C4":"A","\u01DE":"A","\u1EA2":"A","\u00C5":"A","\u01FA":"A","\u01CD":"A","\u0200":"A","\u0202":"A","\u1EA0":"A","\u1EAC":"A","\u1EB6":"A","\u1E00":"A","\u0104":"A","\u023A":"A","\u2C6F":"A","\uA732":"AA","\u00C6":"AE","\u01FC":"AE","\u01E2":"AE","\uA734":"AO","\uA736":"AU","\uA738":"AV","\uA73A":"AV","\uA73C":"AY","\u24B7":"B","\uFF22":"B","\u1E02":"B","\u1E04":"B","\u1E06":"B","\u0243":"B","\u0182":"B","\u0181":"B","\u24B8":"C","\uFF23":"C","\u0106":"C","\u0108":"C","\u010A":"C","\u010C":"C","\u00C7":"C","\u1E08":"C","\u0187":"C","\u023B":"C","\uA73E":"C","\u24B9":"D","\uFF24":"D","\u1E0A":"D","\u010E":"D","\u1E0C":"D","\u1E10":"D","\u1E12":"D","\u1E0E":"D","\u0110":"D","\u018B":"D","\u018A":"D","\u0189":"D","\uA779":"D","\u01F1":"DZ","\u01C4":"DZ","\u01F2":"Dz","\u01C5":"Dz","\u24BA":"E","\uFF25":"E","\u00C8":"E","\u00C9":"E","\u00CA":"E","\u1EC0":"E","\u1EBE":"E","\u1EC4":"E","\u1EC2":"E","\u1EBC":"E","\u0112":"E","\u1E14":"E","\u1E16":"E","\u0114":"E","\u0116":"E","\u00CB":"E","\u1EBA":"E","\u011A":"E","\u0204":"E","\u0206":"E","\u1EB8":"E","\u1EC6":"E","\u0228":"E","\u1E1C":"E","\u0118":"E","\u1E18":"E","\u1E1A":"E","\u0190":"E","\u018E":"E","\u24BB":"F","\uFF26":"F","\u1E1E":"F","\u0191":"F","\uA77B":"F","\u24BC":"G","\uFF27":"G","\u01F4":"G","\u011C":"G","\u1E20":"G","\u011E":"G","\u0120":"G","\u01E6":"G","\u0122":"G","\u01E4":"G","\u0193":"G","\uA7A0":"G","\uA77D":"G","\uA77E":"G","\u24BD":"H","\uFF28":"H","\u0124":"H","\u1E22":"H","\u1E26":"H","\u021E":"H","\u1E24":"H","\u1E28":"H","\u1E2A":"H","\u0126":"H","\u2C67":"H","\u2C75":"H","\uA78D":"H","\u24BE":"I","\uFF29":"I","\u00CC":"I","\u00CD":"I","\u00CE":"I","\u0128":"I","\u012A":"I","\u012C":"I","\u0130":"I","\u00CF":"I","\u1E2E":"I","\u1EC8":"I","\u01CF":"I","\u0208":"I","\u020A":"I","\u1ECA":"I","\u012E":"I","\u1E2C":"I","\u0197":"I","\u24BF":"J","\uFF2A":"J","\u0134":"J","\u0248":"J","\u24C0":"K","\uFF2B":"K","\u1E30":"K","\u01E8":"K","\u1E32":"K","\u0136":"K","\u1E34":"K","\u0198":"K","\u2C69":"K","\uA740":"K","\uA742":"K","\uA744":"K","\uA7A2":"K","\u24C1":"L","\uFF2C":"L","\u013F":"L","\u0139":"L","\u013D":"L","\u1E36":"L","\u1E38":"L","\u013B":"L","\u1E3C":"L","\u1E3A":"L","\u0141":"L","\u023D":"L","\u2C62":"L","\u2C60":"L","\uA748":"L","\uA746":"L","\uA780":"L","\u01C7":"LJ","\u01C8":"Lj","\u24C2":"M","\uFF2D":"M","\u1E3E":"M","\u1E40":"M","\u1E42":"M","\u2C6E":"M","\u019C":"M","\u24C3":"N","\uFF2E":"N","\u01F8":"N","\u0143":"N","\u00D1":"N","\u1E44":"N","\u0147":"N","\u1E46":"N","\u0145":"N","\u1E4A":"N","\u1E48":"N","\u0220":"N","\u019D":"N","\uA790":"N","\uA7A4":"N","\u01CA":"NJ","\u01CB":"Nj","\u24C4":"O","\uFF2F":"O","\u00D2":"O","\u00D3":"O","\u00D4":"O","\u1ED2":"O","\u1ED0":"O","\u1ED6":"O","\u1ED4":"O","\u00D5":"O","\u1E4C":"O","\u022C":"O","\u1E4E":"O","\u014C":"O","\u1E50":"O","\u1E52":"O","\u014E":"O","\u022E":"O","\u0230":"O","\u00D6":"O","\u022A":"O","\u1ECE":"O","\u0150":"O","\u01D1":"O","\u020C":"O","\u020E":"O","\u01A0":"O","\u1EDC":"O","\u1EDA":"O","\u1EE0":"O","\u1EDE":"O","\u1EE2":"O","\u1ECC":"O","\u1ED8":"O","\u01EA":"O","\u01EC":"O","\u00D8":"O","\u01FE":"O","\u0186":"O","\u019F":"O","\uA74A":"O","\uA74C":"O","\u01A2":"OI","\uA74E":"OO","\u0222":"OU","\u24C5":"P","\uFF30":"P","\u1E54":"P","\u1E56":"P","\u01A4":"P","\u2C63":"P","\uA750":"P","\uA752":"P","\uA754":"P","\u24C6":"Q","\uFF31":"Q","\uA756":"Q","\uA758":"Q","\u024A":"Q","\u24C7":"R","\uFF32":"R","\u0154":"R","\u1E58":"R","\u0158":"R","\u0210":"R","\u0212":"R","\u1E5A":"R","\u1E5C":"R","\u0156":"R","\u1E5E":"R","\u024C":"R","\u2C64":"R","\uA75A":"R","\uA7A6":"R","\uA782":"R","\u24C8":"S","\uFF33":"S","\u1E9E":"S","\u015A":"S","\u1E64":"S","\u015C":"S","\u1E60":"S","\u0160":"S","\u1E66":"S","\u1E62":"S","\u1E68":"S","\u0218":"S","\u015E":"S","\u2C7E":"S","\uA7A8":"S","\uA784":"S","\u24C9":"T","\uFF34":"T","\u1E6A":"T","\u0164":"T","\u1E6C":"T","\u021A":"T","\u0162":"T","\u1E70":"T","\u1E6E":"T","\u0166":"T","\u01AC":"T","\u01AE":"T","\u023E":"T","\uA786":"T","\uA728":"TZ","\u24CA":"U","\uFF35":"U","\u00D9":"U","\u00DA":"U","\u00DB":"U","\u0168":"U","\u1E78":"U","\u016A":"U","\u1E7A":"U","\u016C":"U","\u00DC":"U","\u01DB":"U","\u01D7":"U","\u01D5":"U","\u01D9":"U","\u1EE6":"U","\u016E":"U","\u0170":"U","\u01D3":"U","\u0214":"U","\u0216":"U","\u01AF":"U","\u1EEA":"U","\u1EE8":"U","\u1EEE":"U","\u1EEC":"U","\u1EF0":"U","\u1EE4":"U","\u1E72":"U","\u0172":"U","\u1E76":"U","\u1E74":"U","\u0244":"U","\u24CB":"V","\uFF36":"V","\u1E7C":"V","\u1E7E":"V","\u01B2":"V","\uA75E":"V","\u0245":"V","\uA760":"VY","\u24CC":"W","\uFF37":"W","\u1E80":"W","\u1E82":"W","\u0174":"W","\u1E86":"W","\u1E84":"W","\u1E88":"W","\u2C72":"W","\u24CD":"X","\uFF38":"X","\u1E8A":"X","\u1E8C":"X","\u24CE":"Y","\uFF39":"Y","\u1EF2":"Y","\u00DD":"Y","\u0176":"Y","\u1EF8":"Y","\u0232":"Y","\u1E8E":"Y","\u0178":"Y","\u1EF6":"Y","\u1EF4":"Y","\u01B3":"Y","\u024E":"Y","\u1EFE":"Y","\u24CF":"Z","\uFF3A":"Z","\u0179":"Z","\u1E90":"Z","\u017B":"Z","\u017D":"Z","\u1E92":"Z","\u1E94":"Z","\u01B5":"Z","\u0224":"Z","\u2C7F":"Z","\u2C6B":"Z","\uA762":"Z","\u24D0":"a","\uFF41":"a","\u1E9A":"a","\u00E0":"a","\u00E1":"a","\u00E2":"a","\u1EA7":"a","\u1EA5":"a","\u1EAB":"a","\u1EA9":"a","\u00E3":"a","\u0101":"a","\u0103":"a","\u1EB1":"a","\u1EAF":"a","\u1EB5":"a","\u1EB3":"a","\u0227":"a","\u01E1":"a","\u00E4":"a","\u01DF":"a","\u1EA3":"a","\u00E5":"a","\u01FB":"a","\u01CE":"a","\u0201":"a","\u0203":"a","\u1EA1":"a","\u1EAD":"a","\u1EB7":"a","\u1E01":"a","\u0105":"a","\u2C65":"a","\u0250":"a","\uA733":"aa","\u00E6":"ae","\u01FD":"ae","\u01E3":"ae","\uA735":"ao","\uA737":"au","\uA739":"av","\uA73B":"av","\uA73D":"ay","\u24D1":"b","\uFF42":"b","\u1E03":"b","\u1E05":"b","\u1E07":"b","\u0180":"b","\u0183":"b","\u0253":"b","\u24D2":"c","\uFF43":"c","\u0107":"c","\u0109":"c","\u010B":"c","\u010D":"c","\u00E7":"c","\u1E09":"c","\u0188":"c","\u023C":"c","\uA73F":"c","\u2184":"c","\u24D3":"d","\uFF44":"d","\u1E0B":"d","\u010F":"d","\u1E0D":"d","\u1E11":"d","\u1E13":"d","\u1E0F":"d","\u0111":"d","\u018C":"d","\u0256":"d","\u0257":"d","\uA77A":"d","\u01F3":"dz","\u01C6":"dz","\u24D4":"e","\uFF45":"e","\u00E8":"e","\u00E9":"e","\u00EA":"e","\u1EC1":"e","\u1EBF":"e","\u1EC5":"e","\u1EC3":"e","\u1EBD":"e","\u0113":"e","\u1E15":"e","\u1E17":"e","\u0115":"e","\u0117":"e","\u00EB":"e","\u1EBB":"e","\u011B":"e","\u0205":"e","\u0207":"e","\u1EB9":"e","\u1EC7":"e","\u0229":"e","\u1E1D":"e","\u0119":"e","\u1E19":"e","\u1E1B":"e","\u0247":"e","\u025B":"e","\u01DD":"e","\u24D5":"f","\uFF46":"f","\u1E1F":"f","\u0192":"f","\uA77C":"f","\u24D6":"g","\uFF47":"g","\u01F5":"g","\u011D":"g","\u1E21":"g","\u011F":"g","\u0121":"g","\u01E7":"g","\u0123":"g","\u01E5":"g","\u0260":"g","\uA7A1":"g","\u1D79":"g","\uA77F":"g","\u24D7":"h","\uFF48":"h","\u0125":"h","\u1E23":"h","\u1E27":"h","\u021F":"h","\u1E25":"h","\u1E29":"h","\u1E2B":"h","\u1E96":"h","\u0127":"h","\u2C68":"h","\u2C76":"h","\u0265":"h","\u0195":"hv","\u24D8":"i","\uFF49":"i","\u00EC":"i","\u00ED":"i","\u00EE":"i","\u0129":"i","\u012B":"i","\u012D":"i","\u00EF":"i","\u1E2F":"i","\u1EC9":"i","\u01D0":"i","\u0209":"i","\u020B":"i","\u1ECB":"i","\u012F":"i","\u1E2D":"i","\u0268":"i","\u0131":"i","\u24D9":"j","\uFF4A":"j","\u0135":"j","\u01F0":"j","\u0249":"j","\u24DA":"k","\uFF4B":"k","\u1E31":"k","\u01E9":"k","\u1E33":"k","\u0137":"k","\u1E35":"k","\u0199":"k","\u2C6A":"k","\uA741":"k","\uA743":"k","\uA745":"k","\uA7A3":"k","\u24DB":"l","\uFF4C":"l","\u0140":"l","\u013A":"l","\u013E":"l","\u1E37":"l","\u1E39":"l","\u013C":"l","\u1E3D":"l","\u1E3B":"l","\u017F":"l","\u0142":"l","\u019A":"l","\u026B":"l","\u2C61":"l","\uA749":"l","\uA781":"l","\uA747":"l","\u01C9":"lj","\u24DC":"m","\uFF4D":"m","\u1E3F":"m","\u1E41":"m","\u1E43":"m","\u0271":"m","\u026F":"m","\u24DD":"n","\uFF4E":"n","\u01F9":"n","\u0144":"n","\u00F1":"n","\u1E45":"n","\u0148":"n","\u1E47":"n","\u0146":"n","\u1E4B":"n","\u1E49":"n","\u019E":"n","\u0272":"n","\u0149":"n","\uA791":"n","\uA7A5":"n","\u01CC":"nj","\u24DE":"o","\uFF4F":"o","\u00F2":"o","\u00F3":"o","\u00F4":"o","\u1ED3":"o","\u1ED1":"o","\u1ED7":"o","\u1ED5":"o","\u00F5":"o","\u1E4D":"o","\u022D":"o","\u1E4F":"o","\u014D":"o","\u1E51":"o","\u1E53":"o","\u014F":"o","\u022F":"o","\u0231":"o","\u00F6":"o","\u022B":"o","\u1ECF":"o","\u0151":"o","\u01D2":"o","\u020D":"o","\u020F":"o","\u01A1":"o","\u1EDD":"o","\u1EDB":"o","\u1EE1":"o","\u1EDF":"o","\u1EE3":"o","\u1ECD":"o","\u1ED9":"o","\u01EB":"o","\u01ED":"o","\u00F8":"o","\u01FF":"o","\u0254":"o","\uA74B":"o","\uA74D":"o","\u0275":"o","\u01A3":"oi","\u0223":"ou","\uA74F":"oo","\u24DF":"p","\uFF50":"p","\u1E55":"p","\u1E57":"p","\u01A5":"p","\u1D7D":"p","\uA751":"p","\uA753":"p","\uA755":"p","\u24E0":"q","\uFF51":"q","\u024B":"q","\uA757":"q","\uA759":"q","\u24E1":"r","\uFF52":"r","\u0155":"r","\u1E59":"r","\u0159":"r","\u0211":"r","\u0213":"r","\u1E5B":"r","\u1E5D":"r","\u0157":"r","\u1E5F":"r","\u024D":"r","\u027D":"r","\uA75B":"r","\uA7A7":"r","\uA783":"r","\u24E2":"s","\uFF53":"s","\u00DF":"s","\u015B":"s","\u1E65":"s","\u015D":"s","\u1E61":"s","\u0161":"s","\u1E67":"s","\u1E63":"s","\u1E69":"s","\u0219":"s","\u015F":"s","\u023F":"s","\uA7A9":"s","\uA785":"s","\u1E9B":"s","\u24E3":"t","\uFF54":"t","\u1E6B":"t","\u1E97":"t","\u0165":"t","\u1E6D":"t","\u021B":"t","\u0163":"t","\u1E71":"t","\u1E6F":"t","\u0167":"t","\u01AD":"t","\u0288":"t","\u2C66":"t","\uA787":"t","\uA729":"tz","\u24E4":"u","\uFF55":"u","\u00F9":"u","\u00FA":"u","\u00FB":"u","\u0169":"u","\u1E79":"u","\u016B":"u","\u1E7B":"u","\u016D":"u","\u00FC":"u","\u01DC":"u","\u01D8":"u","\u01D6":"u","\u01DA":"u","\u1EE7":"u","\u016F":"u","\u0171":"u","\u01D4":"u","\u0215":"u","\u0217":"u","\u01B0":"u","\u1EEB":"u","\u1EE9":"u","\u1EEF":"u","\u1EED":"u","\u1EF1":"u","\u1EE5":"u","\u1E73":"u","\u0173":"u","\u1E77":"u","\u1E75":"u","\u0289":"u","\u24E5":"v","\uFF56":"v","\u1E7D":"v","\u1E7F":"v","\u028B":"v","\uA75F":"v","\u028C":"v","\uA761":"vy","\u24E6":"w","\uFF57":"w","\u1E81":"w","\u1E83":"w","\u0175":"w","\u1E87":"w","\u1E85":"w","\u1E98":"w","\u1E89":"w","\u2C73":"w","\u24E7":"x","\uFF58":"x","\u1E8B":"x","\u1E8D":"x","\u24E8":"y","\uFF59":"y","\u1EF3":"y","\u00FD":"y","\u0177":"y","\u1EF9":"y","\u0233":"y","\u1E8F":"y","\u00FF":"y","\u1EF7":"y","\u1E99":"y","\u1EF5":"y","\u01B4":"y","\u024F":"y","\u1EFF":"y","\u24E9":"z","\uFF5A":"z","\u017A":"z","\u1E91":"z","\u017C":"z","\u017E":"z","\u1E93":"z","\u1E95":"z","\u01B6":"z","\u0225":"z","\u0240":"z","\u2C6C":"z","\uA763":"z"}; $document = $(document); nextUid=(function() { var counter=1; return function() { return counter++; }; }()); function stripDiacritics(str) { var ret, i, l, c; if (!str || str.length < 1) return str; ret = ""; for (i = 0, l = str.length; i < l; i++) { c = str.charAt(i); ret += DIACRITICS[c] || c; } return ret; } function indexOf(value, array) { var i = 0, l = array.length; for (; i < l; i = i + 1) { if (equal(value, array[i])) return i; } return -1; } function measureScrollbar () { var $template = $( MEASURE_SCROLLBAR_TEMPLATE ); $template.appendTo('body'); var dim = { width: $template.width() - $template[0].clientWidth, height: $template.height() - $template[0].clientHeight }; $template.remove(); return dim; } /** * Compares equality of a and b * @param a * @param b */ function equal(a, b) { if (a === b) return true; if (a === undefined || b === undefined) return false; if (a === null || b === null) return false; // Check whether 'a' or 'b' is a string (primitive or object). // The concatenation of an empty string (+'') converts its argument to a string's primitive. if (a.constructor === String) return a+'' === b+''; // a+'' - in case 'a' is a String object if (b.constructor === String) return b+'' === a+''; // b+'' - in case 'b' is a String object return false; } /** * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty * strings * @param string * @param separator */ function splitVal(string, separator) { var val, i, l; if (string === null || string.length < 1) return []; val = string.split(separator); for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]); return val; } function getSideBorderPadding(element) { return element.outerWidth(false) - element.width(); } function installKeyUpChangeEvent(element) { var key="keyup-change-value"; element.on("keydown", function () { if ($.data(element, key) === undefined) { $.data(element, key, element.val()); } }); element.on("keyup", function () { var val= $.data(element, key); if (val !== undefined && element.val() !== val) { $.removeData(element, key); element.trigger("keyup-change"); } }); } $document.on("mousemove", function (e) { lastMousePosition.x = e.pageX; lastMousePosition.y = e.pageY; }); /** * filters mouse events so an event is fired only if the mouse moved. * * filters out mouse events that occur when mouse is stationary but * the elements under the pointer are scrolled. */ function installFilteredMouseMove(element) { element.on("mousemove", function (e) { var lastpos = lastMousePosition; if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) { $(e.target).trigger("mousemove-filtered", e); } }); } /** * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made * within the last quietMillis milliseconds. * * @param quietMillis number of milliseconds to wait before invoking fn * @param fn function to be debounced * @param ctx object to be used as this reference within fn * @return debounced version of fn */ function debounce(quietMillis, fn, ctx) { ctx = ctx || undefined; var timeout; return function () { var args = arguments; window.clearTimeout(timeout); timeout = window.setTimeout(function() { fn.apply(ctx, args); }, quietMillis); }; } /** * A simple implementation of a thunk * @param formula function used to lazily initialize the thunk * @return {Function} */ function thunk(formula) { var evaluated = false, value; return function() { if (evaluated === false) { value = formula(); evaluated = true; } return value; }; }; function installDebouncedScroll(threshold, element) { var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);}); element.on("scroll", function (e) { if (indexOf(e.target, element.get()) >= 0) notify(e); }); } function focus($el) { if ($el[0] === document.activeElement) return; /* set the focus in a 0 timeout - that way the focus is set after the processing of the current event has finished - which seems like the only reliable way to set focus */ window.setTimeout(function() { var el=$el[0], pos=$el.val().length, range; $el.focus(); /* make sure el received focus so we do not error out when trying to manipulate the caret. sometimes modals or others listeners may steal it after its set */ if ($el.is(":visible") && el === document.activeElement) { /* after the focus is set move the caret to the end, necessary when we val() just before setting focus */ if(el.setSelectionRange) { el.setSelectionRange(pos, pos); } else if (el.createTextRange) { range = el.createTextRange(); range.collapse(false); range.select(); } } }, 0); } function getCursorInfo(el) { el = $(el)[0]; var offset = 0; var length = 0; if ('selectionStart' in el) { offset = el.selectionStart; length = el.selectionEnd - offset; } else if ('selection' in document) { el.focus(); var sel = document.selection.createRange(); length = document.selection.createRange().text.length; sel.moveStart('character', -el.value.length); offset = sel.text.length - length; } return { offset: offset, length: length }; } function killEvent(event) { event.preventDefault(); event.stopPropagation(); } function killEventImmediately(event) { event.preventDefault(); event.stopImmediatePropagation(); } function measureTextWidth(e) { if (!sizer){ var style = e[0].currentStyle || window.getComputedStyle(e[0], null); sizer = $(document.createElement("div")).css({ position: "absolute", left: "-10000px", top: "-10000px", display: "none", fontSize: style.fontSize, fontFamily: style.fontFamily, fontStyle: style.fontStyle, fontWeight: style.fontWeight, letterSpacing: style.letterSpacing, textTransform: style.textTransform, whiteSpace: "nowrap" }); sizer.attr("class","select2-sizer"); $("body").append(sizer); } sizer.text(e.val()); return sizer.width(); } function syncCssClasses(dest, src, adapter) { var classes, replacements = [], adapted; classes = dest.attr("class"); if (classes) { classes = '' + classes; // for IE which returns object $(classes.split(" ")).each2(function() { if (this.indexOf("select2-") === 0) { replacements.push(this); } }); } classes = src.attr("class"); if (classes) { classes = '' + classes; // for IE which returns object $(classes.split(" ")).each2(function() { if (this.indexOf("select2-") !== 0) { adapted = adapter(this); if (adapted) { replacements.push(this); } } }); } dest.attr("class", replacements.join(" ")); } function markMatch(text, term, markup, escapeMarkup) { var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())), tl=term.length; if (match<0) { markup.push(escapeMarkup(text)); return; } markup.push(escapeMarkup(text.substring(0, match))); markup.push("<span class='select2-match'>"); markup.push(escapeMarkup(text.substring(match, match + tl))); markup.push("</span>"); markup.push(escapeMarkup(text.substring(match + tl, text.length))); } function defaultEscapeMarkup(markup) { var replace_map = { '\\': '&#92;', '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', "/": '&#47;' }; return String(markup).replace(/[&<>"'\/\\]/g, function (match) { return replace_map[match]; }); } /** * Produces an ajax-based query function * * @param options object containing configuration paramters * @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax * @param options.url url for the data * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url. * @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2. * The expected format is an object containing the following keys: * results array of objects that will be used as choices * more (optional) boolean indicating whether there are more results available * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true} */ function ajax(options) { var timeout, // current scheduled but not yet executed request handler = null, quietMillis = options.quietMillis || 100, ajaxUrl = options.url, self = this; return function (query) { window.clearTimeout(timeout); timeout = window.setTimeout(function () { var data = options.data, // ajax data function url = ajaxUrl, // ajax url string or function transport = options.transport || $.fn.select2.ajaxDefaults.transport, // deprecated - to be removed in 4.0 - use params instead deprecated = { type: options.type || 'GET', // set type of request (GET or POST) cache: options.cache || false, jsonpCallback: options.jsonpCallback||undefined, dataType: options.dataType||"json" }, params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated); data = data ? data.call(self, query.term, query.page, query.context) : null; url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url; if (handler) { handler.abort(); } if (options.params) { if ($.isFunction(options.params)) { $.extend(params, options.params.call(self)); } else { $.extend(params, options.params); } } $.extend(params, { url: url, dataType: options.dataType, data: data, success: function (data) { // TODO - replace query.page with query so users have access to term, page, etc. var results = options.results(data, query.page); query.callback(results); } }); handler = transport.call(self, params); }, quietMillis); }; } /** * Produces a query function that works with a local array * * @param options object containing configuration parameters. The options parameter can either be an array or an * object. * * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys. * * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text' * key can either be a String in which case it is expected that each element in the 'data' array has a key with the * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract * the text. */ function local(options) { var data = options, // data elements dataText, tmp, text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search if ($.isArray(data)) { tmp = data; data = { results: tmp }; } if ($.isFunction(data) === false) { tmp = data; data = function() { return tmp; }; } var dataItem = data(); if (dataItem.text) { text = dataItem.text; // if text is not a function we assume it to be a key name if (!$.isFunction(text)) { dataText = dataItem.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available text = function (item) { return item[dataText]; }; } } return function (query) { var t = query.term, filtered = { results: [] }, process; if (t === "") { query.callback(data()); return; } process = function(datum, collection) { var group, attr; datum = datum[0]; if (datum.children) { group = {}; for (attr in datum) { if (datum.hasOwnProperty(attr)) group[attr]=datum[attr]; } group.children=[]; $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); }); if (group.children.length || query.matcher(t, text(group), datum)) { collection.push(group); } } else { if (query.matcher(t, text(datum), datum)) { collection.push(datum); } } }; $(data().results).each2(function(i, datum) { process(datum, filtered.results); }); query.callback(filtered); }; } // TODO javadoc function tags(data) { var isFunc = $.isFunction(data); return function (query) { var t = query.term, filtered = {results: []}; $(isFunc ? data() : data).each(function () { var isObject = this.text !== undefined, text = isObject ? this.text : this; if (t === "" || query.matcher(t, text)) { filtered.results.push(isObject ? this : {id: this, text: this}); } }); query.callback(filtered); }; } /** * Checks if the formatter function should be used. * * Throws an error if it is not a function. Returns true if it should be used, * false if no formatting should be performed. * * @param formatter */ function checkFormatter(formatter, formatterName) { if ($.isFunction(formatter)) return true; if (!formatter) return false; throw new Error(formatterName +" must be a function or a falsy value"); } function evaluate(val) { return $.isFunction(val) ? val() : val; } function countResults(results) { var count = 0; $.each(results, function(i, item) { if (item.children) { count += countResults(item.children); } else { count++; } }); return count; } /** * Default tokenizer. This function uses breaks the input on substring match of any string from the * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those * two options have to be defined in order for the tokenizer to work. * * @param input text user has typed so far or pasted into the search field * @param selection currently selected choices * @param selectCallback function(choice) callback tho add the choice to selection * @param opts select2's opts * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value */ function defaultTokenizer(input, selection, selectCallback, opts) { var original = input, // store the original so we can compare and know if we need to tell the search to update its text dupe = false, // check for whether a token we extracted represents a duplicate selected choice token, // token index, // position at which the separator was found i, l, // looping variables separator; // the matched separator if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined; while (true) { index = -1; for (i = 0, l = opts.tokenSeparators.length; i < l; i++) { separator = opts.tokenSeparators[i]; index = input.indexOf(separator); if (index >= 0) break; } if (index < 0) break; // did not find any token separator in the input string, bail token = input.substring(0, index); input = input.substring(index + separator.length); if (token.length > 0) { token = opts.createSearchChoice.call(this, token, selection); if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) { dupe = false; for (i = 0, l = selection.length; i < l; i++) { if (equal(opts.id(token), opts.id(selection[i]))) { dupe = true; break; } } if (!dupe) selectCallback(token); } } } if (original!==input) return input; } /** * Creates a new class * * @param superClass * @param methods */ function clazz(SuperClass, methods) { var constructor = function () {}; constructor.prototype = new SuperClass; constructor.prototype.constructor = constructor; constructor.prototype.parent = SuperClass.prototype; constructor.prototype = $.extend(constructor.prototype, methods); return constructor; } AbstractSelect2 = clazz(Object, { // abstract bind: function (func) { var self = this; return function () { func.apply(self, arguments); }; }, // abstract init: function (opts) { var results, search, resultsSelector = ".select2-results", disabled, readonly; // prepare options this.opts = opts = this.prepareOpts(opts); this.id=opts.id; // destroy if called on an existing component if (opts.element.data("select2") !== undefined && opts.element.data("select2") !== null) { opts.element.data("select2").destroy(); } this.container = this.createContainer(); this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid()); this.containerSelector="#"+this.containerId.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); this.container.attr("id", this.containerId); // cache the body so future lookups are cheap this.body = thunk(function() { return opts.element.closest("body"); }); syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass); this.container.attr("style", opts.element.attr("style")); this.container.css(evaluate(opts.containerCss)); this.container.addClass(evaluate(opts.containerCssClass)); this.elementTabIndex = this.opts.element.attr("tabindex"); // swap container for the element this.opts.element .data("select2", this) .attr("tabindex", "-1") .before(this.container); this.container.data("select2", this); this.dropdown = this.container.find(".select2-drop"); this.dropdown.addClass(evaluate(opts.dropdownCssClass)); this.dropdown.data("select2", this); syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass); this.results = results = this.container.find(resultsSelector); this.search = search = this.container.find("input.select2-input"); this.queryCount = 0; this.resultsPage = 0; this.context = null; // initialize the container this.initContainer(); installFilteredMouseMove(this.results); this.dropdown.on("mousemove-filtered touchstart touchmove touchend", resultsSelector, this.bind(this.highlightUnderEvent)); installDebouncedScroll(80, this.results); this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded)); // do not propagate change event from the search field out of the component $(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();}); $(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();}); // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel if ($.fn.mousewheel) { results.mousewheel(function (e, delta, deltaX, deltaY) { var top = results.scrollTop(), height; if (deltaY > 0 && top - deltaY <= 0) { results.scrollTop(0); killEvent(e); } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) { results.scrollTop(results.get(0).scrollHeight - results.height()); killEvent(e); } }); } installKeyUpChangeEvent(search); search.on("keyup-change input paste", this.bind(this.updateResults)); search.on("focus", function () { search.addClass("select2-focused"); }); search.on("blur", function () { search.removeClass("select2-focused");}); this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) { if ($(e.target).closest(".select2-result-selectable").length > 0) { this.highlightUnderEvent(e); this.selectHighlighted(e); } })); // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's // dom it will trigger the popup close, which is not what we want this.dropdown.on("click mouseup mousedown", function (e) { e.stopPropagation(); }); if ($.isFunction(this.opts.initSelection)) { // initialize selection based on the current value of the source element this.initSelection(); // if the user has provided a function that can set selection based on the value of the source element // we monitor the change event on the element and trigger it, allowing for two way synchronization this.monitorSource(); } if (opts.maximumInputLength !== null) { this.search.attr("maxlength", opts.maximumInputLength); } var disabled = opts.element.prop("disabled"); if (disabled === undefined) disabled = false; this.enable(!disabled); var readonly = opts.element.prop("readonly"); if (readonly === undefined) readonly = false; this.readonly(readonly); // Calculate size of scrollbar scrollBarDimensions = scrollBarDimensions || measureScrollbar(); this.autofocus = opts.element.prop("autofocus"); opts.element.prop("autofocus", false); if (this.autofocus) this.focus(); this.nextSearchTerm = undefined; }, // abstract destroy: function () { var element=this.opts.element, select2 = element.data("select2"); this.close(); if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; } if (select2 !== undefined) { select2.container.remove(); select2.dropdown.remove(); element .removeClass("select2-offscreen") .removeData("select2") .off(".select2") .prop("autofocus", this.autofocus || false); if (this.elementTabIndex) { element.attr({tabindex: this.elementTabIndex}); } else { element.removeAttr("tabindex"); } element.show(); } }, // abstract optionToData: function(element) { if (element.is("option")) { return { id:element.prop("value"), text:element.text(), element: element.get(), css: element.attr("class"), disabled: element.prop("disabled"), locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true) }; } else if (element.is("optgroup")) { return { text:element.attr("label"), children:[], element: element.get(), css: element.attr("class") }; } }, // abstract prepareOpts: function (opts) { var element, select, idKey, ajaxUrl, self = this; element = opts.element; if (element.get(0).tagName.toLowerCase() === "select") { this.select = select = opts.element; } if (select) { // these options are not allowed when attached to a select because they are picked up off the element itself $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () { if (this in opts) { throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element."); } }); } opts = $.extend({}, { populateResults: function(container, results, query) { var populate, data, result, children, id=this.opts.id; populate=function(results, container, depth) { var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted; results = opts.sortResults(results, container, query); for (i = 0, l = results.length; i < l; i = i + 1) { result=results[i]; disabled = (result.disabled === true); selectable = (!disabled) && (id(result) !== undefined); compound=result.children && result.children.length > 0; node=$("<li></li>"); node.addClass("select2-results-dept-"+depth); node.addClass("select2-result"); node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable"); if (disabled) { node.addClass("select2-disabled"); } if (compound) { node.addClass("select2-result-with-children"); } node.addClass(self.opts.formatResultCssClass(result)); label=$(document.createElement("div")); label.addClass("select2-result-label"); formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup); if (formatted!==undefined) { label.html(formatted); } node.append(label); if (compound) { innerContainer=$("<ul></ul>"); innerContainer.addClass("select2-result-sub"); populate(result.children, innerContainer, depth+1); node.append(innerContainer); } node.data("select2-data", result); container.append(node); } }; populate(results, container, 0); } }, $.fn.select2.defaults, opts); if (typeof(opts.id) !== "function") { idKey = opts.id; opts.id = function (e) { return e[idKey]; }; } if ($.isArray(opts.element.data("select2Tags"))) { if ("tags" in opts) { throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id"); } opts.tags=opts.element.data("select2Tags"); } if (select) { opts.query = this.bind(function (query) { var data = { results: [], more: false }, term = query.term, children, placeholderOption, process; process=function(element, collection) { var group; if (element.is("option")) { if (query.matcher(term, element.text(), element)) { collection.push(self.optionToData(element)); } } else if (element.is("optgroup")) { group=self.optionToData(element); element.children().each2(function(i, elm) { process(elm, group.children); }); if (group.children.length>0) { collection.push(group); } } }; children=element.children(); // ignore the placeholder option if there is one if (this.getPlaceholder() !== undefined && children.length > 0) { placeholderOption = this.getPlaceholderOption(); if (placeholderOption) { children=children.not(placeholderOption); } } children.each2(function(i, elm) { process(elm, data.results); }); query.callback(data); }); // this is needed because inside val() we construct choices from options and there id is hardcoded opts.id=function(e) { return e.id; }; opts.formatResultCssClass = function(data) { return data.css; }; } else { if (!("query" in opts)) { if ("ajax" in opts) { ajaxUrl = opts.element.data("ajax-url"); if (ajaxUrl && ajaxUrl.length > 0) { opts.ajax.url = ajaxUrl; } opts.query = ajax.call(opts.element, opts.ajax); } else if ("data" in opts) { opts.query = local(opts.data); } else if ("tags" in opts) { opts.query = tags(opts.tags); if (opts.createSearchChoice === undefined) { opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; }; } if (opts.initSelection === undefined) { opts.initSelection = function (element, callback) { var data = []; $(splitVal(element.val(), opts.separator)).each(function () { var id = this, text = this, tags=opts.tags; if ($.isFunction(tags)) tags=tags(); $(tags).each(function() { if (equal(this.id, id)) { text = this.text; return false; } }); data.push({id: id, text: text}); }); callback(data); }; } } } } if (typeof(opts.query) !== "function") { throw "query function not defined for Select2 " + opts.element.attr("id"); } return opts; }, /** * Monitor the original element for changes and update select2 accordingly */ // abstract monitorSource: function () { var el = this.opts.element, sync; el.on("change.select2", this.bind(function (e) { if (this.opts.element.data("select2-change-triggered") !== true) { this.initSelection(); } })); sync = this.bind(function () { var enabled, readonly, self = this; // sync enabled state var disabled = el.prop("disabled"); if (disabled === undefined) disabled = false; this.enable(!disabled); var readonly = el.prop("readonly"); if (readonly === undefined) readonly = false; this.readonly(readonly); syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass); this.container.addClass(evaluate(this.opts.containerCssClass)); syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass); this.dropdown.addClass(evaluate(this.opts.dropdownCssClass)); }); // mozilla and IE el.on("propertychange.select2 DOMAttrModified.select2", sync); // hold onto a reference of the callback to work around a chromium bug if (this.mutationCallback === undefined) { this.mutationCallback = function (mutations) { mutations.forEach(sync); } } // safari and chrome if (typeof WebKitMutationObserver !== "undefined") { if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; } this.propertyObserver = new WebKitMutationObserver(this.mutationCallback); this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false }); } }, // abstract triggerSelect: function(data) { var evt = $.Event("select2-selecting", { val: this.id(data), object: data }); this.opts.element.trigger(evt); return !evt.isDefaultPrevented(); }, /** * Triggers the change event on the source element */ // abstract triggerChange: function (details) { details = details || {}; details= $.extend({}, details, { type: "change", val: this.val() }); // prevents recursive triggering this.opts.element.data("select2-change-triggered", true); this.opts.element.trigger(details); this.opts.element.data("select2-change-triggered", false); // some validation frameworks ignore the change event and listen instead to keyup, click for selects // so here we trigger the click event manually this.opts.element.click(); // ValidationEngine ignorea the change event and listens instead to blur // so here we trigger the blur event manually if so desired if (this.opts.blurOnChange) this.opts.element.blur(); }, //abstract isInterfaceEnabled: function() { return this.enabledInterface === true; }, // abstract enableInterface: function() { var enabled = this._enabled && !this._readonly, disabled = !enabled; if (enabled === this.enabledInterface) return false; this.container.toggleClass("select2-container-disabled", disabled); this.close(); this.enabledInterface = enabled; return true; }, // abstract enable: function(enabled) { if (enabled === undefined) enabled = true; if (this._enabled === enabled) return; this._enabled = enabled; this.opts.element.prop("disabled", !enabled); this.enableInterface(); }, // abstract disable: function() { this.enable(false); }, // abstract readonly: function(enabled) { if (enabled === undefined) enabled = false; if (this._readonly === enabled) return false; this._readonly = enabled; this.opts.element.prop("readonly", enabled); this.enableInterface(); return true; }, // abstract opened: function () { return this.container.hasClass("select2-dropdown-open"); }, // abstract positionDropdown: function() { var $dropdown = this.dropdown, offset = this.container.offset(), height = this.container.outerHeight(false), width = this.container.outerWidth(false), dropHeight = $dropdown.outerHeight(false), viewPortRight = $(window).scrollLeft() + $(window).width(), viewportBottom = $(window).scrollTop() + $(window).height(), dropTop = offset.top + height, dropLeft = offset.left, enoughRoomBelow = dropTop + dropHeight <= viewportBottom, enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(), dropWidth = $dropdown.outerWidth(false), enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight, aboveNow = $dropdown.hasClass("select2-drop-above"), bodyOffset, above, css, resultsListNode; if (this.opts.dropdownAutoWidth) { resultsListNode = $('.select2-results', $dropdown)[0]; $dropdown.addClass('select2-drop-auto-width'); $dropdown.css('width', ''); // Add scrollbar width to dropdown if vertical scrollbar is present dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width); dropWidth > width ? width = dropWidth : dropWidth = width; enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight; } else { this.container.removeClass('select2-drop-auto-width'); } //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow); //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove); // fix positioning when body has an offset and is not position: static if (this.body().css('position') !== 'static') { bodyOffset = this.body().offset(); dropTop -= bodyOffset.top; dropLeft -= bodyOffset.left; } // always prefer the current above/below alignment, unless there is not enough room if (aboveNow) { above = true; if (!enoughRoomAbove && enoughRoomBelow) above = false; } else { above = false; if (!enoughRoomBelow && enoughRoomAbove) above = true; } if (!enoughRoomOnRight) { dropLeft = offset.left + width - dropWidth; } if (above) { dropTop = offset.top - dropHeight; this.container.addClass("select2-drop-above"); $dropdown.addClass("select2-drop-above"); } else { this.container.removeClass("select2-drop-above"); $dropdown.removeClass("select2-drop-above"); } css = $.extend({ top: dropTop, left: dropLeft, width: width }, evaluate(this.opts.dropdownCss)); $dropdown.css(css); }, // abstract shouldOpen: function() { var event; if (this.opened()) return false; if (this._enabled === false || this._readonly === true) return false; event = $.Event("select2-opening"); this.opts.element.trigger(event); return !event.isDefaultPrevented(); }, // abstract clearDropdownAlignmentPreference: function() { // clear the classes used to figure out the preference of where the dropdown should be opened this.container.removeClass("select2-drop-above"); this.dropdown.removeClass("select2-drop-above"); }, /** * Opens the dropdown * * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example, * the dropdown is already open, or if the 'open' event listener on the element called preventDefault(). */ // abstract open: function () { if (!this.shouldOpen()) return false; this.opening(); return true; }, /** * Performs the opening of the dropdown */ // abstract opening: function() { var cid = this.containerId, scroll = "scroll." + cid, resize = "resize."+cid, orient = "orientationchange."+cid, mask, maskCss; this.container.addClass("select2-dropdown-open").addClass("select2-container-active"); this.clearDropdownAlignmentPreference(); if(this.dropdown[0] !== this.body().children().last()[0]) { this.dropdown.detach().appendTo(this.body()); } // create the dropdown mask if doesnt already exist mask = $("#select2-drop-mask"); if (mask.length == 0) { mask = $(document.createElement("div")); mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask"); mask.hide(); mask.appendTo(this.body()); mask.on("mousedown touchstart click", function (e) { var dropdown = $("#select2-drop"), self; if (dropdown.length > 0) { self=dropdown.data("select2"); if (self.opts.selectOnBlur) { self.selectHighlighted({noFocus: true}); } self.close({focus:false}); e.preventDefault(); e.stopPropagation(); } }); } // ensure the mask is always right before the dropdown if (this.dropdown.prev()[0] !== mask[0]) { this.dropdown.before(mask); } // move the global id to the correct dropdown $("#select2-drop").removeAttr("id"); this.dropdown.attr("id", "select2-drop"); // show the elements mask.show(); this.positionDropdown(); this.dropdown.show(); this.positionDropdown(); this.dropdown.addClass("select2-drop-active"); // attach listeners to events that can change the position of the container and thus require // the position of the dropdown to be updated as well so it does not come unglued from the container var that = this; this.container.parents().add(window).each(function () { $(this).on(resize+" "+scroll+" "+orient, function (e) { that.positionDropdown(); }); }); }, // abstract close: function () { if (!this.opened()) return; var cid = this.containerId, scroll = "scroll." + cid, resize = "resize."+cid, orient = "orientationchange."+cid; // unbind event listeners this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); }); this.clearDropdownAlignmentPreference(); $("#select2-drop-mask").hide(); this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id this.dropdown.hide(); this.container.removeClass("select2-dropdown-open"); this.results.empty(); this.clearSearch(); this.search.removeClass("select2-active"); this.opts.element.trigger($.Event("select2-close")); }, /** * Opens control, sets input value, and updates results. */ // abstract externalSearch: function (term) { this.open(); this.search.val(term); this.updateResults(false); }, // abstract clearSearch: function () { }, //abstract getMaximumSelectionSize: function() { return evaluate(this.opts.maximumSelectionSize); }, // abstract ensureHighlightVisible: function () { var results = this.results, children, index, child, hb, rb, y, more; index = this.highlight(); if (index < 0) return; if (index == 0) { // if the first element is highlighted scroll all the way to the top, // that way any unselectable headers above it will also be scrolled // into view results.scrollTop(0); return; } children = this.findHighlightableChoices().find('.select2-result-label'); child = $(children[index]); hb = child.offset().top + child.outerHeight(true); // if this is the last child lets also make sure select2-more-results is visible if (index === children.length - 1) { more = results.find("li.select2-more-results"); if (more.length > 0) { hb = more.offset().top + more.outerHeight(true); } } rb = results.offset().top + results.outerHeight(true); if (hb > rb) { results.scrollTop(results.scrollTop() + (hb - rb)); } y = child.offset().top - results.offset().top; // make sure the top of the element is visible if (y < 0 && child.css('display') != 'none' ) { results.scrollTop(results.scrollTop() + y); // y is negative } }, // abstract findHighlightableChoices: function() { return this.results.find(".select2-result-selectable:not(.select2-selected):not(.select2-disabled)"); }, // abstract moveHighlight: function (delta) { var choices = this.findHighlightableChoices(), index = this.highlight(); while (index > -1 && index < choices.length) { index += delta; var choice = $(choices[index]); if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) { this.highlight(index); break; } } }, // abstract highlight: function (index) { var choices = this.findHighlightableChoices(), choice, data; if (arguments.length === 0) { return indexOf(choices.filter(".select2-highlighted")[0], choices.get()); } if (index >= choices.length) index = choices.length - 1; if (index < 0) index = 0; this.removeHighlight(); choice = $(choices[index]); choice.addClass("select2-highlighted"); this.ensureHighlightVisible(); data = choice.data("select2-data"); if (data) { this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data }); } }, removeHighlight: function() { this.results.find(".select2-highlighted").removeClass("select2-highlighted"); }, // abstract countSelectableResults: function() { return this.findHighlightableChoices().length; }, // abstract highlightUnderEvent: function (event) { var el = $(event.target).closest(".select2-result-selectable"); if (el.length > 0 && !el.is(".select2-highlighted")) { var choices = this.findHighlightableChoices(); this.highlight(choices.index(el)); } else if (el.length == 0) { // if we are over an unselectable item remove all highlights this.removeHighlight(); } }, // abstract loadMoreIfNeeded: function () { var results = this.results, more = results.find("li.select2-more-results"), below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible offset = -1, // index of first element without data page = this.resultsPage + 1, self=this, term=this.search.val(), context=this.context; if (more.length === 0) return; below = more.offset().top - results.offset().top - results.height(); if (below <= this.opts.loadMorePadding) { more.addClass("select2-active"); this.opts.query({ element: this.opts.element, term: term, page: page, context: context, matcher: this.opts.matcher, callback: this.bind(function (data) { // ignore a response if the select2 has been closed before it was received if (!self.opened()) return; self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context}); self.postprocessResults(data, false, false); if (data.more===true) { more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1)); window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10); } else { more.remove(); } self.positionDropdown(); self.resultsPage = page; self.context = data.context; this.opts.element.trigger({ type: "select2-loaded", items: data }); })}); } }, /** * Default tokenizer function which does nothing */ tokenize: function() { }, /** * @param initial whether or not this is the call to this method right after the dropdown has been opened */ // abstract updateResults: function (initial) { var search = this.search, results = this.results, opts = this.opts, data, self = this, input, term = search.val(), lastTerm = $.data(this.container, "select2-last-term"), // sequence number used to drop out-of-order responses queryNumber; // prevent duplicate queries against the same term if (initial !== true && lastTerm && equal(term, lastTerm)) return; $.data(this.container, "select2-last-term", term); // if the search is currently hidden we do not alter the results if (initial !== true && (this.showSearchInput === false || !this.opened())) { return; } function postRender() { search.removeClass("select2-active"); self.positionDropdown(); } function render(html) { results.html(html); postRender(); } queryNumber = ++this.queryCount; var maxSelSize = this.getMaximumSelectionSize(); if (maxSelSize >=1) { data = this.data(); if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) { render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(maxSelSize) + "</li>"); return; } } if (search.val().length < opts.minimumInputLength) { if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) { render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>"); } else { render(""); } if (initial && this.showSearch) this.showSearch(true); return; } if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) { if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) { render("<li class='select2-no-results'>" + opts.formatInputTooLong(search.val(), opts.maximumInputLength) + "</li>"); } else { render(""); } return; } if (opts.formatSearching && this.findHighlightableChoices().length === 0) { render("<li class='select2-searching'>" + opts.formatSearching() + "</li>"); } search.addClass("select2-active"); this.removeHighlight(); // give the tokenizer a chance to pre-process the input input = this.tokenize(); if (input != undefined && input != null) { search.val(input); } this.resultsPage = 1; opts.query({ element: opts.element, term: search.val(), page: this.resultsPage, context: null, matcher: opts.matcher, callback: this.bind(function (data) { var def; // default choice // ignore old responses if (queryNumber != this.queryCount) { return; } // ignore a response if the select2 has been closed before it was received if (!this.opened()) { this.search.removeClass("select2-active"); return; } // save context, if any this.context = (data.context===undefined) ? null : data.context; // create a default choice and prepend it to the list if (this.opts.createSearchChoice && search.val() !== "") { def = this.opts.createSearchChoice.call(self, search.val(), data.results); if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) { if ($(data.results).filter( function () { return equal(self.id(this), self.id(def)); }).length === 0) { data.results.unshift(def); } } } if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) { render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>"); return; } results.empty(); self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null}); if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) { results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>"); window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10); } this.postprocessResults(data, initial); postRender(); this.opts.element.trigger({ type: "select2-loaded", items: data }); })}); }, // abstract cancel: function () { this.close(); }, // abstract blur: function () { // if selectOnBlur == true, select the currently highlighted option if (this.opts.selectOnBlur) this.selectHighlighted({noFocus: true}); this.close(); this.container.removeClass("select2-container-active"); // synonymous to .is(':focus'), which is available in jquery >= 1.6 if (this.search[0] === document.activeElement) { this.search.blur(); } this.clearSearch(); this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"); }, // abstract focusSearch: function () { focus(this.search); }, // abstract selectHighlighted: function (options) { var index=this.highlight(), highlighted=this.results.find(".select2-highlighted"), data = highlighted.closest('.select2-result').data("select2-data"); if (data) { this.highlight(index); this.onSelect(data, options); } else if (options && options.noFocus) { this.close(); } }, // abstract getPlaceholder: function () { var placeholderOption; return this.opts.element.attr("placeholder") || this.opts.element.attr("data-placeholder") || // jquery 1.4 compat this.opts.element.data("placeholder") || this.opts.placeholder || ((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined); }, // abstract getPlaceholderOption: function() { if (this.select) { var firstOption = this.select.children().first(); if (this.opts.placeholderOption !== undefined ) { //Determine the placeholder option based on the specified placeholderOption setting return (this.opts.placeholderOption === "first" && firstOption) || (typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select)); } else if (firstOption.text() === "" && firstOption.val() === "") { //No explicit placeholder option specified, use the first if it's blank return firstOption; } } }, /** * Get the desired width for the container element. This is * derived first from option `width` passed to select2, then * the inline 'style' on the original element, and finally * falls back to the jQuery calculated element width. */ // abstract initContainerWidth: function () { function resolveContainerWidth() { var style, attrs, matches, i, l; if (this.opts.width === "off") { return null; } else if (this.opts.width === "element"){ return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px'; } else if (this.opts.width === "copy" || this.opts.width === "resolve") { // check if there is inline style on the element that contains width style = this.opts.element.attr('style'); if (style !== undefined) { attrs = style.split(';'); for (i = 0, l = attrs.length; i < l; i = i + 1) { matches = attrs[i].replace(/\s/g, '') .match(/[^-]width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i); if (matches !== null && matches.length >= 1) return matches[1]; } } if (this.opts.width === "resolve") { // next check if css('width') can resolve a width that is percent based, this is sometimes possible // when attached to input type=hidden or elements hidden via css style = this.opts.element.css('width'); if (style.indexOf("%") > 0) return style; // finally, fallback on the calculated width of the element return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px'); } return null; } else if ($.isFunction(this.opts.width)) { return this.opts.width(); } else { return this.opts.width; } }; var width = resolveContainerWidth.call(this); if (width !== null) { this.container.css("width", width); } } }); SingleSelect2 = clazz(AbstractSelect2, { // single createContainer: function () { var container = $(document.createElement("div")).attr({ "class": "select2-container" }).html([ "<a href='javascript:void(0)' onclick='return false;' class='select2-choice' tabindex='-1'>", " <span class='select2-chosen'>&nbsp;</span><abbr class='select2-search-choice-close'></abbr>", " <span class='select2-arrow'><b></b></span>", "</a>", "<input class='select2-focusser select2-offscreen' type='text'/>", "<div class='select2-drop select2-display-none'>", " <div class='select2-search'>", " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'/>", " </div>", " <ul class='select2-results'>", " </ul>", "</div>"].join("")); return container; }, // single enableInterface: function() { if (this.parent.enableInterface.apply(this, arguments)) { this.focusser.prop("disabled", !this.isInterfaceEnabled()); } }, // single opening: function () { var el, range, len; if (this.opts.minimumResultsForSearch >= 0) { this.showSearch(true); } this.parent.opening.apply(this, arguments); if (this.showSearchInput !== false) { // IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range // all other browsers handle this just fine this.search.val(this.focusser.val()); } this.search.focus(); // move the cursor to the end after focussing, otherwise it will be at the beginning and // new text will appear *before* focusser.val() el = this.search.get(0); if (el.createTextRange) { range = el.createTextRange(); range.collapse(false); range.select(); } else if (el.setSelectionRange) { len = this.search.val().length; el.setSelectionRange(len, len); } // initializes search's value with nextSearchTerm (if defined by user) // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter if(this.search.val() === "") { if(this.nextSearchTerm != undefined){ this.search.val(this.nextSearchTerm); this.search.select(); } } this.focusser.prop("disabled", true).val(""); this.updateResults(true); this.opts.element.trigger($.Event("select2-open")); }, // single close: function (params) { if (!this.opened()) return; this.parent.close.apply(this, arguments); params = params || {focus: true}; this.focusser.removeAttr("disabled"); if (params.focus) { this.focusser.focus(); } }, // single focus: function () { if (this.opened()) { this.close(); } else { this.focusser.removeAttr("disabled"); this.focusser.focus(); } }, // single isFocused: function () { return this.container.hasClass("select2-container-active"); }, // single cancel: function () { this.parent.cancel.apply(this, arguments); this.focusser.removeAttr("disabled"); this.focusser.focus(); }, // single destroy: function() { $("label[for='" + this.focusser.attr('id') + "']") .attr('for', this.opts.element.attr("id")); this.parent.destroy.apply(this, arguments); }, // single initContainer: function () { var selection, container = this.container, dropdown = this.dropdown; if (this.opts.minimumResultsForSearch < 0) { this.showSearch(false); } else { this.showSearch(true); } this.selection = selection = container.find(".select2-choice"); this.focusser = container.find(".select2-focusser"); // rewrite labels from original element to focusser this.focusser.attr("id", "s2id_autogen"+nextUid()); $("label[for='" + this.opts.element.attr("id") + "']") .attr('for', this.focusser.attr('id')); this.focusser.attr("tabindex", this.elementTabIndex); this.search.on("keydown", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) { // prevent the page from scrolling killEvent(e); return; } switch (e.which) { case KEY.UP: case KEY.DOWN: this.moveHighlight((e.which === KEY.UP) ? -1 : 1); killEvent(e); return; case KEY.ENTER: this.selectHighlighted(); killEvent(e); return; case KEY.TAB: // if selectOnBlur == true, select the currently highlighted option if (this.opts.selectOnBlur) { this.selectHighlighted({noFocus: true}); } return; case KEY.ESC: this.cancel(e); killEvent(e); return; } })); this.search.on("blur", this.bind(function(e) { // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown. // without this the search field loses focus which is annoying if (document.activeElement === this.body().get(0)) { window.setTimeout(this.bind(function() { this.search.focus(); }), 0); } })); this.focusser.on("keydown", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) { return; } if (this.opts.openOnEnter === false && e.which === KEY.ENTER) { killEvent(e); return; } if (e.which == KEY.DOWN || e.which == KEY.UP || (e.which == KEY.ENTER && this.opts.openOnEnter)) { if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return; this.open(); killEvent(e); return; } if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) { if (this.opts.allowClear) { this.clear(); } killEvent(e); return; } })); installKeyUpChangeEvent(this.focusser); this.focusser.on("keyup-change input", this.bind(function(e) { if (this.opts.minimumResultsForSearch >= 0) { e.stopPropagation(); if (this.opened()) return; this.open(); } })); selection.on("mousedown", "abbr", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; this.clear(); killEventImmediately(e); this.close(); this.selection.focus(); })); selection.on("mousedown", this.bind(function (e) { if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } if (this.opened()) { this.close(); } else if (this.isInterfaceEnabled()) { this.open(); } killEvent(e); })); dropdown.on("mousedown", this.bind(function() { this.search.focus(); })); selection.on("focus", this.bind(function(e) { killEvent(e); })); this.focusser.on("focus", this.bind(function(){ if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.container.addClass("select2-container-active"); })).on("blur", this.bind(function() { if (!this.opened()) { this.container.removeClass("select2-container-active"); this.opts.element.trigger($.Event("select2-blur")); } })); this.search.on("focus", this.bind(function(){ if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.container.addClass("select2-container-active"); })); this.initContainerWidth(); this.opts.element.addClass("select2-offscreen"); this.setPlaceholder(); }, // single clear: function(triggerChange) { var data=this.selection.data("select2-data"); if (data) { // guard against queued quick consecutive clicks var placeholderOption = this.getPlaceholderOption(); this.opts.element.val(placeholderOption ? placeholderOption.val() : ""); this.selection.find(".select2-chosen").empty(); this.selection.removeData("select2-data"); this.setPlaceholder(); if (triggerChange !== false){ this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data }); this.triggerChange({removed:data}); } } }, /** * Sets selection based on source element's value */ // single initSelection: function () { var selected; if (this.isPlaceholderOptionSelected()) { this.updateSelection(null); this.close(); this.setPlaceholder(); } else { var self = this; this.opts.initSelection.call(null, this.opts.element, function(selected){ if (selected !== undefined && selected !== null) { self.updateSelection(selected); self.close(); self.setPlaceholder(); } }); } }, isPlaceholderOptionSelected: function() { var placeholderOption; if (!this.opts.placeholder) return false; // no placeholder specified so no option should be considered return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.is(':selected')) || (this.opts.element.val() === "") || (this.opts.element.val() === undefined) || (this.opts.element.val() === null); }, // single prepareOpts: function () { var opts = this.parent.prepareOpts.apply(this, arguments), self=this; if (opts.element.get(0).tagName.toLowerCase() === "select") { // install the selection initializer opts.initSelection = function (element, callback) { var selected = element.find(":selected"); // a single select box always has a value, no need to null check 'selected' callback(self.optionToData(selected)); }; } else if ("data" in opts) { // install default initSelection when applied to hidden input and data is local opts.initSelection = opts.initSelection || function (element, callback) { var id = element.val(); //search in data by id, storing the actual matching item var match = null; opts.query({ matcher: function(term, text, el){ var is_match = equal(id, opts.id(el)); if (is_match) { match = el; } return is_match; }, callback: !$.isFunction(callback) ? $.noop : function() { callback(match); } }); }; } return opts; }, // single getPlaceholder: function() { // if a placeholder is specified on a single select without a valid placeholder option ignore it if (this.select) { if (this.getPlaceholderOption() === undefined) { return undefined; } } return this.parent.getPlaceholder.apply(this, arguments); }, // single setPlaceholder: function () { var placeholder = this.getPlaceholder(); if (this.isPlaceholderOptionSelected() && placeholder !== undefined) { // check for a placeholder option if attached to a select if (this.select && this.getPlaceholderOption() === undefined) return; this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder)); this.selection.addClass("select2-default"); this.container.removeClass("select2-allowclear"); } }, // single postprocessResults: function (data, initial, noHighlightUpdate) { var selected = 0, self = this, showSearchInput = true; // find the selected element in the result list this.findHighlightableChoices().each2(function (i, elm) { if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) { selected = i; return false; } }); // and highlight it if (noHighlightUpdate !== false) { if (initial === true && selected >= 0) { this.highlight(selected); } else { this.highlight(0); } } // hide the search box if this is the first we got the results and there are enough of them for search if (initial === true) { var min = this.opts.minimumResultsForSearch; if (min >= 0) { this.showSearch(countResults(data.results) >= min); } } }, // single showSearch: function(showSearchInput) { if (this.showSearchInput === showSearchInput) return; this.showSearchInput = showSearchInput; this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput); this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput); //add "select2-with-searchbox" to the container if search box is shown $(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput); }, // single onSelect: function (data, options) { if (!this.triggerSelect(data)) { return; } var old = this.opts.element.val(), oldData = this.data(); this.opts.element.val(this.id(data)); this.updateSelection(data); this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data }); this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val()); this.close(); if (!options || !options.noFocus) this.selection.focus(); if (!equal(old, this.id(data))) { this.triggerChange({added:data,removed:oldData}); } }, // single updateSelection: function (data) { var container=this.selection.find(".select2-chosen"), formatted, cssClass; this.selection.data("select2-data", data); container.empty(); if (data !== null) { formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup); } if (formatted !== undefined) { container.append(formatted); } cssClass=this.opts.formatSelectionCssClass(data, container); if (cssClass !== undefined) { container.addClass(cssClass); } this.selection.removeClass("select2-default"); if (this.opts.allowClear && this.getPlaceholder() !== undefined) { this.container.addClass("select2-allowclear"); } }, // single val: function () { var val, triggerChange = false, data = null, self = this, oldData = this.data(); if (arguments.length === 0) { return this.opts.element.val(); } val = arguments[0]; if (arguments.length > 1) { triggerChange = arguments[1]; } if (this.select) { this.select .val(val) .find(":selected").each2(function (i, elm) { data = self.optionToData(elm); return false; }); this.updateSelection(data); this.setPlaceholder(); if (triggerChange) { this.triggerChange({added: data, removed:oldData}); } } else { // val is an id. !val is true for [undefined,null,'',0] - 0 is legal if (!val && val !== 0) { this.clear(triggerChange); return; } if (this.opts.initSelection === undefined) { throw new Error("cannot call val() if initSelection() is not defined"); } this.opts.element.val(val); this.opts.initSelection(this.opts.element, function(data){ self.opts.element.val(!data ? "" : self.id(data)); self.updateSelection(data); self.setPlaceholder(); if (triggerChange) { self.triggerChange({added: data, removed:oldData}); } }); } }, // single clearSearch: function () { this.search.val(""); this.focusser.val(""); }, // single data: function(value) { var data, triggerChange = false; if (arguments.length === 0) { data = this.selection.data("select2-data"); if (data == undefined) data = null; return data; } else { if (arguments.length > 1) { triggerChange = arguments[1]; } if (!value) { this.clear(triggerChange); } else { data = this.data(); this.opts.element.val(!value ? "" : this.id(value)); this.updateSelection(value); if (triggerChange) { this.triggerChange({added: value, removed:data}); } } } } }); MultiSelect2 = clazz(AbstractSelect2, { // multi createContainer: function () { var container = $(document.createElement("div")).attr({ "class": "select2-container select2-container-multi" }).html([ "<ul class='select2-choices'>", " <li class='select2-search-field'>", " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>", " </li>", "</ul>", "<div class='select2-drop select2-drop-multi select2-display-none'>", " <ul class='select2-results'>", " </ul>", "</div>"].join("")); return container; }, // multi prepareOpts: function () { var opts = this.parent.prepareOpts.apply(this, arguments), self=this; // TODO validate placeholder is a string if specified if (opts.element.get(0).tagName.toLowerCase() === "select") { // install sthe selection initializer opts.initSelection = function (element, callback) { var data = []; element.find(":selected").each2(function (i, elm) { data.push(self.optionToData(elm)); }); callback(data); }; } else if ("data" in opts) { // install default initSelection when applied to hidden input and data is local opts.initSelection = opts.initSelection || function (element, callback) { var ids = splitVal(element.val(), opts.separator); //search in data by array of ids, storing matching items in a list var matches = []; opts.query({ matcher: function(term, text, el){ var is_match = $.grep(ids, function(id) { return equal(id, opts.id(el)); }).length; if (is_match) { matches.push(el); } return is_match; }, callback: !$.isFunction(callback) ? $.noop : function() { // reorder matches based on the order they appear in the ids array because right now // they are in the order in which they appear in data array var ordered = []; for (var i = 0; i < ids.length; i++) { var id = ids[i]; for (var j = 0; j < matches.length; j++) { var match = matches[j]; if (equal(id, opts.id(match))) { ordered.push(match); matches.splice(j, 1); break; } } } callback(ordered); } }); }; } return opts; }, selectChoice: function (choice) { var selected = this.container.find(".select2-search-choice-focus"); if (selected.length && choice && choice[0] == selected[0]) { } else { if (selected.length) { this.opts.element.trigger("choice-deselected", selected); } selected.removeClass("select2-search-choice-focus"); if (choice && choice.length) { this.close(); choice.addClass("select2-search-choice-focus"); this.opts.element.trigger("choice-selected", choice); } } }, // multi destroy: function() { $("label[for='" + this.search.attr('id') + "']") .attr('for', this.opts.element.attr("id")); this.parent.destroy.apply(this, arguments); }, // multi initContainer: function () { var selector = ".select2-choices", selection; this.searchContainer = this.container.find(".select2-search-field"); this.selection = selection = this.container.find(selector); var _this = this; this.selection.on("click", ".select2-search-choice", function (e) { //killEvent(e); _this.search[0].focus(); _this.selectChoice($(this)); }); // rewrite labels from original element to focusser this.search.attr("id", "s2id_autogen"+nextUid()); $("label[for='" + this.opts.element.attr("id") + "']") .attr('for', this.search.attr('id')); this.search.on("input paste", this.bind(function() { if (!this.isInterfaceEnabled()) return; if (!this.opened()) { this.open(); } })); this.search.attr("tabindex", this.elementTabIndex); this.keydowns = 0; this.search.on("keydown", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; ++this.keydowns; var selected = selection.find(".select2-search-choice-focus"); var prev = selected.prev(".select2-search-choice:not(.select2-locked)"); var next = selected.next(".select2-search-choice:not(.select2-locked)"); var pos = getCursorInfo(this.search); if (selected.length && (e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) { var selectedChoice = selected; if (e.which == KEY.LEFT && prev.length) { selectedChoice = prev; } else if (e.which == KEY.RIGHT) { selectedChoice = next.length ? next : null; } else if (e.which === KEY.BACKSPACE) { this.unselect(selected.first()); this.search.width(10); selectedChoice = prev.length ? prev : next; } else if (e.which == KEY.DELETE) { this.unselect(selected.first()); this.search.width(10); selectedChoice = next.length ? next : null; } else if (e.which == KEY.ENTER) { selectedChoice = null; } this.selectChoice(selectedChoice); killEvent(e); if (!selectedChoice || !selectedChoice.length) { this.open(); } return; } else if (((e.which === KEY.BACKSPACE && this.keydowns == 1) || e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) { this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last()); killEvent(e); return; } else { this.selectChoice(null); } if (this.opened()) { switch (e.which) { case KEY.UP: case KEY.DOWN: this.moveHighlight((e.which === KEY.UP) ? -1 : 1); killEvent(e); return; case KEY.ENTER: this.selectHighlighted(); killEvent(e); return; case KEY.TAB: // if selectOnBlur == true, select the currently highlighted option if (this.opts.selectOnBlur) { this.selectHighlighted({noFocus:true}); } this.close(); return; case KEY.ESC: this.cancel(e); killEvent(e); return; } } if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) { return; } if (e.which === KEY.ENTER) { if (this.opts.openOnEnter === false) { return; } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) { return; } } this.open(); if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) { // prevent the page from scrolling killEvent(e); } if (e.which === KEY.ENTER) { // prevent form from being submitted killEvent(e); } })); this.search.on("keyup", this.bind(function (e) { this.keydowns = 0; this.resizeSearch(); }) ); this.search.on("blur", this.bind(function(e) { this.container.removeClass("select2-container-active"); this.search.removeClass("select2-focused"); this.selectChoice(null); if (!this.opened()) this.clearSearch(); e.stopImmediatePropagation(); this.opts.element.trigger($.Event("select2-blur")); })); this.container.on("click", selector, this.bind(function (e) { if (!this.isInterfaceEnabled()) return; if ($(e.target).closest(".select2-search-choice").length > 0) { // clicked inside a select2 search choice, do not open return; } this.selectChoice(null); this.clearPlaceholder(); if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.open(); this.focusSearch(); e.preventDefault(); })); this.container.on("focus", selector, this.bind(function () { if (!this.isInterfaceEnabled()) return; if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.container.addClass("select2-container-active"); this.dropdown.addClass("select2-drop-active"); this.clearPlaceholder(); })); this.initContainerWidth(); this.opts.element.addClass("select2-offscreen"); // set the placeholder if necessary this.clearSearch(); }, // multi enableInterface: function() { if (this.parent.enableInterface.apply(this, arguments)) { this.search.prop("disabled", !this.isInterfaceEnabled()); } }, // multi initSelection: function () { var data; if (this.opts.element.val() === "" && this.opts.element.text() === "") { this.updateSelection([]); this.close(); // set the placeholder if necessary this.clearSearch(); } if (this.select || this.opts.element.val() !== "") { var self = this; this.opts.initSelection.call(null, this.opts.element, function(data){ if (data !== undefined && data !== null) { self.updateSelection(data); self.close(); // set the placeholder if necessary self.clearSearch(); } }); } }, // multi clearSearch: function () { var placeholder = this.getPlaceholder(), maxWidth = this.getMaxSearchWidth(); if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) { this.search.val(placeholder).addClass("select2-default"); // stretch the search box to full width of the container so as much of the placeholder is visible as possible // we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944 this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width")); } else { this.search.val("").width(10); } }, // multi clearPlaceholder: function () { if (this.search.hasClass("select2-default")) { this.search.val("").removeClass("select2-default"); } }, // multi opening: function () { this.clearPlaceholder(); // should be done before super so placeholder is not used to search this.resizeSearch(); this.parent.opening.apply(this, arguments); this.focusSearch(); this.updateResults(true); this.search.focus(); this.opts.element.trigger($.Event("select2-open")); }, // multi close: function () { if (!this.opened()) return; this.parent.close.apply(this, arguments); }, // multi focus: function () { this.close(); this.search.focus(); }, // multi isFocused: function () { return this.search.hasClass("select2-focused"); }, // multi updateSelection: function (data) { var ids = [], filtered = [], self = this; // filter out duplicates $(data).each(function () { if (indexOf(self.id(this), ids) < 0) { ids.push(self.id(this)); filtered.push(this); } }); data = filtered; this.selection.find(".select2-search-choice").remove(); $(data).each(function () { self.addSelectedChoice(this); }); self.postprocessResults(); }, // multi tokenize: function() { var input = this.search.val(); input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts); if (input != null && input != undefined) { this.search.val(input); if (input.length > 0) { this.open(); } } }, // multi onSelect: function (data, options) { if (!this.triggerSelect(data)) { return; } this.addSelectedChoice(data); this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data }); if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true); if (this.opts.closeOnSelect) { this.close(); this.search.width(10); } else { if (this.countSelectableResults()>0) { this.search.width(10); this.resizeSearch(); if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) { // if we reached max selection size repaint the results so choices // are replaced with the max selection reached message this.updateResults(true); } this.positionDropdown(); } else { // if nothing left to select close this.close(); this.search.width(10); } } // since its not possible to select an element that has already been // added we do not need to check if this is a new element before firing change this.triggerChange({ added: data }); if (!options || !options.noFocus) this.focusSearch(); }, // multi cancel: function () { this.close(); this.focusSearch(); }, addSelectedChoice: function (data) { var enableChoice = !data.locked, enabledItem = $( "<li class='select2-search-choice'>" + " <div></div>" + " <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a>" + "</li>"), disabledItem = $( "<li class='select2-search-choice select2-locked'>" + "<div></div>" + "</li>"); var choice = enableChoice ? enabledItem : disabledItem, id = this.id(data), val = this.getVal(), formatted, cssClass; formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup); if (formatted != undefined) { choice.find("div").replaceWith("<div>"+formatted+"</div>"); } cssClass=this.opts.formatSelectionCssClass(data, choice.find("div")); if (cssClass != undefined) { choice.addClass(cssClass); } if(enableChoice){ choice.find(".select2-search-choice-close") .on("mousedown", killEvent) .on("click dblclick", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; $(e.target).closest(".select2-search-choice").fadeOut('fast', this.bind(function(){ this.unselect($(e.target)); this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"); this.close(); this.focusSearch(); })).dequeue(); killEvent(e); })).on("focus", this.bind(function () { if (!this.isInterfaceEnabled()) return; this.container.addClass("select2-container-active"); this.dropdown.addClass("select2-drop-active"); })); } choice.data("select2-data", data); choice.insertBefore(this.searchContainer); val.push(id); this.setVal(val); }, // multi unselect: function (selected) { var val = this.getVal(), data, index; selected = selected.closest(".select2-search-choice"); if (selected.length === 0) { throw "Invalid argument: " + selected + ". Must be .select2-search-choice"; } data = selected.data("select2-data"); if (!data) { // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued // and invoked on an element already removed return; } index = indexOf(this.id(data), val); if (index >= 0) { val.splice(index, 1); this.setVal(val); if (this.select) this.postprocessResults(); } selected.remove(); this.opts.element.trigger({ type: "removed", val: this.id(data), choice: data }); this.triggerChange({ removed: data }); }, // multi postprocessResults: function (data, initial, noHighlightUpdate) { var val = this.getVal(), choices = this.results.find(".select2-result"), compound = this.results.find(".select2-result-with-children"), self = this; choices.each2(function (i, choice) { var id = self.id(choice.data("select2-data")); if (indexOf(id, val) >= 0) { choice.addClass("select2-selected"); // mark all children of the selected parent as selected choice.find(".select2-result-selectable").addClass("select2-selected"); } }); compound.each2(function(i, choice) { // hide an optgroup if it doesnt have any selectable children if (!choice.is('.select2-result-selectable') && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) { choice.addClass("select2-selected"); } }); if (this.highlight() == -1 && noHighlightUpdate !== false){ self.highlight(0); } //If all results are chosen render formatNoMAtches if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){ if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) { if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) { this.results.append("<li class='select2-no-results'>" + self.opts.formatNoMatches(self.search.val()) + "</li>"); } } } }, // multi getMaxSearchWidth: function() { return this.selection.width() - getSideBorderPadding(this.search); }, // multi resizeSearch: function () { var minimumWidth, left, maxWidth, containerLeft, searchWidth, sideBorderPadding = getSideBorderPadding(this.search); minimumWidth = measureTextWidth(this.search) + 10; left = this.search.offset().left; maxWidth = this.selection.width(); containerLeft = this.selection.offset().left; searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding; if (searchWidth < minimumWidth) { searchWidth = maxWidth - sideBorderPadding; } if (searchWidth < 40) { searchWidth = maxWidth - sideBorderPadding; } if (searchWidth <= 0) { searchWidth = minimumWidth; } this.search.width(searchWidth); }, // multi getVal: function () { var val; if (this.select) { val = this.select.val(); return val === null ? [] : val; } else { val = this.opts.element.val(); return splitVal(val, this.opts.separator); } }, // multi setVal: function (val) { var unique; if (this.select) { this.select.val(val); } else { unique = []; // filter out duplicates $(val).each(function () { if (indexOf(this, unique) < 0) unique.push(this); }); this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator)); } }, // multi buildChangeDetails: function (old, current) { var current = current.slice(0), old = old.slice(0); // remove intersection from each array for (var i = 0; i < current.length; i++) { for (var j = 0; j < old.length; j++) { if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) { current.splice(i, 1); i--; old.splice(j, 1); j--; } } } return {added: current, removed: old}; }, // multi val: function (val, triggerChange) { var oldData, self=this, changeDetails; if (arguments.length === 0) { return this.getVal(); } oldData=this.data(); if (!oldData.length) oldData=[]; // val is an id. !val is true for [undefined,null,'',0] - 0 is legal if (!val && val !== 0) { this.opts.element.val(""); this.updateSelection([]); this.clearSearch(); if (triggerChange) { this.triggerChange({added: this.data(), removed: oldData}); } return; } // val is a list of ids this.setVal(val); if (this.select) { this.opts.initSelection(this.select, this.bind(this.updateSelection)); if (triggerChange) { this.triggerChange(this.buildChangeDetails(oldData, this.data())); } } else { if (this.opts.initSelection === undefined) { throw new Error("val() cannot be called if initSelection() is not defined"); } this.opts.initSelection(this.opts.element, function(data){ var ids=$.map(data, self.id); self.setVal(ids); self.updateSelection(data); self.clearSearch(); if (triggerChange) { self.triggerChange(self.buildChangeDetails(oldData, this.data())); } }); } this.clearSearch(); }, // multi onSortStart: function() { if (this.select) { throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead."); } // collapse search field into 0 width so its container can be collapsed as well this.search.width(0); // hide the container this.searchContainer.hide(); }, // multi onSortEnd:function() { var val=[], self=this; // show search and move it to the end of the list this.searchContainer.show(); // make sure the search container is the last item in the list this.searchContainer.appendTo(this.searchContainer.parent()); // since we collapsed the width in dragStarted, we resize it here this.resizeSearch(); // update selection this.selection.find(".select2-search-choice").each(function() { val.push(self.opts.id($(this).data("select2-data"))); }); this.setVal(val); this.triggerChange(); }, // multi data: function(values, triggerChange) { var self=this, ids, old; if (arguments.length === 0) { return this.selection .find(".select2-search-choice") .map(function() { return $(this).data("select2-data"); }) .get(); } else { old = this.data(); if (!values) { values = []; } ids = $.map(values, function(e) { return self.opts.id(e); }); this.setVal(ids); this.updateSelection(values); this.clearSearch(); if (triggerChange) { this.triggerChange(this.buildChangeDetails(old, this.data())); } } } }); $.fn.select2 = function () { var args = Array.prototype.slice.call(arguments, 0), opts, select2, method, value, multiple, allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"], valueMethods = ["opened", "isFocused", "container", "dropdown"], propertyMethods = ["val", "data"], methodsMap = { search: "externalSearch" }; this.each(function () { if (args.length === 0 || typeof(args[0]) === "object") { opts = args.length === 0 ? {} : $.extend({}, args[0]); opts.element = $(this); if (opts.element.get(0).tagName.toLowerCase() === "select") { multiple = opts.element.prop("multiple"); } else { multiple = opts.multiple || false; if ("tags" in opts) {opts.multiple = multiple = true;} } select2 = multiple ? new MultiSelect2() : new SingleSelect2(); select2.init(opts); } else if (typeof(args[0]) === "string") { if (indexOf(args[0], allowedMethods) < 0) { throw "Unknown method: " + args[0]; } value = undefined; select2 = $(this).data("select2"); if (select2 === undefined) return; method=args[0]; if (method === "container") { value = select2.container; } else if (method === "dropdown") { value = select2.dropdown; } else { if (methodsMap[method]) method = methodsMap[method]; value = select2[method].apply(select2, args.slice(1)); } if (indexOf(args[0], valueMethods) >= 0 || (indexOf(args[0], propertyMethods) && args.length == 1)) { return false; // abort the iteration, ready to return first matched value } } else { throw "Invalid arguments to select2 plugin: " + args; } }); return (value === undefined) ? this : value; }; // plugin defaults, accessible to users $.fn.select2.defaults = { width: "copy", loadMorePadding: 0, closeOnSelect: true, openOnEnter: true, containerCss: {}, dropdownCss: {}, containerCssClass: "", dropdownCssClass: "", formatResult: function(result, container, query, escapeMarkup) { var markup=[]; markMatch(result.text, query.term, markup, escapeMarkup); return markup.join(""); }, formatSelection: function (data, container, escapeMarkup) { return data ? escapeMarkup(data.text) : undefined; }, sortResults: function (results, container, query) { return results; }, formatResultCssClass: function(data) {return undefined;}, formatSelectionCssClass: function(data, container) {return undefined;}, formatNoMatches: function () { return "No matches found"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " more character" + (n == 1? "" : "s"); }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); }, formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); }, formatLoadMore: function (pageNumber) { return "Loading more results..."; }, formatSearching: function () { return "Searching..."; }, minimumResultsForSearch: 0, minimumInputLength: 0, maximumInputLength: null, maximumSelectionSize: 0, id: function (e) { return e.id; }, matcher: function(term, text) { return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0; }, separator: ",", tokenSeparators: [], tokenizer: defaultTokenizer, escapeMarkup: defaultEscapeMarkup, blurOnChange: false, selectOnBlur: false, adaptContainerCssClass: function(c) { return c; }, adaptDropdownCssClass: function(c) { return null; }, nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; } }; $.fn.select2.ajaxDefaults = { transport: $.ajax, params: { type: "GET", cache: false, dataType: "json" } }; // exports window.Select2 = { query: { ajax: ajax, local: local, tags: tags }, util: { debounce: debounce, markMatch: markMatch, escapeMarkup: defaultEscapeMarkup, stripDiacritics: stripDiacritics }, "class": { "abstract": AbstractSelect2, "single": SingleSelect2, "multi": MultiSelect2 } }; }(jQuery));
JavaScript
/** * Select2 Latvian translation */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Sakritību nav"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Lūdzu ievadiet vēl " + n + " simbol" + (n == 11 ? "us" : (/^\d*[1]$/im.test(n)? "u" : "us")); }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Lūdzu ievadiet par " + n + " simbol" + (n == 11 ? "iem" : (/^\d*[1]$/im.test(n)? "u" : "iem")) + " mazāk"; }, formatSelectionTooBig: function (limit) { return "Jūs varat izvēlēties ne vairāk kā " + limit + " element" + (limit == 11 ? "us" : (/^\d*[1]$/im.test(limit)? "u" : "us")); }, formatLoadMore: function (pageNumber) { return "Datu ielāde..."; }, formatSearching: function () { return "Meklēšana..."; } }); })(jQuery);
JavaScript
/** * Select2 Traditional Chinese translation */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "沒有找到相符的項目"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "請再輸入" + n + "個字元";}, formatInputTooLong: function (input, max) { var n = input.length - max; return "請刪掉" + n + "個字元";}, formatSelectionTooBig: function (limit) { return "你只能選擇最多" + limit + "項"; }, formatLoadMore: function (pageNumber) { return "載入中..."; }, formatSearching: function () { return "搜尋中..."; } }); })(jQuery);
JavaScript
/** * Select2 Slovak translation. * * Author: David Vallner <david@vallner.net> */ (function ($) { "use strict"; // use text for the numbers 2 through 4 var smallNumbers = { 2: function(masc) { return (masc ? "dva" : "dve"); }, 3: function() { return "tri"; }, 4: function() { return "štyri"; } } $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Nenašli sa žiadne položky"; }, formatInputTooShort: function (input, min) { var n = min - input.length; if (n == 1) { return "Prosím zadajte ešte jeden znak"; } else if (n <= 4) { return "Prosím zadajte ešte ďalšie "+smallNumbers[n](true)+" znaky"; } else { return "Prosím zadajte ešte ďalších "+n+" znakov"; } }, formatInputTooLong: function (input, max) { var n = input.length - max; if (n == 1) { return "Prosím zadajte o jeden znak menej"; } else if (n <= 4) { return "Prosím zadajte o "+smallNumbers[n](true)+" znaky menej"; } else { return "Prosím zadajte o "+n+" znakov menej"; } }, formatSelectionTooBig: function (limit) { if (limit == 1) { return "Môžete zvoliť len jednu položku"; } else if (limit <= 4) { return "Môžete zvoliť najviac "+smallNumbers[limit](false)+" položky"; } else { return "Môžete zvoliť najviac "+limit+" položiek"; } }, formatLoadMore: function (pageNumber) { return "Načítavajú sa ďalšie výsledky..."; }, formatSearching: function () { return "Vyhľadávanie..."; } }); })(jQuery);
JavaScript
/** * Select2 German translation */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Keine Übereinstimmungen gefunden"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Bitte " + n + " Zeichen mehr eingeben"; }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Bitte " + n + " Zeichen weniger eingeben"; }, formatSelectionTooBig: function (limit) { return "Sie können nur " + limit + " Eintr" + (limit === 1 ? "ag" : "äge") + " auswählen"; }, formatLoadMore: function (pageNumber) { return "Lade mehr Ergebnisse..."; }, formatSearching: function () { return "Suche..."; } }); })(jQuery);
JavaScript
/** * Select2 Malay translation. * * Author: Kepoweran <kepoweran@gmail.com> */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Tiada padanan yang ditemui"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Sila masukkan " + n + " aksara lagi"; }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Sila hapuskan " + n + " aksara"; }, formatSelectionTooBig: function (limit) { return "Anda hanya boleh memilih " + limit + " pilihan"; }, formatLoadMore: function (pageNumber) { return "Sedang memuatkan keputusan..."; }, formatSearching: function () { return "Mencari..."; } }); })(jQuery);
JavaScript
/** * Select2 <Language> translation. * * Author: Your Name <your@email> */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Δεν βρέθηκαν αποτελέσματα"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Παρακαλούμε εισάγετε " + n + " περισσότερους χαρακτήρες" + (n == 1 ? "" : "s"); }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Παρακαλούμε διαγράψτε " + n + " χαρακτήρες" + (n == 1 ? "" : "s"); }, formatSelectionTooBig: function (limit) { return "Μπορείτε να επιλέξετε μόνο " + limit + " αντικείμενο" + (limit == 1 ? "" : "s"); }, formatLoadMore: function (pageNumber) { return "Φόρτωση περισσότερων..."; }, formatSearching: function () { return "Αναζήτηση..."; } }); })(jQuery);
JavaScript
/** * Select2 Croatian translation. * * Author: Edi Modrić <edi.modric@gmail.com> */ (function ($) { "use strict"; var specialNumbers = { 1: function(n) { return (n % 100 != 11 ? "znak" : "znakova"); }, 2: function(n) { return (n % 100 != 12 ? "znaka" : "znakova"); }, 3: function(n) { return (n % 100 != 13 ? "znaka" : "znakova"); }, 4: function(n) { return (n % 100 != 14 ? "znaka" : "znakova"); } }; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Nema rezultata"; }, formatInputTooShort: function (input, min) { var n = min - input.length; var nMod10 = n % 10; if (nMod10 > 0 && nMod10 < 5) { return "Unesite još " + n + " " + specialNumbers[nMod10](n); } return "Unesite još " + n + " znakova"; }, formatInputTooLong: function (input, max) { var n = input.length - max; var nMod10 = n % 10; if (nMod10 > 0 && nMod10 < 5) { return "Unesite " + n + " " + specialNumbers[nMod10](n) + " manje"; } return "Unesite " + n + " znakova manje"; }, formatSelectionTooBig: function (limit) { return "Maksimalan broj odabranih stavki je " + limit; }, formatLoadMore: function (pageNumber) { return "Učitavanje rezultata..."; }, formatSearching: function () { return "Pretraga..."; } }); })(jQuery);
JavaScript
/** * Select2 Basque translation. * * Author: Julen Ruiz Aizpuru <julenx at gmail dot com> */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Ez da bat datorrenik aurkitu"; }, formatInputTooShort: function (input, min) { var n = min - input.length; if (n === 1) { return "Idatzi karaktere bat gehiago"; } else { return "Idatzi " + n + " karaktere gehiago"; } }, formatInputTooLong: function (input, max) { var n = input.length - max; if (n === 1) { return "Idatzi karaktere bat gutxiago"; } else { return "Idatzi " + n + " karaktere gutxiago"; } }, formatSelectionTooBig: function (limit) { if (limit === 1 ) { return "Elementu bakarra hauta dezakezu"; } else { return limit + " elementu hauta ditzakezu soilik"; } }, formatLoadMore: function (pageNumber) { return "Emaitza gehiago kargatzen..."; }, formatSearching: function () { return "Bilatzen..."; } }); })(jQuery);
JavaScript
/** * Select2 Turkish translation. * * Author: Salim KAYABAŞI <salim.kayabasi@gmail.com> */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Sonuç bulunamadı"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "En az " + n + " karakter daha girmelisiniz"; }, formatInputTooLong: function (input, max) { var n = input.length - max; return n + " karakter azaltmalısınız"; }, formatSelectionTooBig: function (limit) { return "Sadece " + limit + " seçim yapabilirsiniz"; }, formatLoadMore: function (pageNumber) { return "Daha fazla..."; }, formatSearching: function () { return "Aranıyor..."; } }); })(jQuery);
JavaScript
/** * Select2 Romanian translation. */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Nu a fost găsit nimic"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Vă rugăm să introduceți incă " + n + " caracter" + (n == 1 ? "" : "e"); }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Vă rugăm să introduceți mai puțin de " + n + " caracter" + (n == 1? "" : "e"); }, formatSelectionTooBig: function (limit) { return "Aveți voie să selectați cel mult " + limit + " element" + (limit == 1 ? "" : "e"); }, formatLoadMore: function (pageNumber) { return "Se încarcă..."; }, formatSearching: function () { return "Căutare..."; } }); })(jQuery);
JavaScript
/** * Select2 <Language> translation. * * Author: Swen Mun <longfinfunnel@gmail.com> */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "결과 없음"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "너무 짧습니다. "+n+"글자 더 입력해주세요."; }, formatInputTooLong: function (input, max) { var n = input.length - max; return "너무 깁니다. "+n+"글자 지워주세요."; }, formatSelectionTooBig: function (limit) { return "최대 "+limit+"개까지만 선택하실 수 있습니다."; }, formatLoadMore: function (pageNumber) { return "불러오는 중…"; }, formatSearching: function () { return "검색 중…"; } }); })(jQuery);
JavaScript
/** * Select2 Icelandic translation. * */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Ekkert fannst"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Vinsamlegast skrifið " + n + " staf" + (n == 1 ? "" : "i") + " í viðbót"; }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Vinsamlegast styttið texta um " + n + " staf" + (n == 1 ? "" : "i"); }, formatSelectionTooBig: function (limit) { return "Þú getur aðeins valið " + limit + " atriði"; }, formatLoadMore: function (pageNumber) { return "Sæki fleiri niðurstöður..."; }, formatSearching: function () { return "Leita..."; } }); })(jQuery);
JavaScript
/** * Select2 Estonian translation. * * Author: Kuldar Kalvik <kuldar@kalvik.ee> */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Tulemused puuduvad"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Sisesta " + n + " täht" + (n == 1 ? "" : "e") + " rohkem"; }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Sisesta " + n + " täht" + (n == 1? "" : "e") + " vähem"; }, formatSelectionTooBig: function (limit) { return "Saad vaid " + limit + " tulemus" + (limit == 1 ? "e" : "t") + " valida"; }, formatLoadMore: function (pageNumber) { return "Laen tulemusi.."; }, formatSearching: function () { return "Otsin.."; } }); })(jQuery);
JavaScript
/** * Select2 Galician translation * * Author: Leandro Regueiro <leandro.regueiro@gmail.com> */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Non se atoparon resultados"; }, formatInputTooShort: function (input, min) { var n = min - input.length; if (n === 1) { return "Engada un carácter"; } else { return "Engada " + n + " caracteres"; } }, formatInputTooLong: function (input, max) { var n = input.length - max; if (n === 1) { return "Elimine un carácter"; } else { return "Elimine " + n + " caracteres"; } }, formatSelectionTooBig: function (limit) { if (limit === 1 ) { return "Só pode seleccionar un elemento"; } else { return "Só pode seleccionar " + limit + " elementos"; } }, formatLoadMore: function (pageNumber) { return "Cargando máis resultados..."; }, formatSearching: function () { return "Buscando..."; } }); })(jQuery);
JavaScript
/** * Select2 Vietnamese translation. * * Author: Long Nguyen <olragon@gmail.com> */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Không tìm thấy kết quả"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Vui lòng nhập nhiều hơn " + n + " ký tự" + (n == 1 ? "" : "s"); }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Vui lòng nhập ít hơn " + n + " ký tự" + (n == 1? "" : "s"); }, formatSelectionTooBig: function (limit) { return "Chỉ có thể chọn được " + limit + " tùy chọn" + (limit == 1 ? "" : "s"); }, formatLoadMore: function (pageNumber) { return "Đang lấy thêm kết quả..."; }, formatSearching: function () { return "Đang tìm..."; } }); })(jQuery);
JavaScript