code
stringlengths
1
2.08M
language
stringclasses
1 value
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.Preview', { init : function(ed, url) { var t = this, css = tinymce.explode(ed.settings.content_css); t.editor = ed; // Force absolute CSS urls tinymce.each(css, function(u, k) { css[k] = ed.documentBaseURI.toAbsolute(u); }); ed.addCommand('mcePreview', function() { ed.windowManager.open({ file : ed.getParam("plugin_preview_pageurl", url + "/preview.html"), width : parseInt(ed.getParam("plugin_preview_width", "550")), height : parseInt(ed.getParam("plugin_preview_height", "600")), resizable : "yes", scrollbars : "yes", popup_css : css ? css.join(',') : ed.baseURI.toAbsolute("themes/" + ed.settings.theme + "/skins/" + ed.settings.skin + "/content.css"), inline : ed.getParam("plugin_preview_inline", 1) }, { base : ed.documentBaseURI.getURI() }); }); ed.addButton('preview', {title : 'preview.preview_desc', cmd : 'mcePreview'}); }, getInfo : function() { return { longname : 'Preview', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/preview', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('preview', tinymce.plugins.Preview); })();
JavaScript
/** * This script contains embed functions for common plugins. This scripts are complety free to use for any purpose. */ function writeFlash(p) { writeEmbed( 'D27CDB6E-AE6D-11cf-96B8-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'application/x-shockwave-flash', p ); } function writeShockWave(p) { writeEmbed( '166B1BCA-3F9C-11CF-8075-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0', 'application/x-director', p ); } function writeQuickTime(p) { writeEmbed( '02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0', 'video/quicktime', p ); } function writeRealMedia(p) { writeEmbed( 'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'audio/x-pn-realaudio-plugin', p ); } function writeWindowsMedia(p) { p.url = p.src; writeEmbed( '6BF52A52-394A-11D3-B153-00C04F79FAA6', 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701', 'application/x-mplayer2', p ); } function writeEmbed(cls, cb, mt, p) { var h = '', n; h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"'; h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : ''; h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : ''; h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : ''; h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : ''; h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : ''; h += '>'; for (n in p) h += '<param name="' + n + '" value="' + p[n] + '">'; h += '<embed type="' + mt + '"'; for (n in p) h += n + '="' + p[n] + '" '; h += '></embed></object>'; document.write(h); }
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var Event = tinymce.dom.Event, each = tinymce.each, DOM = tinymce.DOM; /** * This plugin a context menu to TinyMCE editor instances. * * @class tinymce.plugins.ContextMenu */ tinymce.create('tinymce.plugins.ContextMenu', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @method init * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed) { var t = this, showMenu, contextmenuNeverUseNative, realCtrlKey, hideMenu; t.editor = ed; contextmenuNeverUseNative = ed.settings.contextmenu_never_use_native; /** * This event gets fired when the context menu is shown. * * @event onContextMenu * @param {tinymce.plugins.ContextMenu} sender Plugin instance sending the event. * @param {tinymce.ui.DropMenu} menu Drop down menu to fill with more items if needed. */ t.onContextMenu = new tinymce.util.Dispatcher(this); hideMenu = function(e) { hide(ed, e); }; showMenu = ed.onContextMenu.add(function(ed, e) { // Block TinyMCE menu on ctrlKey and work around Safari issue if ((realCtrlKey !== 0 ? realCtrlKey : e.ctrlKey) && !contextmenuNeverUseNative) return; Event.cancel(e); // Select the image if it's clicked. WebKit would other wise expand the selection if (e.target.nodeName == 'IMG') ed.selection.select(e.target); t._getMenu(ed).showMenu(e.clientX || e.pageX, e.clientY || e.pageY); Event.add(ed.getDoc(), 'click', hideMenu); ed.nodeChanged(); }); ed.onRemove.add(function() { if (t._menu) t._menu.removeAll(); }); function hide(ed, e) { realCtrlKey = 0; // Since the contextmenu event moves // the selection we need to store it away if (e && e.button == 2) { realCtrlKey = e.ctrlKey; return; } if (t._menu) { t._menu.removeAll(); t._menu.destroy(); Event.remove(ed.getDoc(), 'click', hideMenu); t._menu = null; } }; ed.onMouseDown.add(hide); ed.onKeyDown.add(hide); ed.onKeyDown.add(function(ed, e) { if (e.shiftKey && !e.ctrlKey && !e.altKey && e.keyCode === 121) { Event.cancel(e); showMenu(ed, e); } }); }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @method getInfo * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'Contextmenu', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/contextmenu', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, _getMenu : function(ed) { var t = this, m = t._menu, se = ed.selection, col = se.isCollapsed(), el = se.getNode() || ed.getBody(), am, p; if (m) { m.removeAll(); m.destroy(); } p = DOM.getPos(ed.getContentAreaContainer()); m = ed.controlManager.createDropMenu('contextmenu', { offset_x : p.x + ed.getParam('contextmenu_offset_x', 0), offset_y : p.y + ed.getParam('contextmenu_offset_y', 0), constrain : 1, keyboard_focus: true }); t._menu = m; m.add({title : 'advanced.cut_desc', icon : 'cut', cmd : 'Cut'}).setDisabled(col); m.add({title : 'advanced.copy_desc', icon : 'copy', cmd : 'Copy'}).setDisabled(col); m.add({title : 'advanced.paste_desc', icon : 'paste', cmd : 'Paste'}); if ((el.nodeName == 'A' && !ed.dom.getAttrib(el, 'name')) || !col) { m.addSeparator(); m.add({title : 'advanced.link_desc', icon : 'link', cmd : ed.plugins.advlink ? 'mceAdvLink' : 'mceLink', ui : true}); m.add({title : 'advanced.unlink_desc', icon : 'unlink', cmd : 'UnLink'}); } m.addSeparator(); m.add({title : 'advanced.image_desc', icon : 'image', cmd : ed.plugins.advimage ? 'mceAdvImage' : 'mceImage', ui : true}); m.addSeparator(); am = m.addMenu({title : 'contextmenu.align'}); am.add({title : 'contextmenu.left', icon : 'justifyleft', cmd : 'JustifyLeft'}); am.add({title : 'contextmenu.center', icon : 'justifycenter', cmd : 'JustifyCenter'}); am.add({title : 'contextmenu.right', icon : 'justifyright', cmd : 'JustifyRight'}); am.add({title : 'contextmenu.full', icon : 'justifyfull', cmd : 'JustifyFull'}); t.onContextMenu.dispatch(t, m, el, col); return m; } }); // Register plugin tinymce.PluginManager.add('contextmenu', tinymce.plugins.ContextMenu); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2011, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.AutolinkPlugin', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { var t = this; // Add a key down handler ed.onKeyDown.addToTop(function(ed, e) { if (e.keyCode == 13) return t.handleEnter(ed); }); // Internet Explorer has built-in automatic linking for most cases if (tinyMCE.isIE) return; ed.onKeyPress.add(function(ed, e) { if (e.which == 41) return t.handleEclipse(ed); }); // Add a key up handler ed.onKeyUp.add(function(ed, e) { if (e.keyCode == 32) return t.handleSpacebar(ed); }); }, handleEclipse : function(ed) { this.parseCurrentLine(ed, -1, '(', true); }, handleSpacebar : function(ed) { this.parseCurrentLine(ed, 0, '', true); }, handleEnter : function(ed) { this.parseCurrentLine(ed, -1, '', false); }, parseCurrentLine : function(ed, end_offset, delimiter, goback) { var r, end, start, endContainer, bookmark, text, matches, prev, len; // We need at least five characters to form a URL, // hence, at minimum, five characters from the beginning of the line. r = ed.selection.getRng(true).cloneRange(); if (r.startOffset < 5) { // During testing, the caret is placed inbetween two text nodes. // The previous text node contains the URL. prev = r.endContainer.previousSibling; if (prev == null) { if (r.endContainer.firstChild == null || r.endContainer.firstChild.nextSibling == null) return; prev = r.endContainer.firstChild.nextSibling; } len = prev.length; r.setStart(prev, len); r.setEnd(prev, len); if (r.endOffset < 5) return; end = r.endOffset; endContainer = prev; } else { endContainer = r.endContainer; // Get a text node if (endContainer.nodeType != 3 && endContainer.firstChild) { while (endContainer.nodeType != 3 && endContainer.firstChild) endContainer = endContainer.firstChild; // Move range to text node if (endContainer.nodeType == 3) { r.setStart(endContainer, 0); r.setEnd(endContainer, endContainer.nodeValue.length); } } if (r.endOffset == 1) end = 2; else end = r.endOffset - 1 - end_offset; } start = end; do { // Move the selection one character backwards. r.setStart(endContainer, end >= 2 ? end - 2 : 0); r.setEnd(endContainer, end >= 1 ? end - 1 : 0); end -= 1; // Loop until one of the following is found: a blank space, &nbsp;, delimeter, (end-2) >= 0 } while (r.toString() != ' ' && r.toString() != '' && r.toString().charCodeAt(0) != 160 && (end -2) >= 0 && r.toString() != delimiter); if (r.toString() == delimiter || r.toString().charCodeAt(0) == 160) { r.setStart(endContainer, end); r.setEnd(endContainer, start); end += 1; } else if (r.startOffset == 0) { r.setStart(endContainer, 0); r.setEnd(endContainer, start); } else { r.setStart(endContainer, end); r.setEnd(endContainer, start); } // Exclude last . from word like "www.site.com." var text = r.toString(); if (text.charAt(text.length - 1) == '.') { r.setEnd(endContainer, start - 1); } text = r.toString(); matches = text.match(/^(https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.|(?:mailto:)?[A-Z0-9._%+-]+@)(.+)$/i); if (matches) { if (matches[1] == 'www.') { matches[1] = 'http://www.'; } else if (/@$/.test(matches[1]) && !/^mailto:/.test(matches[1])) { matches[1] = 'mailto:' + matches[1]; } bookmark = ed.selection.getBookmark(); ed.selection.setRng(r); tinyMCE.execCommand('createlink',false, matches[1] + matches[2]); ed.selection.moveToBookmark(bookmark); ed.nodeChanged(); // TODO: Determine if this is still needed. if (tinyMCE.isWebKit) { // move the caret to its original position ed.selection.collapse(false); var max = Math.min(endContainer.length, start + 1); r.setStart(endContainer, max); r.setEnd(endContainer, max); ed.selection.setRng(r); } } }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'Autolink', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autolink', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('autolink', tinymce.plugins.AutolinkPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { function findParentLayer(node) { do { if (node.className && node.className.indexOf('mceItemLayer') != -1) { return node; } } while (node = node.parentNode); }; tinymce.create('tinymce.plugins.Layer', { init : function(ed, url) { var t = this; t.editor = ed; // Register commands ed.addCommand('mceInsertLayer', t._insertLayer, t); ed.addCommand('mceMoveForward', function() { t._move(1); }); ed.addCommand('mceMoveBackward', function() { t._move(-1); }); ed.addCommand('mceMakeAbsolute', function() { t._toggleAbsolute(); }); // Register buttons ed.addButton('moveforward', {title : 'layer.forward_desc', cmd : 'mceMoveForward'}); ed.addButton('movebackward', {title : 'layer.backward_desc', cmd : 'mceMoveBackward'}); ed.addButton('absolute', {title : 'layer.absolute_desc', cmd : 'mceMakeAbsolute'}); ed.addButton('insertlayer', {title : 'layer.insertlayer_desc', cmd : 'mceInsertLayer'}); ed.onInit.add(function() { var dom = ed.dom; if (tinymce.isIE) ed.getDoc().execCommand('2D-Position', false, true); }); // Remove serialized styles when selecting a layer since it might be changed by a drag operation ed.onMouseUp.add(function(ed, e) { var layer = findParentLayer(e.target); if (layer) { ed.dom.setAttrib(layer, 'data-mce-style', ''); } }); // Fixes edit focus issues with layers on Gecko // This will enable designMode while inside a layer and disable it when outside ed.onMouseDown.add(function(ed, e) { var node = e.target, doc = ed.getDoc(), parent; if (tinymce.isGecko) { if (findParentLayer(node)) { if (doc.designMode !== 'on') { doc.designMode = 'on'; // Repaint caret node = doc.body; parent = node.parentNode; parent.removeChild(node); parent.appendChild(node); } } else if (doc.designMode == 'on') { doc.designMode = 'off'; } } }); ed.onNodeChange.add(t._nodeChange, t); ed.onVisualAid.add(t._visualAid, t); }, getInfo : function() { return { longname : 'Layer', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/layer', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _nodeChange : function(ed, cm, n) { var le, p; le = this._getParentLayer(n); p = ed.dom.getParent(n, 'DIV,P,IMG'); if (!p) { cm.setDisabled('absolute', 1); cm.setDisabled('moveforward', 1); cm.setDisabled('movebackward', 1); } else { cm.setDisabled('absolute', 0); cm.setDisabled('moveforward', !le); cm.setDisabled('movebackward', !le); cm.setActive('absolute', le && le.style.position.toLowerCase() == "absolute"); } }, // Private methods _visualAid : function(ed, e, s) { var dom = ed.dom; tinymce.each(dom.select('div,p', e), function(e) { if (/^(absolute|relative|fixed)$/i.test(e.style.position)) { if (s) dom.addClass(e, 'mceItemVisualAid'); else dom.removeClass(e, 'mceItemVisualAid'); dom.addClass(e, 'mceItemLayer'); } }); }, _move : function(d) { var ed = this.editor, i, z = [], le = this._getParentLayer(ed.selection.getNode()), ci = -1, fi = -1, nl; nl = []; tinymce.walk(ed.getBody(), function(n) { if (n.nodeType == 1 && /^(absolute|relative|static)$/i.test(n.style.position)) nl.push(n); }, 'childNodes'); // Find z-indexes for (i=0; i<nl.length; i++) { z[i] = nl[i].style.zIndex ? parseInt(nl[i].style.zIndex) : 0; if (ci < 0 && nl[i] == le) ci = i; } if (d < 0) { // Move back // Try find a lower one for (i=0; i<z.length; i++) { if (z[i] < z[ci]) { fi = i; break; } } if (fi > -1) { nl[ci].style.zIndex = z[fi]; nl[fi].style.zIndex = z[ci]; } else { if (z[ci] > 0) nl[ci].style.zIndex = z[ci] - 1; } } else { // Move forward // Try find a higher one for (i=0; i<z.length; i++) { if (z[i] > z[ci]) { fi = i; break; } } if (fi > -1) { nl[ci].style.zIndex = z[fi]; nl[fi].style.zIndex = z[ci]; } else nl[ci].style.zIndex = z[ci] + 1; } ed.execCommand('mceRepaint'); }, _getParentLayer : function(n) { return this.editor.dom.getParent(n, function(n) { return n.nodeType == 1 && /^(absolute|relative|static)$/i.test(n.style.position); }); }, _insertLayer : function() { var ed = this.editor, dom = ed.dom, p = dom.getPos(dom.getParent(ed.selection.getNode(), '*')), body = ed.getBody(); ed.dom.add(body, 'div', { style : { position : 'absolute', left : p.x, top : (p.y > 20 ? p.y : 20), width : 100, height : 100 }, 'class' : 'mceItemVisualAid mceItemLayer' }, ed.selection.getContent() || ed.getLang('layer.content')); // Workaround for IE where it messes up the JS engine if you insert a layer on IE 6,7 if (tinymce.isIE) dom.setHTML(body, body.innerHTML); }, _toggleAbsolute : function() { var ed = this.editor, le = this._getParentLayer(ed.selection.getNode()); if (!le) le = ed.dom.getParent(ed.selection.getNode(), 'DIV,P,IMG'); if (le) { if (le.style.position.toLowerCase() == "absolute") { ed.dom.setStyles(le, { position : '', left : '', top : '', width : '', height : '' }); ed.dom.removeClass(le, 'mceItemVisualAid'); ed.dom.removeClass(le, 'mceItemLayer'); } else { if (le.style.left == "") le.style.left = 20 + 'px'; if (le.style.top == "") le.style.top = 20 + 'px'; if (le.style.width == "") le.style.width = le.width ? (le.width + 'px') : '100px'; if (le.style.height == "") le.style.height = le.height ? (le.height + 'px') : '100px'; le.style.position = "absolute"; ed.dom.setAttrib(le, 'data-mce-style', ''); ed.addVisual(ed.getBody()); } ed.execCommand('mceRepaint'); ed.nodeChanged(); } } }); // Register plugin tinymce.PluginManager.add('layer', tinymce.plugins.Layer); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var TreeWalker = tinymce.dom.TreeWalker; var externalName = 'contenteditable', internalName = 'data-mce-' + externalName; var VK = tinymce.VK; function handleContentEditableSelection(ed) { var dom = ed.dom, selection = ed.selection, invisibleChar, caretContainerId = 'mce_noneditablecaret', invisibleChar = '\uFEFF'; // Returns the content editable state of a node "true/false" or null function getContentEditable(node) { var contentEditable; // Ignore non elements if (node.nodeType === 1) { // Check for fake content editable contentEditable = node.getAttribute(internalName); if (contentEditable && contentEditable !== "inherit") { return contentEditable; } // Check for real content editable contentEditable = node.contentEditable; if (contentEditable !== "inherit") { return contentEditable; } } return null; }; // Returns the noneditable parent or null if there is a editable before it or if it wasn't found function getNonEditableParent(node) { var state; while (node) { state = getContentEditable(node); if (state) { return state === "false" ? node : null; } node = node.parentNode; } }; // Get caret container parent for the specified node function getParentCaretContainer(node) { while (node) { if (node.id === caretContainerId) { return node; } node = node.parentNode; } }; // Finds the first text node in the specified node function findFirstTextNode(node) { var walker; if (node) { walker = new TreeWalker(node, node); for (node = walker.current(); node; node = walker.next()) { if (node.nodeType === 3) { return node; } } } }; // Insert caret container before/after target or expand selection to include block function insertCaretContainerOrExpandToBlock(target, before) { var caretContainer, rng; // Select block if (getContentEditable(target) === "false") { if (dom.isBlock(target)) { selection.select(target); return; } } rng = dom.createRng(); if (getContentEditable(target) === "true") { if (!target.firstChild) { target.appendChild(ed.getDoc().createTextNode('\u00a0')); } target = target.firstChild; before = true; } //caretContainer = dom.create('span', {id: caretContainerId, 'data-mce-bogus': true, style:'border: 1px solid red'}, invisibleChar); caretContainer = dom.create('span', {id: caretContainerId, 'data-mce-bogus': true}, invisibleChar); if (before) { target.parentNode.insertBefore(caretContainer, target); } else { dom.insertAfter(caretContainer, target); } rng.setStart(caretContainer.firstChild, 1); rng.collapse(true); selection.setRng(rng); return caretContainer; }; // Removes any caret container except the one we might be in function removeCaretContainer(caretContainer) { var child, currentCaretContainer, lastContainer; if (caretContainer) { rng = selection.getRng(true); rng.setStartBefore(caretContainer); rng.setEndBefore(caretContainer); child = findFirstTextNode(caretContainer); if (child && child.nodeValue.charAt(0) == invisibleChar) { child = child.deleteData(0, 1); } dom.remove(caretContainer, true); selection.setRng(rng); } else { currentCaretContainer = getParentCaretContainer(selection.getStart()); while ((caretContainer = dom.get(caretContainerId)) && caretContainer !== lastContainer) { if (currentCaretContainer !== caretContainer) { child = findFirstTextNode(caretContainer); if (child && child.nodeValue.charAt(0) == invisibleChar) { child = child.deleteData(0, 1); } dom.remove(caretContainer, true); } lastContainer = caretContainer; } } }; // Modifies the selection to include contentEditable false elements or insert caret containers function moveSelection() { var nonEditableStart, nonEditableEnd, isCollapsed, rng, element; // Checks if there is any contents to the left/right side of caret returns the noneditable element or any editable element if it finds one inside function hasSideContent(element, left) { var container, offset, walker, node, len; container = rng.startContainer; offset = rng.startOffset; // If endpoint is in middle of text node then expand to beginning/end of element if (container.nodeType == 3) { len = container.nodeValue.length; if ((offset > 0 && offset < len) || (left ? offset == len : offset == 0)) { return; } } else { // Can we resolve the node by index if (offset < container.childNodes.length) { // Browser represents caret position as the offset at the start of an element. When moving right // this is the element we are moving into so we consider our container to be child node at offset-1 var pos = !left && offset > 0 ? offset-1 : offset; container = container.childNodes[pos]; if (container.hasChildNodes()) { container = container.firstChild; } } else { // If not then the caret is at the last position in it's container and the caret container should be inserted after the noneditable element return !left ? element : null; } } // Walk left/right to look for contents walker = new TreeWalker(container, element); while (node = walker[left ? 'prev' : 'next']()) { if (node.nodeType === 3 && node.nodeValue.length > 0) { return; } else if (getContentEditable(node) === "true") { // Found contentEditable=true element return this one to we can move the caret inside it return node; } } return element; }; // Remove any existing caret containers removeCaretContainer(); // Get noneditable start/end elements isCollapsed = selection.isCollapsed(); nonEditableStart = getNonEditableParent(selection.getStart()); nonEditableEnd = getNonEditableParent(selection.getEnd()); // Is any fo the range endpoints noneditable if (nonEditableStart || nonEditableEnd) { rng = selection.getRng(true); // If it's a caret selection then look left/right to see if we need to move the caret out side or expand if (isCollapsed) { nonEditableStart = nonEditableStart || nonEditableEnd; var start = selection.getStart(); if (element = hasSideContent(nonEditableStart, true)) { // We have no contents to the left of the caret then insert a caret container before the noneditable element insertCaretContainerOrExpandToBlock(element, true); } else if (element = hasSideContent(nonEditableStart, false)) { // We have no contents to the right of the caret then insert a caret container after the noneditable element insertCaretContainerOrExpandToBlock(element, false); } else { // We are in the middle of a noneditable so expand to select it selection.select(nonEditableStart); } } else { rng = selection.getRng(true); // Expand selection to include start non editable element if (nonEditableStart) { rng.setStartBefore(nonEditableStart); } // Expand selection to include end non editable element if (nonEditableEnd) { rng.setEndAfter(nonEditableEnd); } selection.setRng(rng); } } }; function handleKey(ed, e) { var keyCode = e.keyCode, nonEditableParent, caretContainer, startElement, endElement; function getNonEmptyTextNodeSibling(node, prev) { while (node = node[prev ? 'previousSibling' : 'nextSibling']) { if (node.nodeType !== 3 || node.nodeValue.length > 0) { return node; } } }; function positionCaretOnElement(element, start) { selection.select(element); selection.collapse(start); } function canDelete(backspace) { var rng, container, offset, nonEditableParent; function removeNodeIfNotParent(node) { var parent = container; while (parent) { if (parent === node) { return; } parent = parent.parentNode; } dom.remove(node); moveSelection(); } function isNextPrevTreeNodeNonEditable() { var node, walker, nonEmptyElements = ed.schema.getNonEmptyElements(); walker = new tinymce.dom.TreeWalker(container, ed.getBody()); while (node = (backspace ? walker.prev() : walker.next())) { // Found IMG/INPUT etc if (nonEmptyElements[node.nodeName.toLowerCase()]) { break; } // Found text node with contents if (node.nodeType === 3 && tinymce.trim(node.nodeValue).length > 0) { break; } // Found non editable node if (getContentEditable(node) === "false") { removeNodeIfNotParent(node); return true; } } // Check if the content node is within a non editable parent if (getNonEditableParent(node)) { return true; } return false; } if (selection.isCollapsed()) { rng = selection.getRng(true); container = rng.startContainer; offset = rng.startOffset; container = getParentCaretContainer(container) || container; // Is in noneditable parent if (nonEditableParent = getNonEditableParent(container)) { removeNodeIfNotParent(nonEditableParent); return false; } // Check if the caret is in the middle of a text node if (container.nodeType == 3 && (backspace ? offset > 0 : offset < container.nodeValue.length)) { return true; } // Resolve container index if (container.nodeType == 1) { container = container.childNodes[offset] || container; } // Check if previous or next tree node is non editable then block the event if (isNextPrevTreeNodeNonEditable()) { return false; } } return true; } startElement = selection.getStart() endElement = selection.getEnd(); // Disable all key presses in contentEditable=false except delete or backspace nonEditableParent = getNonEditableParent(startElement) || getNonEditableParent(endElement); if (nonEditableParent && (keyCode < 112 || keyCode > 124) && keyCode != VK.DELETE && keyCode != VK.BACKSPACE) { // Is Ctrl+c, Ctrl+v or Ctrl+x then use default browser behavior if ((tinymce.isMac ? e.metaKey : e.ctrlKey) && (keyCode == 67 || keyCode == 88 || keyCode == 86)) { return; } e.preventDefault(); // Arrow left/right select the element and collapse left/right if (keyCode == VK.LEFT || keyCode == VK.RIGHT) { var left = keyCode == VK.LEFT; // If a block element find previous or next element to position the caret if (ed.dom.isBlock(nonEditableParent)) { var targetElement = left ? nonEditableParent.previousSibling : nonEditableParent.nextSibling; var walker = new TreeWalker(targetElement, targetElement); var caretElement = left ? walker.prev() : walker.next(); positionCaretOnElement(caretElement, !left); } else { positionCaretOnElement(nonEditableParent, left); } } } else { // Is arrow left/right, backspace or delete if (keyCode == VK.LEFT || keyCode == VK.RIGHT || keyCode == VK.BACKSPACE || keyCode == VK.DELETE) { caretContainer = getParentCaretContainer(startElement); if (caretContainer) { // Arrow left or backspace if (keyCode == VK.LEFT || keyCode == VK.BACKSPACE) { nonEditableParent = getNonEmptyTextNodeSibling(caretContainer, true); if (nonEditableParent && getContentEditable(nonEditableParent) === "false") { e.preventDefault(); if (keyCode == VK.LEFT) { positionCaretOnElement(nonEditableParent, true); } else { dom.remove(nonEditableParent); return; } } else { removeCaretContainer(caretContainer); } } // Arrow right or delete if (keyCode == VK.RIGHT || keyCode == VK.DELETE) { nonEditableParent = getNonEmptyTextNodeSibling(caretContainer); if (nonEditableParent && getContentEditable(nonEditableParent) === "false") { e.preventDefault(); if (keyCode == VK.RIGHT) { positionCaretOnElement(nonEditableParent, false); } else { dom.remove(nonEditableParent); return; } } else { removeCaretContainer(caretContainer); } } } if ((keyCode == VK.BACKSPACE || keyCode == VK.DELETE) && !canDelete(keyCode == VK.BACKSPACE)) { e.preventDefault(); return false; } } } }; ed.onMouseDown.addToTop(function(ed, e) { var node = ed.selection.getNode(); if (getContentEditable(node) === "false" && node == e.target) { // Expand selection on mouse down we can't block the default event since it's used for drag/drop moveSelection(); } }); ed.onMouseUp.addToTop(moveSelection); ed.onKeyDown.addToTop(handleKey); ed.onKeyUp.addToTop(moveSelection); }; tinymce.create('tinymce.plugins.NonEditablePlugin', { init : function(ed, url) { var editClass, nonEditClass, nonEditableRegExps; // Converts configured regexps to noneditable span items function convertRegExpsToNonEditable(ed, args) { var i = nonEditableRegExps.length, content = args.content, cls = tinymce.trim(nonEditClass); // Don't replace the variables when raw is used for example on undo/redo if (args.format == "raw") { return; } while (i--) { content = content.replace(nonEditableRegExps[i], function(match) { var args = arguments, index = args[args.length - 2]; // Is value inside an attribute then don't replace if (index > 0 && content.charAt(index - 1) == '"') { return match; } return '<span class="' + cls + '" data-mce-content="' + ed.dom.encode(args[0]) + '">' + ed.dom.encode(typeof(args[1]) === "string" ? args[1] : args[0]) + '</span>'; }); } args.content = content; }; editClass = " " + tinymce.trim(ed.getParam("noneditable_editable_class", "mceEditable")) + " "; nonEditClass = " " + tinymce.trim(ed.getParam("noneditable_noneditable_class", "mceNonEditable")) + " "; // Setup noneditable regexps array nonEditableRegExps = ed.getParam("noneditable_regexp"); if (nonEditableRegExps && !nonEditableRegExps.length) { nonEditableRegExps = [nonEditableRegExps]; } ed.onPreInit.add(function() { handleContentEditableSelection(ed); if (nonEditableRegExps) { ed.selection.onBeforeSetContent.add(convertRegExpsToNonEditable); ed.onBeforeSetContent.add(convertRegExpsToNonEditable); } // Apply contentEditable true/false on elements with the noneditable/editable classes ed.parser.addAttributeFilter('class', function(nodes) { var i = nodes.length, className, node; while (i--) { node = nodes[i]; className = " " + node.attr("class") + " "; if (className.indexOf(editClass) !== -1) { node.attr(internalName, "true"); } else if (className.indexOf(nonEditClass) !== -1) { node.attr(internalName, "false"); } } }); // Remove internal name ed.serializer.addAttributeFilter(internalName, function(nodes, name) { var i = nodes.length, node; while (i--) { node = nodes[i]; if (nonEditableRegExps && node.attr('data-mce-content')) { node.name = "#text"; node.type = 3; node.raw = true; node.value = node.attr('data-mce-content'); } else { node.attr(externalName, null); node.attr(internalName, null); } } }); // Convert external name into internal name ed.parser.addAttributeFilter(externalName, function(nodes, name) { var i = nodes.length, node; while (i--) { node = nodes[i]; node.attr(internalName, node.attr(externalName)); node.attr(externalName, null); } }); }); }, getInfo : function() { return { longname : 'Non editable elements', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/noneditable', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('noneditable', tinymce.plugins.NonEditablePlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.InsertDateTime', { init : function(ed, url) { var t = this; t.editor = ed; ed.addCommand('mceInsertDate', function() { var str = t._getDateTime(new Date(), ed.getParam("plugin_insertdate_dateFormat", ed.getLang('insertdatetime.date_fmt'))); ed.execCommand('mceInsertContent', false, str); }); ed.addCommand('mceInsertTime', function() { var str = t._getDateTime(new Date(), ed.getParam("plugin_insertdate_timeFormat", ed.getLang('insertdatetime.time_fmt'))); ed.execCommand('mceInsertContent', false, str); }); ed.addButton('insertdate', {title : 'insertdatetime.insertdate_desc', cmd : 'mceInsertDate'}); ed.addButton('inserttime', {title : 'insertdatetime.inserttime_desc', cmd : 'mceInsertTime'}); }, getInfo : function() { return { longname : 'Insert date/time', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/insertdatetime', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _getDateTime : function(d, fmt) { var ed = this.editor; function addZeros(value, len) { value = "" + value; if (value.length < len) { for (var i=0; i<(len-value.length); i++) value = "0" + value; } return value; }; fmt = fmt.replace("%D", "%m/%d/%y"); fmt = fmt.replace("%r", "%I:%M:%S %p"); fmt = fmt.replace("%Y", "" + d.getFullYear()); fmt = fmt.replace("%y", "" + d.getYear()); fmt = fmt.replace("%m", addZeros(d.getMonth()+1, 2)); fmt = fmt.replace("%d", addZeros(d.getDate(), 2)); fmt = fmt.replace("%H", "" + addZeros(d.getHours(), 2)); fmt = fmt.replace("%M", "" + addZeros(d.getMinutes(), 2)); fmt = fmt.replace("%S", "" + addZeros(d.getSeconds(), 2)); fmt = fmt.replace("%I", "" + ((d.getHours() + 11) % 12 + 1)); fmt = fmt.replace("%p", "" + (d.getHours() < 12 ? "AM" : "PM")); fmt = fmt.replace("%B", "" + ed.getLang("insertdatetime.months_long").split(',')[d.getMonth()]); fmt = fmt.replace("%b", "" + ed.getLang("insertdatetime.months_short").split(',')[d.getMonth()]); fmt = fmt.replace("%A", "" + ed.getLang("insertdatetime.day_long").split(',')[d.getDay()]); fmt = fmt.replace("%a", "" + ed.getLang("insertdatetime.day_short").split(',')[d.getDay()]); fmt = fmt.replace("%%", "%"); return fmt; } }); // Register plugin tinymce.PluginManager.add('insertdatetime', tinymce.plugins.InsertDateTime); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.AdvancedImagePlugin', { init : function(ed, url) { // Register commands ed.addCommand('mceAdvImage', function() { // Internal image object like a flash placeholder if (ed.dom.getAttrib(ed.selection.getNode(), 'class', '').indexOf('mceItem') != -1) return; ed.windowManager.open({ file : url + '/image.htm', width : 480 + parseInt(ed.getLang('advimage.delta_width', 0)), height : 385 + parseInt(ed.getLang('advimage.delta_height', 0)), inline : 1 }, { plugin_url : url }); }); // Register buttons ed.addButton('image', { title : 'advimage.image_desc', cmd : 'mceAdvImage' }); }, getInfo : function() { return { longname : 'Advanced image', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advimage', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('advimage', tinymce.plugins.AdvancedImagePlugin); })();
JavaScript
var ImageDialog = { preInit : function() { var url; tinyMCEPopup.requireLangPack(); if (url = tinyMCEPopup.getParam("external_image_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function(ed) { var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, dom = ed.dom, n = ed.selection.getNode(), fl = tinyMCEPopup.getParam('external_image_list', 'tinyMCEImageList'); tinyMCEPopup.resizeToInnerSize(); this.fillClassList('class_list'); this.fillFileList('src_list', fl); this.fillFileList('over_list', fl); this.fillFileList('out_list', fl); TinyMCE_EditableSelects.init(); if (n.nodeName == 'IMG') { nl.src.value = dom.getAttrib(n, 'src'); nl.width.value = dom.getAttrib(n, 'width'); nl.height.value = dom.getAttrib(n, 'height'); nl.alt.value = dom.getAttrib(n, 'alt'); nl.title.value = dom.getAttrib(n, 'title'); nl.vspace.value = this.getAttrib(n, 'vspace'); nl.hspace.value = this.getAttrib(n, 'hspace'); nl.border.value = this.getAttrib(n, 'border'); selectByValue(f, 'align', this.getAttrib(n, 'align')); selectByValue(f, 'class_list', dom.getAttrib(n, 'class'), true, true); nl.style.value = dom.getAttrib(n, 'style'); nl.id.value = dom.getAttrib(n, 'id'); nl.dir.value = dom.getAttrib(n, 'dir'); nl.lang.value = dom.getAttrib(n, 'lang'); nl.usemap.value = dom.getAttrib(n, 'usemap'); nl.longdesc.value = dom.getAttrib(n, 'longdesc'); nl.insert.value = ed.getLang('update'); if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseover'))) nl.onmouseoversrc.value = dom.getAttrib(n, 'onmouseover').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1'); if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseout'))) nl.onmouseoutsrc.value = dom.getAttrib(n, 'onmouseout').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1'); if (ed.settings.inline_styles) { // Move attribs to styles if (dom.getAttrib(n, 'align')) this.updateStyle('align'); if (dom.getAttrib(n, 'hspace')) this.updateStyle('hspace'); if (dom.getAttrib(n, 'border')) this.updateStyle('border'); if (dom.getAttrib(n, 'vspace')) this.updateStyle('vspace'); } } // Setup browse button document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image'); if (isVisible('srcbrowser')) document.getElementById('src').style.width = '260px'; // Setup browse button document.getElementById('onmouseoversrccontainer').innerHTML = getBrowserHTML('overbrowser','onmouseoversrc','image','theme_advanced_image'); if (isVisible('overbrowser')) document.getElementById('onmouseoversrc').style.width = '260px'; // Setup browse button document.getElementById('onmouseoutsrccontainer').innerHTML = getBrowserHTML('outbrowser','onmouseoutsrc','image','theme_advanced_image'); if (isVisible('outbrowser')) document.getElementById('onmouseoutsrc').style.width = '260px'; // If option enabled default contrain proportions to checked if (ed.getParam("advimage_constrain_proportions", true)) f.constrain.checked = true; // Check swap image if valid data if (nl.onmouseoversrc.value || nl.onmouseoutsrc.value) this.setSwapImage(true); else this.setSwapImage(false); this.changeAppearance(); this.showPreviewImage(nl.src.value, 1); }, insert : function(file, title) { var ed = tinyMCEPopup.editor, t = this, f = document.forms[0]; if (f.src.value === '') { if (ed.selection.getNode().nodeName == 'IMG') { ed.dom.remove(ed.selection.getNode()); ed.execCommand('mceRepaint'); } tinyMCEPopup.close(); return; } if (tinyMCEPopup.getParam("accessibility_warnings", 1)) { if (!f.alt.value) { tinyMCEPopup.confirm(tinyMCEPopup.getLang('advimage_dlg.missing_alt'), function(s) { if (s) t.insertAndClose(); }); return; } } t.insertAndClose(); }, insertAndClose : function() { var ed = tinyMCEPopup.editor, f = document.forms[0], nl = f.elements, v, args = {}, el; tinyMCEPopup.restoreSelection(); // Fixes crash in Safari if (tinymce.isWebKit) ed.getWin().focus(); if (!ed.settings.inline_styles) { args = { vspace : nl.vspace.value, hspace : nl.hspace.value, border : nl.border.value, align : getSelectValue(f, 'align') }; } else { // Remove deprecated values args = { vspace : '', hspace : '', border : '', align : '' }; } tinymce.extend(args, { src : nl.src.value.replace(/ /g, '%20'), width : nl.width.value, height : nl.height.value, alt : nl.alt.value, title : nl.title.value, 'class' : getSelectValue(f, 'class_list'), style : nl.style.value, id : nl.id.value, dir : nl.dir.value, lang : nl.lang.value, usemap : nl.usemap.value, longdesc : nl.longdesc.value }); args.onmouseover = args.onmouseout = ''; if (f.onmousemovecheck.checked) { if (nl.onmouseoversrc.value) args.onmouseover = "this.src='" + nl.onmouseoversrc.value + "';"; if (nl.onmouseoutsrc.value) args.onmouseout = "this.src='" + nl.onmouseoutsrc.value + "';"; } el = ed.selection.getNode(); if (el && el.nodeName == 'IMG') { ed.dom.setAttribs(el, args); } else { tinymce.each(args, function(value, name) { if (value === "") { delete args[name]; } }); ed.execCommand('mceInsertContent', false, tinyMCEPopup.editor.dom.createHTML('img', args), {skip_undo : 1}); ed.undoManager.add(); } tinyMCEPopup.editor.execCommand('mceRepaint'); tinyMCEPopup.editor.focus(); tinyMCEPopup.close(); }, getAttrib : function(e, at) { var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2; if (ed.settings.inline_styles) { switch (at) { case 'align': if (v = dom.getStyle(e, 'float')) return v; if (v = dom.getStyle(e, 'vertical-align')) return v; break; case 'hspace': v = dom.getStyle(e, 'margin-left') v2 = dom.getStyle(e, 'margin-right'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'vspace': v = dom.getStyle(e, 'margin-top') v2 = dom.getStyle(e, 'margin-bottom'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'border': v = 0; tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) { sv = dom.getStyle(e, 'border-' + sv + '-width'); // False or not the same as prev if (!sv || (sv != v && v !== 0)) { v = 0; return false; } if (sv) v = sv; }); if (v) return parseInt(v.replace(/[^0-9]/g, '')); break; } } if (v = dom.getAttrib(e, at)) return v; return ''; }, setSwapImage : function(st) { var f = document.forms[0]; f.onmousemovecheck.checked = st; setBrowserDisabled('overbrowser', !st); setBrowserDisabled('outbrowser', !st); if (f.over_list) f.over_list.disabled = !st; if (f.out_list) f.out_list.disabled = !st; f.onmouseoversrc.disabled = !st; f.onmouseoutsrc.disabled = !st; }, fillClassList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; if (v = tinyMCEPopup.getParam('theme_advanced_styles')) { cl = []; tinymce.each(v.split(';'), function(v) { var p = v.split('='); cl.push({'title' : p[0], 'class' : p[1]}); }); } else cl = tinyMCEPopup.editor.dom.getClasses(); if (cl.length > 0) { lst.options.length = 0; lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); tinymce.each(cl, function(o) { lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = typeof(l) === 'function' ? l() : window[l]; lst.options.length = 0; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, resetImageData : function() { var f = document.forms[0]; f.elements.width.value = f.elements.height.value = ''; }, updateImageData : function(img, st) { var f = document.forms[0]; if (!st) { f.elements.width.value = img.width; f.elements.height.value = img.height; } this.preloadImg = img; }, changeAppearance : function() { var ed = tinyMCEPopup.editor, f = document.forms[0], img = document.getElementById('alignSampleImg'); if (img) { if (ed.getParam('inline_styles')) { ed.dom.setAttrib(img, 'style', f.style.value); } else { img.align = f.align.value; img.border = f.border.value; img.hspace = f.hspace.value; img.vspace = f.vspace.value; } } }, changeHeight : function() { var f = document.forms[0], tp, t = this; if (!f.constrain.checked || !t.preloadImg) { return; } if (f.width.value == "" || f.height.value == "") return; tp = (parseInt(f.width.value) / parseInt(t.preloadImg.width)) * t.preloadImg.height; f.height.value = tp.toFixed(0); }, changeWidth : function() { var f = document.forms[0], tp, t = this; if (!f.constrain.checked || !t.preloadImg) { return; } if (f.width.value == "" || f.height.value == "") return; tp = (parseInt(f.height.value) / parseInt(t.preloadImg.height)) * t.preloadImg.width; f.width.value = tp.toFixed(0); }, updateStyle : function(ty) { var dom = tinyMCEPopup.dom, b, bStyle, bColor, v, isIE = tinymce.isIE, f = document.forms[0], img = dom.create('img', {style : dom.get('style').value}); if (tinyMCEPopup.editor.settings.inline_styles) { // Handle align if (ty == 'align') { dom.setStyle(img, 'float', ''); dom.setStyle(img, 'vertical-align', ''); v = getSelectValue(f, 'align'); if (v) { if (v == 'left' || v == 'right') dom.setStyle(img, 'float', v); else img.style.verticalAlign = v; } } // Handle border if (ty == 'border') { b = img.style.border ? img.style.border.split(' ') : []; bStyle = dom.getStyle(img, 'border-style'); bColor = dom.getStyle(img, 'border-color'); dom.setStyle(img, 'border', ''); v = f.border.value; if (v || v == '0') { if (v == '0') img.style.border = isIE ? '0' : '0 none none'; else { var isOldIE = tinymce.isIE && (!document.documentMode || document.documentMode < 9); if (b.length == 3 && b[isOldIE ? 2 : 1]) bStyle = b[isOldIE ? 2 : 1]; else if (!bStyle || bStyle == 'none') bStyle = 'solid'; if (b.length == 3 && b[isIE ? 0 : 2]) bColor = b[isOldIE ? 0 : 2]; else if (!bColor || bColor == 'none') bColor = 'black'; img.style.border = v + 'px ' + bStyle + ' ' + bColor; } } } // Handle hspace if (ty == 'hspace') { dom.setStyle(img, 'marginLeft', ''); dom.setStyle(img, 'marginRight', ''); v = f.hspace.value; if (v) { img.style.marginLeft = v + 'px'; img.style.marginRight = v + 'px'; } } // Handle vspace if (ty == 'vspace') { dom.setStyle(img, 'marginTop', ''); dom.setStyle(img, 'marginBottom', ''); v = f.vspace.value; if (v) { img.style.marginTop = v + 'px'; img.style.marginBottom = v + 'px'; } } // Merge dom.get('style').value = dom.serializeStyle(dom.parseStyle(img.style.cssText), 'img'); } }, changeMouseMove : function() { }, showPreviewImage : function(u, st) { if (!u) { tinyMCEPopup.dom.setHTML('prev', ''); return; } if (!st && tinyMCEPopup.getParam("advimage_update_dimensions_onchange", true)) this.resetImageData(); u = tinyMCEPopup.editor.documentBaseURI.toAbsolute(u); if (!st) tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="ImageDialog.updateImageData(this);" onerror="ImageDialog.resetImageData();" />'); else tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="ImageDialog.updateImageData(this, 1);" />'); } }; ImageDialog.preInit(); tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { /** * Auto Resize * * This plugin automatically resizes the content area to fit its content height. * It will retain a minimum height, which is the height of the content area when * it's initialized. */ tinymce.create('tinymce.plugins.AutoResizePlugin', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { var t = this, oldSize = 0; if (ed.getParam('fullscreen_is_enabled')) return; /** * This method gets executed each time the editor needs to resize. */ function resize() { var deltaSize, d = ed.getDoc(), body = d.body, de = d.documentElement, DOM = tinymce.DOM, resizeHeight = t.autoresize_min_height, myHeight; // Get height differently depending on the browser used myHeight = tinymce.isIE ? body.scrollHeight : (tinymce.isWebKit && body.clientHeight == 0 ? 0 : body.offsetHeight); // Don't make it smaller than the minimum height if (myHeight > t.autoresize_min_height) resizeHeight = myHeight; // If a maximum height has been defined don't exceed this height if (t.autoresize_max_height && myHeight > t.autoresize_max_height) { resizeHeight = t.autoresize_max_height; body.style.overflowY = "auto"; de.style.overflowY = "auto"; // Old IE } else { body.style.overflowY = "hidden"; de.style.overflowY = "hidden"; // Old IE body.scrollTop = 0; } // Resize content element if (resizeHeight !== oldSize) { deltaSize = resizeHeight - oldSize; DOM.setStyle(DOM.get(ed.id + '_ifr'), 'height', resizeHeight + 'px'); oldSize = resizeHeight; // WebKit doesn't decrease the size of the body element until the iframe gets resized // So we need to continue to resize the iframe down until the size gets fixed if (tinymce.isWebKit && deltaSize < 0) resize(); } }; t.editor = ed; // Define minimum height t.autoresize_min_height = parseInt(ed.getParam('autoresize_min_height', ed.getElement().offsetHeight)); // Define maximum height t.autoresize_max_height = parseInt(ed.getParam('autoresize_max_height', 0)); // Add padding at the bottom for better UX ed.onInit.add(function(ed){ ed.dom.setStyle(ed.getBody(), 'paddingBottom', ed.getParam('autoresize_bottom_margin', 50) + 'px'); }); // Add appropriate listeners for resizing content area ed.onChange.add(resize); ed.onSetContent.add(resize); ed.onPaste.add(resize); ed.onKeyUp.add(resize); ed.onPostRender.add(resize); if (ed.getParam('autoresize_on_init', true)) { ed.onLoad.add(resize); ed.onLoadContent.add(resize); } // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample'); ed.addCommand('mceAutoResize', resize); }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'Auto Resize', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autoresize', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('autoresize', tinymce.plugins.AutoResizePlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2011, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var each = tinymce.each, Event = tinymce.dom.Event, bookmark; // Skips text nodes that only contain whitespace since they aren't semantically important. function skipWhitespaceNodes(e, next) { while (e && (e.nodeType === 8 || (e.nodeType === 3 && /^[ \t\n\r]*$/.test(e.nodeValue)))) { e = next(e); } return e; } function skipWhitespaceNodesBackwards(e) { return skipWhitespaceNodes(e, function(e) { return e.previousSibling; }); } function skipWhitespaceNodesForwards(e) { return skipWhitespaceNodes(e, function(e) { return e.nextSibling; }); } function hasParentInList(ed, e, list) { return ed.dom.getParent(e, function(p) { return tinymce.inArray(list, p) !== -1; }); } function isList(e) { return e && (e.tagName === 'OL' || e.tagName === 'UL'); } function splitNestedLists(element, dom) { var tmp, nested, wrapItem; tmp = skipWhitespaceNodesBackwards(element.lastChild); while (isList(tmp)) { nested = tmp; tmp = skipWhitespaceNodesBackwards(nested.previousSibling); } if (nested) { wrapItem = dom.create('li', { style: 'list-style-type: none;'}); dom.split(element, nested); dom.insertAfter(wrapItem, nested); wrapItem.appendChild(nested); wrapItem.appendChild(nested); element = wrapItem.previousSibling; } return element; } function attemptMergeWithAdjacent(e, allowDifferentListStyles, mergeParagraphs) { e = attemptMergeWithPrevious(e, allowDifferentListStyles, mergeParagraphs); return attemptMergeWithNext(e, allowDifferentListStyles, mergeParagraphs); } function attemptMergeWithPrevious(e, allowDifferentListStyles, mergeParagraphs) { var prev = skipWhitespaceNodesBackwards(e.previousSibling); if (prev) { return attemptMerge(prev, e, allowDifferentListStyles ? prev : false, mergeParagraphs); } else { return e; } } function attemptMergeWithNext(e, allowDifferentListStyles, mergeParagraphs) { var next = skipWhitespaceNodesForwards(e.nextSibling); if (next) { return attemptMerge(e, next, allowDifferentListStyles ? next : false, mergeParagraphs); } else { return e; } } function attemptMerge(e1, e2, differentStylesMasterElement, mergeParagraphs) { if (canMerge(e1, e2, !!differentStylesMasterElement, mergeParagraphs)) { return merge(e1, e2, differentStylesMasterElement); } else if (e1 && e1.tagName === 'LI' && isList(e2)) { // Fix invalidly nested lists. e1.appendChild(e2); } return e2; } function canMerge(e1, e2, allowDifferentListStyles, mergeParagraphs) { if (!e1 || !e2) { return false; } else if (e1.tagName === 'LI' && e2.tagName === 'LI') { return e2.style.listStyleType === 'none' || containsOnlyAList(e2); } else if (isList(e1)) { return (e1.tagName === e2.tagName && (allowDifferentListStyles || e1.style.listStyleType === e2.style.listStyleType)) || isListForIndent(e2); } else return mergeParagraphs && e1.tagName === 'P' && e2.tagName === 'P'; } function isListForIndent(e) { var firstLI = skipWhitespaceNodesForwards(e.firstChild), lastLI = skipWhitespaceNodesBackwards(e.lastChild); return firstLI && lastLI && isList(e) && firstLI === lastLI && (isList(firstLI) || firstLI.style.listStyleType === 'none' || containsOnlyAList(firstLI)); } function containsOnlyAList(e) { var firstChild = skipWhitespaceNodesForwards(e.firstChild), lastChild = skipWhitespaceNodesBackwards(e.lastChild); return firstChild && lastChild && firstChild === lastChild && isList(firstChild); } function merge(e1, e2, masterElement) { var lastOriginal = skipWhitespaceNodesBackwards(e1.lastChild), firstNew = skipWhitespaceNodesForwards(e2.firstChild); if (e1.tagName === 'P') { e1.appendChild(e1.ownerDocument.createElement('br')); } while (e2.firstChild) { e1.appendChild(e2.firstChild); } if (masterElement) { e1.style.listStyleType = masterElement.style.listStyleType; } e2.parentNode.removeChild(e2); attemptMerge(lastOriginal, firstNew, false); return e1; } function findItemToOperateOn(e, dom) { var item; if (!dom.is(e, 'li,ol,ul')) { item = dom.getParent(e, 'li'); if (item) { e = item; } } return e; } tinymce.create('tinymce.plugins.Lists', { init: function(ed) { var LIST_TABBING = 'TABBING'; var LIST_EMPTY_ITEM = 'EMPTY'; var LIST_ESCAPE = 'ESCAPE'; var LIST_PARAGRAPH = 'PARAGRAPH'; var LIST_UNKNOWN = 'UNKNOWN'; var state = LIST_UNKNOWN; function isTabInList(e) { // Don't indent on Ctrl+Tab or Alt+Tab return e.keyCode === tinymce.VK.TAB && !(e.altKey || e.ctrlKey) && (ed.queryCommandState('InsertUnorderedList') || ed.queryCommandState('InsertOrderedList')); } function isOnLastListItem() { var li = getLi(); var grandParent = li.parentNode.parentNode; var isLastItem = li.parentNode.lastChild === li; return isLastItem && !isNestedList(grandParent) && isEmptyListItem(li); } function isNestedList(grandParent) { if (isList(grandParent)) { return grandParent.parentNode && grandParent.parentNode.tagName === 'LI'; } else { return grandParent.tagName === 'LI'; } } function isInEmptyListItem() { return ed.selection.isCollapsed() && isEmptyListItem(getLi()); } function getLi() { var n = ed.selection.getStart(); // Get start will return BR if the LI only contains a BR or an empty element as we use these to fix caret position return ((n.tagName == 'BR' || n.tagName == '') && n.parentNode.tagName == 'LI') ? n.parentNode : n; } function isEmptyListItem(li) { var numChildren = li.childNodes.length; if (li.tagName === 'LI') { return numChildren == 0 ? true : numChildren == 1 && (li.firstChild.tagName == '' || li.firstChild.tagName == 'BR' || isEmptyIE9Li(li)); } return false; } function isEmptyIE9Li(li) { // only consider this to be last item if there is no list item content or that content is nbsp or space since IE9 creates these var lis = tinymce.grep(li.parentNode.childNodes, function(n) {return n.tagName == 'LI'}); var isLastLi = li == lis[lis.length - 1]; var child = li.firstChild; return tinymce.isIE9 && isLastLi && (child.nodeValue == String.fromCharCode(160) || child.nodeValue == String.fromCharCode(32)); } function isEnter(e) { return e.keyCode === tinymce.VK.ENTER; } function isEnterWithoutShift(e) { return isEnter(e) && !e.shiftKey; } function getListKeyState(e) { if (isTabInList(e)) { return LIST_TABBING; } else if (isEnterWithoutShift(e) && isOnLastListItem()) { // Returns LIST_UNKNOWN since breaking out of lists is handled by the EnterKey.js logic now //return LIST_ESCAPE; return LIST_UNKNOWN; } else if (isEnterWithoutShift(e) && isInEmptyListItem()) { return LIST_EMPTY_ITEM; } else { return LIST_UNKNOWN; } } function cancelDefaultEvents(ed, e) { // list escape is done manually using outdent as it does not create paragraphs correctly in td's if (state == LIST_TABBING || state == LIST_EMPTY_ITEM || tinymce.isGecko && state == LIST_ESCAPE) { Event.cancel(e); } } function isCursorAtEndOfContainer() { var range = ed.selection.getRng(true); var startContainer = range.startContainer; if (startContainer.nodeType == 3) { var value = startContainer.nodeValue; if (tinymce.isIE9 && value.length > 1 && value.charCodeAt(value.length-1) == 32) { // IE9 places a space on the end of the text in some cases so ignore last char return (range.endOffset == value.length-1); } else { return (range.endOffset == value.length); } } else if (startContainer.nodeType == 1) { return range.endOffset == startContainer.childNodes.length; } return false; } /* If we are at the end of a list item surrounded with an element, pressing enter should create a new list item instead without splitting the element e.g. don't want to create new P or H1 tag */ function isEndOfListItem() { var node = ed.selection.getNode(); var validElements = 'h1,h2,h3,h4,h5,h6,p,div'; var isLastParagraphOfLi = ed.dom.is(node, validElements) && node.parentNode.tagName === 'LI' && node.parentNode.lastChild === node; return ed.selection.isCollapsed() && isLastParagraphOfLi && isCursorAtEndOfContainer(); } // Creates a new list item after the current selection's list item parent function createNewLi(ed, e) { if (isEnterWithoutShift(e) && isEndOfListItem()) { var node = ed.selection.getNode(); var li = ed.dom.create("li"); var parentLi = ed.dom.getParent(node, 'li'); ed.dom.insertAfter(li, parentLi); // Move caret to new list element. if (tinymce.isIE6 || tinymce.isIE7 || tinyMCE.isIE8) { // Removed this line since it would create an odd <&nbsp;> tag and placing the caret inside an empty LI is handled and should be handled by the selection logic //li.appendChild(ed.dom.create("&nbsp;")); // IE needs an element within the bullet point ed.selection.setCursorLocation(li, 1); } else { ed.selection.setCursorLocation(li, 0); } e.preventDefault(); } } function imageJoiningListItem(ed, e) { var prevSibling; if (!tinymce.isGecko) return; var n = ed.selection.getStart(); if (e.keyCode != tinymce.VK.BACKSPACE || n.tagName !== 'IMG') return; function lastLI(node) { var child = node.firstChild; var li = null; do { if (!child) break; if (child.tagName === 'LI') li = child; } while (child = child.nextSibling); return li; } function addChildren(parentNode, destination) { while (parentNode.childNodes.length > 0) destination.appendChild(parentNode.childNodes[0]); } // Check if there is a previous sibling prevSibling = n.parentNode.previousSibling; if (!prevSibling) return; var ul; if (prevSibling.tagName === 'UL' || prevSibling.tagName === 'OL') ul = prevSibling; else if (prevSibling.previousSibling && (prevSibling.previousSibling.tagName === 'UL' || prevSibling.previousSibling.tagName === 'OL')) ul = prevSibling.previousSibling; else return; var li = lastLI(ul); // move the caret to the end of the list item var rng = ed.dom.createRng(); rng.setStart(li, 1); rng.setEnd(li, 1); ed.selection.setRng(rng); ed.selection.collapse(true); // save a bookmark at the end of the list item var bookmark = ed.selection.getBookmark(); // copy the image an its text to the list item var clone = n.parentNode.cloneNode(true); if (clone.tagName === 'P' || clone.tagName === 'DIV') addChildren(clone, li); else li.appendChild(clone); // remove the old copy of the image n.parentNode.parentNode.removeChild(n.parentNode); // move the caret where we saved the bookmark ed.selection.moveToBookmark(bookmark); } // fix the cursor position to ensure it is correct in IE function setCursorPositionToOriginalLi(li) { var list = ed.dom.getParent(li, 'ol,ul'); if (list != null) { var lastLi = list.lastChild; // Removed this line since IE9 would report an DOM character error and placing the caret inside an empty LI is handled and should be handled by the selection logic //lastLi.appendChild(ed.getDoc().createElement('')); ed.selection.setCursorLocation(lastLi, 0); } } this.ed = ed; ed.addCommand('Indent', this.indent, this); ed.addCommand('Outdent', this.outdent, this); ed.addCommand('InsertUnorderedList', function() { this.applyList('UL', 'OL'); }, this); ed.addCommand('InsertOrderedList', function() { this.applyList('OL', 'UL'); }, this); ed.onInit.add(function() { ed.editorCommands.addCommands({ 'outdent': function() { var sel = ed.selection, dom = ed.dom; function hasStyleIndent(n) { n = dom.getParent(n, dom.isBlock); return n && (parseInt(ed.dom.getStyle(n, 'margin-left') || 0, 10) + parseInt(ed.dom.getStyle(n, 'padding-left') || 0, 10)) > 0; } return hasStyleIndent(sel.getStart()) || hasStyleIndent(sel.getEnd()) || ed.queryCommandState('InsertOrderedList') || ed.queryCommandState('InsertUnorderedList'); } }, 'state'); }); ed.onKeyUp.add(function(ed, e) { if (state == LIST_TABBING) { ed.execCommand(e.shiftKey ? 'Outdent' : 'Indent', true, null); state = LIST_UNKNOWN; return Event.cancel(e); } else if (state == LIST_EMPTY_ITEM) { var li = getLi(); var shouldOutdent = ed.settings.list_outdent_on_enter === true || e.shiftKey; ed.execCommand(shouldOutdent ? 'Outdent' : 'Indent', true, null); if (tinymce.isIE) { setCursorPositionToOriginalLi(li); } return Event.cancel(e); } else if (state == LIST_ESCAPE) { if (tinymce.isIE6 || tinymce.isIE7 || tinymce.isIE8) { // append a zero sized nbsp so that caret is positioned correctly in IE after escaping and applying formatting. // if there is no text then applying formatting for e.g a H1 to the P tag immediately following list after // escaping from it will cause the caret to be positioned on the last li instead of staying the in P tag. var n = ed.getDoc().createTextNode('\uFEFF'); ed.selection.getNode().appendChild(n); } else if (tinymce.isIE9 || tinymce.isGecko) { // IE9 does not escape the list so we use outdent to do this and cancel the default behaviour // Gecko does not create a paragraph outdenting inside a TD so default behaviour is cancelled and we outdent ourselves ed.execCommand('Outdent'); return Event.cancel(e); } } }); function fixListItem(parent, reference) { // a zero-sized non-breaking space is placed in the empty list item so that the nested list is // displayed on the below line instead of next to it var n = ed.getDoc().createTextNode('\uFEFF'); parent.insertBefore(n, reference); ed.selection.setCursorLocation(n, 0); // repaint to remove rendering artifact. only visible when creating new list ed.execCommand('mceRepaint'); } function fixIndentedListItemForGecko(ed, e) { if (isEnter(e)) { var li = getLi(); if (li) { var parent = li.parentNode; var grandParent = parent && parent.parentNode; if (grandParent && grandParent.nodeName == 'LI' && grandParent.firstChild == parent && li == parent.firstChild) { fixListItem(grandParent, parent); } } } } function fixIndentedListItemForIE8(ed, e) { if (isEnter(e)) { var li = getLi(); if (ed.dom.select('ul li', li).length === 1) { var list = li.firstChild; fixListItem(li, list); } } } function fixDeletingFirstCharOfList(ed, e) { function listElements(li) { var elements = []; var walker = new tinymce.dom.TreeWalker(li.firstChild, li); for (var node = walker.current(); node; node = walker.next()) { if (ed.dom.is(node, 'ol,ul,li')) { elements.push(node); } } return elements; } if (e.keyCode == tinymce.VK.BACKSPACE) { var li = getLi(); if (li) { var list = ed.dom.getParent(li, 'ol,ul'), rng = ed.selection.getRng(); if (list && list.firstChild === li && rng.startOffset == 0) { var elements = listElements(li); elements.unshift(li); ed.execCommand("Outdent", false, elements); ed.undoManager.add(); return Event.cancel(e); } } } } function fixDeletingEmptyLiInWebkit(ed, e) { var li = getLi(); if (e.keyCode === tinymce.VK.BACKSPACE && ed.dom.is(li, 'li') && li.parentNode.firstChild!==li) { if (ed.dom.select('ul,ol', li).length === 1) { var prevLi = li.previousSibling; ed.dom.remove(ed.dom.select('br', li)); ed.dom.remove(li, true); var textNodes = tinymce.grep(prevLi.childNodes, function(n){ return n.nodeType === 3 }); if (textNodes.length === 1) { var textNode = textNodes[0]; ed.selection.setCursorLocation(textNode, textNode.length); } ed.undoManager.add(); return Event.cancel(e); } } } ed.onKeyDown.add(function(_, e) { state = getListKeyState(e); }); ed.onKeyDown.add(cancelDefaultEvents); ed.onKeyDown.add(imageJoiningListItem); ed.onKeyDown.add(createNewLi); if (tinymce.isGecko) { ed.onKeyUp.add(fixIndentedListItemForGecko); } if (tinymce.isIE8) { ed.onKeyUp.add(fixIndentedListItemForIE8); } if (tinymce.isGecko || tinymce.isWebKit) { ed.onKeyDown.add(fixDeletingFirstCharOfList); } if (tinymce.isWebKit) { ed.onKeyDown.add(fixDeletingEmptyLiInWebkit); } }, applyList: function(targetListType, oppositeListType) { var t = this, ed = t.ed, dom = ed.dom, applied = [], hasSameType = false, hasOppositeType = false, hasNonList = false, actions, selectedBlocks = ed.selection.getSelectedBlocks(); function cleanupBr(e) { if (e && e.tagName === 'BR') { dom.remove(e); } } function makeList(element) { var list = dom.create(targetListType), li; function adjustIndentForNewList(element) { // If there's a margin-left, outdent one level to account for the extra list margin. if (element.style.marginLeft || element.style.paddingLeft) { t.adjustPaddingFunction(false)(element); } } if (element.tagName === 'LI') { // No change required. } else if (element.tagName === 'P' || element.tagName === 'DIV' || element.tagName === 'BODY') { processBrs(element, function(startSection, br) { doWrapList(startSection, br, element.tagName === 'BODY' ? null : startSection.parentNode); li = startSection.parentNode; adjustIndentForNewList(li); cleanupBr(br); }); if (li) { if (li.tagName === 'LI' && (element.tagName === 'P' || selectedBlocks.length > 1)) { dom.split(li.parentNode.parentNode, li.parentNode); } attemptMergeWithAdjacent(li.parentNode, true); } return; } else { // Put the list around the element. li = dom.create('li'); dom.insertAfter(li, element); li.appendChild(element); adjustIndentForNewList(element); element = li; } dom.insertAfter(list, element); list.appendChild(element); attemptMergeWithAdjacent(list, true); applied.push(element); } function doWrapList(start, end, template) { var li, n = start, tmp; while (!dom.isBlock(start.parentNode) && start.parentNode !== dom.getRoot()) { start = dom.split(start.parentNode, start.previousSibling); start = start.nextSibling; n = start; } if (template) { li = template.cloneNode(true); start.parentNode.insertBefore(li, start); while (li.firstChild) dom.remove(li.firstChild); li = dom.rename(li, 'li'); } else { li = dom.create('li'); start.parentNode.insertBefore(li, start); } while (n && n != end) { tmp = n.nextSibling; li.appendChild(n); n = tmp; } if (li.childNodes.length === 0) { li.innerHTML = '<br _mce_bogus="1" />'; } makeList(li); } function processBrs(element, callback) { var startSection, previousBR, END_TO_START = 3, START_TO_END = 1, breakElements = 'br,ul,ol,p,div,h1,h2,h3,h4,h5,h6,table,blockquote,address,pre,form,center,dl'; function isAnyPartSelected(start, end) { var r = dom.createRng(), sel; bookmark.keep = true; ed.selection.moveToBookmark(bookmark); bookmark.keep = false; sel = ed.selection.getRng(true); if (!end) { end = start.parentNode.lastChild; } r.setStartBefore(start); r.setEndAfter(end); return !(r.compareBoundaryPoints(END_TO_START, sel) > 0 || r.compareBoundaryPoints(START_TO_END, sel) <= 0); } function nextLeaf(br) { if (br.nextSibling) return br.nextSibling; if (!dom.isBlock(br.parentNode) && br.parentNode !== dom.getRoot()) return nextLeaf(br.parentNode); } // Split on BRs within the range and process those. startSection = element.firstChild; // First mark the BRs that have any part of the previous section selected. var trailingContentSelected = false; each(dom.select(breakElements, element), function(br) { if (br.hasAttribute && br.hasAttribute('_mce_bogus')) { return true; // Skip the bogus Brs that are put in to appease Firefox and Safari. } if (isAnyPartSelected(startSection, br)) { dom.addClass(br, '_mce_tagged_br'); startSection = nextLeaf(br); } }); trailingContentSelected = (startSection && isAnyPartSelected(startSection, undefined)); startSection = element.firstChild; each(dom.select(breakElements, element), function(br) { // Got a section from start to br. var tmp = nextLeaf(br); if (br.hasAttribute && br.hasAttribute('_mce_bogus')) { return true; // Skip the bogus Brs that are put in to appease Firefox and Safari. } if (dom.hasClass(br, '_mce_tagged_br')) { callback(startSection, br, previousBR); previousBR = null; } else { previousBR = br; } startSection = tmp; }); if (trailingContentSelected) { callback(startSection, undefined, previousBR); } } function wrapList(element) { processBrs(element, function(startSection, br, previousBR) { // Need to indent this part doWrapList(startSection, br); cleanupBr(br); cleanupBr(previousBR); }); } function changeList(element) { if (tinymce.inArray(applied, element) !== -1) { return; } if (element.parentNode.tagName === oppositeListType) { dom.split(element.parentNode, element); makeList(element); attemptMergeWithNext(element.parentNode, false); } applied.push(element); } function convertListItemToParagraph(element) { var child, nextChild, mergedElement, splitLast; if (tinymce.inArray(applied, element) !== -1) { return; } element = splitNestedLists(element, dom); while (dom.is(element.parentNode, 'ol,ul,li')) { dom.split(element.parentNode, element); } // Push the original element we have from the selection, not the renamed one. applied.push(element); element = dom.rename(element, 'p'); mergedElement = attemptMergeWithAdjacent(element, false, ed.settings.force_br_newlines); if (mergedElement === element) { // Now split out any block elements that can't be contained within a P. // Manually iterate to ensure we handle modifications correctly (doesn't work with tinymce.each) child = element.firstChild; while (child) { if (dom.isBlock(child)) { child = dom.split(child.parentNode, child); splitLast = true; nextChild = child.nextSibling && child.nextSibling.firstChild; } else { nextChild = child.nextSibling; if (splitLast && child.tagName === 'BR') { dom.remove(child); } splitLast = false; } child = nextChild; } } } each(selectedBlocks, function(e) { e = findItemToOperateOn(e, dom); if (e.tagName === oppositeListType || (e.tagName === 'LI' && e.parentNode.tagName === oppositeListType)) { hasOppositeType = true; } else if (e.tagName === targetListType || (e.tagName === 'LI' && e.parentNode.tagName === targetListType)) { hasSameType = true; } else { hasNonList = true; } }); if (hasNonList &&!hasSameType || hasOppositeType || selectedBlocks.length === 0) { actions = { 'LI': changeList, 'H1': makeList, 'H2': makeList, 'H3': makeList, 'H4': makeList, 'H5': makeList, 'H6': makeList, 'P': makeList, 'BODY': makeList, 'DIV': selectedBlocks.length > 1 ? makeList : wrapList, defaultAction: wrapList, elements: this.selectedBlocks() }; } else { actions = { defaultAction: convertListItemToParagraph, elements: this.selectedBlocks(), processEvenIfEmpty: true }; } this.process(actions); }, indent: function() { var ed = this.ed, dom = ed.dom, indented = []; function createWrapItem(element) { var wrapItem = dom.create('li', { style: 'list-style-type: none;'}); dom.insertAfter(wrapItem, element); return wrapItem; } function createWrapList(element) { var wrapItem = createWrapItem(element), list = dom.getParent(element, 'ol,ul'), listType = list.tagName, listStyle = dom.getStyle(list, 'list-style-type'), attrs = {}, wrapList; if (listStyle !== '') { attrs.style = 'list-style-type: ' + listStyle + ';'; } wrapList = dom.create(listType, attrs); wrapItem.appendChild(wrapList); return wrapList; } function indentLI(element) { if (!hasParentInList(ed, element, indented)) { element = splitNestedLists(element, dom); var wrapList = createWrapList(element); wrapList.appendChild(element); attemptMergeWithAdjacent(wrapList.parentNode, false); attemptMergeWithAdjacent(wrapList, false); indented.push(element); } } this.process({ 'LI': indentLI, defaultAction: this.adjustPaddingFunction(true), elements: this.selectedBlocks() }); }, outdent: function(ui, elements) { var t = this, ed = t.ed, dom = ed.dom, outdented = []; function outdentLI(element) { var listElement, targetParent, align; if (!hasParentInList(ed, element, outdented)) { if (dom.getStyle(element, 'margin-left') !== '' || dom.getStyle(element, 'padding-left') !== '') { return t.adjustPaddingFunction(false)(element); } align = dom.getStyle(element, 'text-align', true); if (align === 'center' || align === 'right') { dom.setStyle(element, 'text-align', 'left'); return; } element = splitNestedLists(element, dom); listElement = element.parentNode; targetParent = element.parentNode.parentNode; if (targetParent.tagName === 'P') { dom.split(targetParent, element.parentNode); } else { dom.split(listElement, element); if (targetParent.tagName === 'LI') { // Nested list, need to split the LI and go back out to the OL/UL element. dom.split(targetParent, element); } else if (!dom.is(targetParent, 'ol,ul')) { dom.rename(element, 'p'); } } outdented.push(element); } } var listElements = elements && tinymce.is(elements, 'array') ? elements : this.selectedBlocks(); this.process({ 'LI': outdentLI, defaultAction: this.adjustPaddingFunction(false), elements: listElements }); each(outdented, attemptMergeWithAdjacent); }, process: function(actions) { var t = this, sel = t.ed.selection, dom = t.ed.dom, selectedBlocks, r; function isEmptyElement(element) { var excludeBrsAndBookmarks = tinymce.grep(element.childNodes, function(n) { return !(n.nodeName === 'BR' || n.nodeName === 'SPAN' && dom.getAttrib(n, 'data-mce-type') == 'bookmark' || n.nodeType == 3 && (n.nodeValue == String.fromCharCode(160) || n.nodeValue == '')); }); return excludeBrsAndBookmarks.length === 0; } function processElement(element) { dom.removeClass(element, '_mce_act_on'); if (!element || element.nodeType !== 1 || ! actions.processEvenIfEmpty && selectedBlocks.length > 1 && isEmptyElement(element)) { return; } element = findItemToOperateOn(element, dom); var action = actions[element.tagName]; if (!action) { action = actions.defaultAction; } action(element); } function recurse(element) { t.splitSafeEach(element.childNodes, processElement, true); } function brAtEdgeOfSelection(container, offset) { return offset >= 0 && container.hasChildNodes() && offset < container.childNodes.length && container.childNodes[offset].tagName === 'BR'; } function isInTable() { var n = sel.getNode(); var p = dom.getParent(n, 'td'); return p !== null; } selectedBlocks = actions.elements; r = sel.getRng(true); if (!r.collapsed) { if (brAtEdgeOfSelection(r.endContainer, r.endOffset - 1)) { r.setEnd(r.endContainer, r.endOffset - 1); sel.setRng(r); } if (brAtEdgeOfSelection(r.startContainer, r.startOffset)) { r.setStart(r.startContainer, r.startOffset + 1); sel.setRng(r); } } if (tinymce.isIE8) { // append a zero sized nbsp so that caret is restored correctly using bookmark var s = t.ed.selection.getNode(); if (s.tagName === 'LI' && !(s.parentNode.lastChild === s)) { var i = t.ed.getDoc().createTextNode('\uFEFF'); s.appendChild(i); } } bookmark = sel.getBookmark(); actions.OL = actions.UL = recurse; t.splitSafeEach(selectedBlocks, processElement); sel.moveToBookmark(bookmark); bookmark = null; // we avoid doing repaint in a table as this will move the caret out of the table in Firefox 3.6 if (!isInTable()) { // Avoids table or image handles being left behind in Firefox. t.ed.execCommand('mceRepaint'); } }, splitSafeEach: function(elements, f, forceClassBase) { if (forceClassBase || (tinymce.isGecko && (/Firefox\/[12]\.[0-9]/.test(navigator.userAgent) || /Firefox\/3\.[0-4]/.test(navigator.userAgent)))) { this.classBasedEach(elements, f); } else { each(elements, f); } }, classBasedEach: function(elements, f) { var dom = this.ed.dom, nodes, element; // Mark nodes each(elements, function(element) { dom.addClass(element, '_mce_act_on'); }); nodes = dom.select('._mce_act_on'); while (nodes.length > 0) { element = nodes.shift(); dom.removeClass(element, '_mce_act_on'); f(element); nodes = dom.select('._mce_act_on'); } }, adjustPaddingFunction: function(isIndent) { var indentAmount, indentUnits, ed = this.ed; indentAmount = ed.settings.indentation; indentUnits = /[a-z%]+/i.exec(indentAmount); indentAmount = parseInt(indentAmount, 10); return function(element) { var currentIndent, newIndentAmount; currentIndent = parseInt(ed.dom.getStyle(element, 'margin-left') || 0, 10) + parseInt(ed.dom.getStyle(element, 'padding-left') || 0, 10); if (isIndent) { newIndentAmount = currentIndent + indentAmount; } else { newIndentAmount = currentIndent - indentAmount; } ed.dom.setStyle(element, 'padding-left', ''); ed.dom.setStyle(element, 'margin-left', newIndentAmount > 0 ? newIndentAmount + indentUnits : ''); }; }, selectedBlocks: function() { var ed = this.ed, selectedBlocks = ed.selection.getSelectedBlocks(); return selectedBlocks.length == 0 ? [ ed.dom.getRoot() ] : selectedBlocks; }, getInfo: function() { return { longname : 'Lists', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/lists', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); tinymce.PluginManager.add("lists", tinymce.plugins.Lists); }());
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.AdvancedHRPlugin', { init : function(ed, url) { // Register commands ed.addCommand('mceAdvancedHr', function() { ed.windowManager.open({ file : url + '/rule.htm', width : 250 + parseInt(ed.getLang('advhr.delta_width', 0)), height : 160 + parseInt(ed.getLang('advhr.delta_height', 0)), inline : 1 }, { plugin_url : url }); }); // Register buttons ed.addButton('advhr', { title : 'advhr.advhr_desc', cmd : 'mceAdvancedHr' }); ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('advhr', n.nodeName == 'HR'); }); ed.onClick.add(function(ed, e) { e = e.target; if (e.nodeName === 'HR') ed.selection.select(e); }); }, getInfo : function() { return { longname : 'Advanced HR', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advhr', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('advhr', tinymce.plugins.AdvancedHRPlugin); })();
JavaScript
var AdvHRDialog = { init : function(ed) { var dom = ed.dom, f = document.forms[0], n = ed.selection.getNode(), w; w = dom.getAttrib(n, 'width'); f.width.value = w ? parseInt(w) : (dom.getStyle('width') || ''); f.size.value = dom.getAttrib(n, 'size') || parseInt(dom.getStyle('height')) || ''; f.noshade.checked = !!dom.getAttrib(n, 'noshade') || !!dom.getStyle('border-width'); selectByValue(f, 'width2', w.indexOf('%') != -1 ? '%' : 'px'); }, update : function() { var ed = tinyMCEPopup.editor, h, f = document.forms[0], st = ''; h = '<hr'; if (f.size.value) { h += ' size="' + f.size.value + '"'; st += ' height:' + f.size.value + 'px;'; } if (f.width.value) { h += ' width="' + f.width.value + (f.width2.value == '%' ? '%' : '') + '"'; st += ' width:' + f.width.value + (f.width2.value == '%' ? '%' : 'px') + ';'; } if (f.noshade.checked) { h += ' noshade="noshade"'; st += ' border-width: 1px; border-style: solid; border-color: #CCCCCC; color: #ffffff;'; } if (ed.settings.inline_styles) h += ' style="' + tinymce.trim(st) + '"'; h += ' />'; ed.execCommand("mceInsertContent", false, h); tinyMCEPopup.close(); } }; tinyMCEPopup.requireLangPack(); tinyMCEPopup.onInit.add(AdvHRDialog.init, AdvHRDialog);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.SearchReplacePlugin', { init : function(ed, url) { function open(m) { // Keep IE from writing out the f/r character to the editor // instance while initializing a new dialog. See: #3131190 window.focus(); ed.windowManager.open({ file : url + '/searchreplace.htm', width : 420 + parseInt(ed.getLang('searchreplace.delta_width', 0)), height : 170 + parseInt(ed.getLang('searchreplace.delta_height', 0)), inline : 1, auto_focus : 0 }, { mode : m, search_string : ed.selection.getContent({format : 'text'}), plugin_url : url }); }; // Register commands ed.addCommand('mceSearch', function() { open('search'); }); ed.addCommand('mceReplace', function() { open('replace'); }); // Register buttons ed.addButton('search', {title : 'searchreplace.search_desc', cmd : 'mceSearch'}); ed.addButton('replace', {title : 'searchreplace.replace_desc', cmd : 'mceReplace'}); ed.addShortcut('ctrl+f', 'searchreplace.search_desc', 'mceSearch'); }, getInfo : function() { return { longname : 'Search/Replace', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/searchreplace', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('searchreplace', tinymce.plugins.SearchReplacePlugin); })();
JavaScript
tinyMCEPopup.requireLangPack(); var SearchReplaceDialog = { init : function(ed) { var t = this, f = document.forms[0], m = tinyMCEPopup.getWindowArg("mode"); t.switchMode(m); f[m + '_panel_searchstring'].value = tinyMCEPopup.getWindowArg("search_string"); // Focus input field f[m + '_panel_searchstring'].focus(); mcTabs.onChange.add(function(tab_id, panel_id) { t.switchMode(tab_id.substring(0, tab_id.indexOf('_'))); }); }, switchMode : function(m) { var f, lm = this.lastMode; if (lm != m) { f = document.forms[0]; if (lm) { f[m + '_panel_searchstring'].value = f[lm + '_panel_searchstring'].value; f[m + '_panel_backwardsu'].checked = f[lm + '_panel_backwardsu'].checked; f[m + '_panel_backwardsd'].checked = f[lm + '_panel_backwardsd'].checked; f[m + '_panel_casesensitivebox'].checked = f[lm + '_panel_casesensitivebox'].checked; } mcTabs.displayTab(m + '_tab', m + '_panel'); document.getElementById("replaceBtn").style.display = (m == "replace") ? "inline" : "none"; document.getElementById("replaceAllBtn").style.display = (m == "replace") ? "inline" : "none"; this.lastMode = m; } }, searchNext : function(a) { var ed = tinyMCEPopup.editor, se = ed.selection, r = se.getRng(), f, m = this.lastMode, s, b, fl = 0, w = ed.getWin(), wm = ed.windowManager, fo = 0; // Get input f = document.forms[0]; s = f[m + '_panel_searchstring'].value; b = f[m + '_panel_backwardsu'].checked; ca = f[m + '_panel_casesensitivebox'].checked; rs = f['replace_panel_replacestring'].value; if (tinymce.isIE) { r = ed.getDoc().selection.createRange(); } if (s == '') return; function fix() { // Correct Firefox graphics glitches // TODO: Verify if this is actually needed any more, maybe it was for very old FF versions? r = se.getRng().cloneRange(); ed.getDoc().execCommand('SelectAll', false, null); se.setRng(r); }; function replace() { ed.selection.setContent(rs); // Needs to be duplicated due to selection bug in IE }; // IE flags if (ca) fl = fl | 4; switch (a) { case 'all': // Move caret to beginning of text ed.execCommand('SelectAll'); ed.selection.collapse(true); if (tinymce.isIE) { ed.focus(); r = ed.getDoc().selection.createRange(); while (r.findText(s, b ? -1 : 1, fl)) { r.scrollIntoView(); r.select(); replace(); fo = 1; if (b) { r.moveEnd("character", -(rs.length)); // Otherwise will loop forever } } tinyMCEPopup.storeSelection(); } else { while (w.find(s, ca, b, false, false, false, false)) { replace(); fo = 1; } } if (fo) tinyMCEPopup.alert(ed.getLang('searchreplace_dlg.allreplaced')); else tinyMCEPopup.alert(ed.getLang('searchreplace_dlg.notfound')); return; case 'current': if (!ed.selection.isCollapsed()) replace(); break; } se.collapse(b); r = se.getRng(); // Whats the point if (!s) return; if (tinymce.isIE) { ed.focus(); r = ed.getDoc().selection.createRange(); if (r.findText(s, b ? -1 : 1, fl)) { r.scrollIntoView(); r.select(); } else tinyMCEPopup.alert(ed.getLang('searchreplace_dlg.notfound')); tinyMCEPopup.storeSelection(); } else { if (!w.find(s, ca, b, false, false, false, false)) tinyMCEPopup.alert(ed.getLang('searchreplace_dlg.notfound')); else fix(); } } }; tinyMCEPopup.onInit.add(SearchReplaceDialog.init, SearchReplaceDialog);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing * * Adds auto-save capability to the TinyMCE text editor to rescue content * inadvertently lost. This plugin was originally developed by Speednet * and that project can be found here: http://code.google.com/p/tinyautosave/ * * TECHNOLOGY DISCUSSION: * * The plugin attempts to use the most advanced features available in the current browser to save * as much content as possible. There are a total of four different methods used to autosave the * content. In order of preference, they are: * * 1. localStorage - A new feature of HTML 5, localStorage can store megabytes of data per domain * on the client computer. Data stored in the localStorage area has no expiration date, so we must * manage expiring the data ourselves. localStorage is fully supported by IE8, and it is supposed * to be working in Firefox 3 and Safari 3.2, but in reality is is flaky in those browsers. As * HTML 5 gets wider support, the AutoSave plugin will use it automatically. In Windows Vista/7, * localStorage is stored in the following folder: * C:\Users\[username]\AppData\Local\Microsoft\Internet Explorer\DOMStore\[tempFolder] * * 2. sessionStorage - A new feature of HTML 5, sessionStorage works similarly to localStorage, * except it is designed to expire after a certain amount of time. Because the specification * around expiration date/time is very loosely-described, it is preferrable to use locaStorage and * manage the expiration ourselves. sessionStorage has similar storage characteristics to * localStorage, although it seems to have better support by Firefox 3 at the moment. (That will * certainly change as Firefox continues getting better at HTML 5 adoption.) * * 3. UserData - A very under-exploited feature of Microsoft Internet Explorer, UserData is a * way to store up to 128K of data per "document", or up to 1MB of data per domain, on the client * computer. The feature is available for IE 5+, which makes it available for every version of IE * supported by TinyMCE. The content is persistent across browser restarts and expires on the * date/time specified, just like a cookie. However, the data is not cleared when the user clears * cookies on the browser, which makes it well-suited for rescuing autosaved content. UserData, * like other Microsoft IE browser technologies, is implemented as a behavior attached to a * specific DOM object, so in this case we attach the behavior to the same DOM element that the * TinyMCE editor instance is attached to. */ (function(tinymce) { // Setup constants to help the compressor to reduce script size var PLUGIN_NAME = 'autosave', RESTORE_DRAFT = 'restoredraft', TRUE = true, undefined, unloadHandlerAdded, Dispatcher = tinymce.util.Dispatcher; /** * This plugin adds auto-save capability to the TinyMCE text editor to rescue content * inadvertently lost. By using localStorage. * * @class tinymce.plugins.AutoSave */ tinymce.create('tinymce.plugins.AutoSave', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @method init * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { var self = this, settings = ed.settings; self.editor = ed; // Parses the specified time string into a milisecond number 10m, 10s etc. function parseTime(time) { var multipels = { s : 1000, m : 60000 }; time = /^(\d+)([ms]?)$/.exec('' + time); return (time[2] ? multipels[time[2]] : 1) * parseInt(time); }; // Default config tinymce.each({ ask_before_unload : TRUE, interval : '30s', retention : '20m', minlength : 50 }, function(value, key) { key = PLUGIN_NAME + '_' + key; if (settings[key] === undefined) settings[key] = value; }); // Parse times settings.autosave_interval = parseTime(settings.autosave_interval); settings.autosave_retention = parseTime(settings.autosave_retention); // Register restore button ed.addButton(RESTORE_DRAFT, { title : PLUGIN_NAME + ".restore_content", onclick : function() { if (ed.getContent({draft: true}).replace(/\s|&nbsp;|<\/?p[^>]*>|<br[^>]*>/gi, "").length > 0) { // Show confirm dialog if the editor isn't empty ed.windowManager.confirm( PLUGIN_NAME + ".warning_message", function(ok) { if (ok) self.restoreDraft(); } ); } else self.restoreDraft(); } }); // Enable/disable restoredraft button depending on if there is a draft stored or not ed.onNodeChange.add(function() { var controlManager = ed.controlManager; if (controlManager.get(RESTORE_DRAFT)) controlManager.setDisabled(RESTORE_DRAFT, !self.hasDraft()); }); ed.onInit.add(function() { // Check if the user added the restore button, then setup auto storage logic if (ed.controlManager.get(RESTORE_DRAFT)) { // Setup storage engine self.setupStorage(ed); // Auto save contents each interval time setInterval(function() { if (!ed.removed) { self.storeDraft(); ed.nodeChanged(); } }, settings.autosave_interval); } }); /** * This event gets fired when a draft is stored to local storage. * * @event onStoreDraft * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event. * @param {Object} draft Draft object containing the HTML contents of the editor. */ self.onStoreDraft = new Dispatcher(self); /** * This event gets fired when a draft is restored from local storage. * * @event onStoreDraft * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event. * @param {Object} draft Draft object containing the HTML contents of the editor. */ self.onRestoreDraft = new Dispatcher(self); /** * This event gets fired when a draft removed/expired. * * @event onRemoveDraft * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event. * @param {Object} draft Draft object containing the HTML contents of the editor. */ self.onRemoveDraft = new Dispatcher(self); // Add ask before unload dialog only add one unload handler if (!unloadHandlerAdded) { window.onbeforeunload = tinymce.plugins.AutoSave._beforeUnloadHandler; unloadHandlerAdded = TRUE; } }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @method getInfo * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'Auto save', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autosave', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, /** * Returns an expiration date UTC string. * * @method getExpDate * @return {String} Expiration date UTC string. */ getExpDate : function() { return new Date( new Date().getTime() + this.editor.settings.autosave_retention ).toUTCString(); }, /** * This method will setup the storage engine. If the browser has support for it. * * @method setupStorage */ setupStorage : function(ed) { var self = this, testKey = PLUGIN_NAME + '_test', testVal = "OK"; self.key = PLUGIN_NAME + ed.id; // Loop though each storage engine type until we find one that works tinymce.each([ function() { // Try HTML5 Local Storage if (localStorage) { localStorage.setItem(testKey, testVal); if (localStorage.getItem(testKey) === testVal) { localStorage.removeItem(testKey); return localStorage; } } }, function() { // Try HTML5 Session Storage if (sessionStorage) { sessionStorage.setItem(testKey, testVal); if (sessionStorage.getItem(testKey) === testVal) { sessionStorage.removeItem(testKey); return sessionStorage; } } }, function() { // Try IE userData if (tinymce.isIE) { ed.getElement().style.behavior = "url('#default#userData')"; // Fake localStorage on old IE return { autoExpires : TRUE, setItem : function(key, value) { var userDataElement = ed.getElement(); userDataElement.setAttribute(key, value); userDataElement.expires = self.getExpDate(); try { userDataElement.save("TinyMCE"); } catch (e) { // Ignore, saving might fail if "Userdata Persistence" is disabled in IE } }, getItem : function(key) { var userDataElement = ed.getElement(); try { userDataElement.load("TinyMCE"); return userDataElement.getAttribute(key); } catch (e) { // Ignore, loading might fail if "Userdata Persistence" is disabled in IE return null; } }, removeItem : function(key) { ed.getElement().removeAttribute(key); } }; } }, ], function(setup) { // Try executing each function to find a suitable storage engine try { self.storage = setup(); if (self.storage) return false; } catch (e) { // Ignore } }); }, /** * This method will store the current contents in the the storage engine. * * @method storeDraft */ storeDraft : function() { var self = this, storage = self.storage, editor = self.editor, expires, content; // Is the contents dirty if (storage) { // If there is no existing key and the contents hasn't been changed since // it's original value then there is no point in saving a draft if (!storage.getItem(self.key) && !editor.isDirty()) return; // Store contents if the contents if longer than the minlength of characters content = editor.getContent({draft: true}); if (content.length > editor.settings.autosave_minlength) { expires = self.getExpDate(); // Store expiration date if needed IE userData has auto expire built in if (!self.storage.autoExpires) self.storage.setItem(self.key + "_expires", expires); self.storage.setItem(self.key, content); self.onStoreDraft.dispatch(self, { expires : expires, content : content }); } } }, /** * This method will restore the contents from the storage engine back to the editor. * * @method restoreDraft */ restoreDraft : function() { var self = this, storage = self.storage, content; if (storage) { content = storage.getItem(self.key); if (content) { self.editor.setContent(content); self.onRestoreDraft.dispatch(self, { content : content }); } } }, /** * This method will return true/false if there is a local storage draft available. * * @method hasDraft * @return {boolean} true/false state if there is a local draft. */ hasDraft : function() { var self = this, storage = self.storage, expDate, exists; if (storage) { // Does the item exist at all exists = !!storage.getItem(self.key); if (exists) { // Storage needs autoexpire if (!self.storage.autoExpires) { expDate = new Date(storage.getItem(self.key + "_expires")); // Contents hasn't expired if (new Date().getTime() < expDate.getTime()) return TRUE; // Remove it if it has self.removeDraft(); } else return TRUE; } } return false; }, /** * Removes the currently stored draft. * * @method removeDraft */ removeDraft : function() { var self = this, storage = self.storage, key = self.key, content; if (storage) { // Get current contents and remove the existing draft content = storage.getItem(key); storage.removeItem(key); storage.removeItem(key + "_expires"); // Dispatch remove event if we had any contents if (content) { self.onRemoveDraft.dispatch(self, { content : content }); } } }, "static" : { // Internal unload handler will be called before the page is unloaded _beforeUnloadHandler : function(e) { var msg; tinymce.each(tinyMCE.editors, function(ed) { // Store a draft for each editor instance if (ed.plugins.autosave) ed.plugins.autosave.storeDraft(); // Never ask in fullscreen mode if (ed.getParam("fullscreen_is_enabled")) return; // Setup a return message if the editor is dirty if (!msg && ed.isDirty() && ed.getParam("autosave_ask_before_unload")) msg = ed.getLang("autosave.unload_msg"); }); return msg; } } }); tinymce.PluginManager.add('autosave', tinymce.plugins.AutoSave); })(tinymce);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var each = tinymce.each; tinymce.create('tinymce.plugins.TemplatePlugin', { init : function(ed, url) { var t = this; t.editor = ed; // Register commands ed.addCommand('mceTemplate', function(ui) { ed.windowManager.open({ file : url + '/template.htm', width : ed.getParam('template_popup_width', 750), height : ed.getParam('template_popup_height', 600), inline : 1 }, { plugin_url : url }); }); ed.addCommand('mceInsertTemplate', t._insertTemplate, t); // Register buttons ed.addButton('template', {title : 'template.desc', cmd : 'mceTemplate'}); ed.onPreProcess.add(function(ed, o) { var dom = ed.dom; each(dom.select('div', o.node), function(e) { if (dom.hasClass(e, 'mceTmpl')) { each(dom.select('*', e), function(e) { if (dom.hasClass(e, ed.getParam('template_mdate_classes', 'mdate').replace(/\s+/g, '|'))) e.innerHTML = t._getDateTime(new Date(), ed.getParam("template_mdate_format", ed.getLang("template.mdate_format"))); }); t._replaceVals(e); } }); }); }, getInfo : function() { return { longname : 'Template plugin', author : 'Moxiecode Systems AB', authorurl : 'http://www.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/template', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, _insertTemplate : function(ui, v) { var t = this, ed = t.editor, h, el, dom = ed.dom, sel = ed.selection.getContent(); h = v.content; each(t.editor.getParam('template_replace_values'), function(v, k) { if (typeof(v) != 'function') h = h.replace(new RegExp('\\{\\$' + k + '\\}', 'g'), v); }); el = dom.create('div', null, h); // Find template element within div n = dom.select('.mceTmpl', el); if (n && n.length > 0) { el = dom.create('div', null); el.appendChild(n[0].cloneNode(true)); } function hasClass(n, c) { return new RegExp('\\b' + c + '\\b', 'g').test(n.className); }; each(dom.select('*', el), function(n) { // Replace cdate if (hasClass(n, ed.getParam('template_cdate_classes', 'cdate').replace(/\s+/g, '|'))) n.innerHTML = t._getDateTime(new Date(), ed.getParam("template_cdate_format", ed.getLang("template.cdate_format"))); // Replace mdate if (hasClass(n, ed.getParam('template_mdate_classes', 'mdate').replace(/\s+/g, '|'))) n.innerHTML = t._getDateTime(new Date(), ed.getParam("template_mdate_format", ed.getLang("template.mdate_format"))); // Replace selection if (hasClass(n, ed.getParam('template_selected_content_classes', 'selcontent').replace(/\s+/g, '|'))) n.innerHTML = sel; }); t._replaceVals(el); ed.execCommand('mceInsertContent', false, el.innerHTML); ed.addVisual(); }, _replaceVals : function(e) { var dom = this.editor.dom, vl = this.editor.getParam('template_replace_values'); each(dom.select('*', e), function(e) { each(vl, function(v, k) { if (dom.hasClass(e, k)) { if (typeof(vl[k]) == 'function') vl[k](e); } }); }); }, _getDateTime : function(d, fmt) { if (!fmt) return ""; function addZeros(value, len) { var i; value = "" + value; if (value.length < len) { for (i=0; i<(len-value.length); i++) value = "0" + value; } return value; } fmt = fmt.replace("%D", "%m/%d/%y"); fmt = fmt.replace("%r", "%I:%M:%S %p"); fmt = fmt.replace("%Y", "" + d.getFullYear()); fmt = fmt.replace("%y", "" + d.getYear()); fmt = fmt.replace("%m", addZeros(d.getMonth()+1, 2)); fmt = fmt.replace("%d", addZeros(d.getDate(), 2)); fmt = fmt.replace("%H", "" + addZeros(d.getHours(), 2)); fmt = fmt.replace("%M", "" + addZeros(d.getMinutes(), 2)); fmt = fmt.replace("%S", "" + addZeros(d.getSeconds(), 2)); fmt = fmt.replace("%I", "" + ((d.getHours() + 11) % 12 + 1)); fmt = fmt.replace("%p", "" + (d.getHours() < 12 ? "AM" : "PM")); fmt = fmt.replace("%B", "" + this.editor.getLang("template_months_long").split(',')[d.getMonth()]); fmt = fmt.replace("%b", "" + this.editor.getLang("template_months_short").split(',')[d.getMonth()]); fmt = fmt.replace("%A", "" + this.editor.getLang("template_day_long").split(',')[d.getDay()]); fmt = fmt.replace("%a", "" + this.editor.getLang("template_day_short").split(',')[d.getDay()]); fmt = fmt.replace("%%", "%"); return fmt; } }); // Register plugin tinymce.PluginManager.add('template', tinymce.plugins.TemplatePlugin); })();
JavaScript
tinyMCEPopup.requireLangPack(); var TemplateDialog = { preInit : function() { var url = tinyMCEPopup.getParam("template_external_list_url"); if (url != null) document.write('<sc'+'ript language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></sc'+'ript>'); }, init : function() { var ed = tinyMCEPopup.editor, tsrc, sel, x, u; tsrc = ed.getParam("template_templates", false); sel = document.getElementById('tpath'); // Setup external template list if (!tsrc && typeof(tinyMCETemplateList) != 'undefined') { for (x=0, tsrc = []; x<tinyMCETemplateList.length; x++) tsrc.push({title : tinyMCETemplateList[x][0], src : tinyMCETemplateList[x][1], description : tinyMCETemplateList[x][2]}); } for (x=0; x<tsrc.length; x++) sel.options[sel.options.length] = new Option(tsrc[x].title, tinyMCEPopup.editor.documentBaseURI.toAbsolute(tsrc[x].src)); this.resize(); this.tsrc = tsrc; }, resize : function() { var w, h, e; if (!self.innerWidth) { w = document.body.clientWidth - 50; h = document.body.clientHeight - 160; } else { w = self.innerWidth - 50; h = self.innerHeight - 170; } e = document.getElementById('templatesrc'); if (e) { e.style.height = Math.abs(h) + 'px'; e.style.width = Math.abs(w - 5) + 'px'; } }, loadCSSFiles : function(d) { var ed = tinyMCEPopup.editor; tinymce.each(ed.getParam("content_css", '').split(','), function(u) { d.write('<link href="' + ed.documentBaseURI.toAbsolute(u) + '" rel="stylesheet" type="text/css" />'); }); }, selectTemplate : function(u, ti) { var d = window.frames['templatesrc'].document, x, tsrc = this.tsrc; if (!u) return; d.body.innerHTML = this.templateHTML = this.getFileContents(u); for (x=0; x<tsrc.length; x++) { if (tsrc[x].title == ti) document.getElementById('tmpldesc').innerHTML = tsrc[x].description || ''; } }, insert : function() { tinyMCEPopup.execCommand('mceInsertTemplate', false, { content : this.templateHTML, selection : tinyMCEPopup.editor.selection.getContent() }); tinyMCEPopup.close(); }, getFileContents : function(u) { var x, d, t = 'text/plain'; function g(s) { x = 0; try { x = new ActiveXObject(s); } catch (s) { } return x; }; x = window.ActiveXObject ? g('Msxml2.XMLHTTP') || g('Microsoft.XMLHTTP') : new XMLHttpRequest(); // Synchronous AJAX load file x.overrideMimeType && x.overrideMimeType(t); x.open("GET", u, false); x.send(null); return x.responseText; } }; TemplateDialog.preInit(); tinyMCEPopup.onInit.add(TemplateDialog.init, TemplateDialog);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing * * This plugin will force TinyMCE to produce deprecated legacy output such as font elements, u elements, align * attributes and so forth. There are a few cases where these old items might be needed for example in email applications or with Flash * * However you should NOT use this plugin if you are building some system that produces web contents such as a CMS. All these elements are * not apart of the newer specifications for HTML and XHTML. */ (function(tinymce) { // Override inline_styles setting to force TinyMCE to produce deprecated contents tinymce.onAddEditor.addToTop(function(tinymce, editor) { editor.settings.inline_styles = false; }); // Create the legacy ouput plugin tinymce.create('tinymce.plugins.LegacyOutput', { init : function(editor) { editor.onInit.add(function() { var alignElements = 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', fontSizes = tinymce.explode(editor.settings.font_size_style_values), schema = editor.schema; // Override some internal formats to produce legacy elements and attributes editor.formatter.register({ // Change alignment formats to use the deprecated align attribute alignleft : {selector : alignElements, attributes : {align : 'left'}}, aligncenter : {selector : alignElements, attributes : {align : 'center'}}, alignright : {selector : alignElements, attributes : {align : 'right'}}, alignfull : {selector : alignElements, attributes : {align : 'justify'}}, // Change the basic formatting elements to use deprecated element types bold : [ {inline : 'b', remove : 'all'}, {inline : 'strong', remove : 'all'}, {inline : 'span', styles : {fontWeight : 'bold'}} ], italic : [ {inline : 'i', remove : 'all'}, {inline : 'em', remove : 'all'}, {inline : 'span', styles : {fontStyle : 'italic'}} ], underline : [ {inline : 'u', remove : 'all'}, {inline : 'span', styles : {textDecoration : 'underline'}, exact : true} ], strikethrough : [ {inline : 'strike', remove : 'all'}, {inline : 'span', styles : {textDecoration: 'line-through'}, exact : true} ], // Change font size and font family to use the deprecated font element fontname : {inline : 'font', attributes : {face : '%value'}}, fontsize : { inline : 'font', attributes : { size : function(vars) { return tinymce.inArray(fontSizes, vars.value) + 1; } } }, // Setup font elements for colors as well forecolor : {inline : 'font', attributes : {color : '%value'}}, hilitecolor : {inline : 'font', styles : {backgroundColor : '%value'}} }); // Check that deprecated elements are allowed if not add them tinymce.each('b,i,u,strike'.split(','), function(name) { schema.addValidElements(name + '[*]'); }); // Add font element if it's missing if (!schema.getElementRule("font")) schema.addValidElements("font[face|size|color|style]"); // Add the missing and depreacted align attribute for the serialization engine tinymce.each(alignElements.split(','), function(name) { var rule = schema.getElementRule(name), found; if (rule) { if (!rule.attributes.align) { rule.attributes.align = {}; rule.attributesOrder.push('align'); } } }); // Listen for the onNodeChange event so that we can do special logic for the font size and font name drop boxes editor.onNodeChange.add(function(editor, control_manager) { var control, fontElm, fontName, fontSize; // Find font element get it's name and size fontElm = editor.dom.getParent(editor.selection.getNode(), 'font'); if (fontElm) { fontName = fontElm.face; fontSize = fontElm.size; } // Select/unselect the font name in droplist if (control = control_manager.get('fontselect')) { control.select(function(value) { return value == fontName; }); } // Select/unselect the font size in droplist if (control = control_manager.get('fontsizeselect')) { control.select(function(value) { var index = tinymce.inArray(fontSizes, value.fontSize); return index + 1 == fontSize; }); } }); }); }, getInfo : function() { return { longname : 'LegacyOutput', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/legacyoutput', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('legacyoutput', tinymce.plugins.LegacyOutput); })(tinymce);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var each = tinymce.each, Node = tinymce.html.Node; tinymce.create('tinymce.plugins.FullPagePlugin', { init : function(ed, url) { var t = this; t.editor = ed; // Register commands ed.addCommand('mceFullPageProperties', function() { ed.windowManager.open({ file : url + '/fullpage.htm', width : 430 + parseInt(ed.getLang('fullpage.delta_width', 0)), height : 495 + parseInt(ed.getLang('fullpage.delta_height', 0)), inline : 1 }, { plugin_url : url, data : t._htmlToData() }); }); // Register buttons ed.addButton('fullpage', {title : 'fullpage.desc', cmd : 'mceFullPageProperties'}); ed.onBeforeSetContent.add(t._setContent, t); ed.onGetContent.add(t._getContent, t); }, getInfo : function() { return { longname : 'Fullpage', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/fullpage', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private plugin internal methods _htmlToData : function() { var headerFragment = this._parseHeader(), data = {}, nodes, elm, matches, editor = this.editor; function getAttr(elm, name) { var value = elm.attr(name); return value || ''; }; // Default some values data.fontface = editor.getParam("fullpage_default_fontface", ""); data.fontsize = editor.getParam("fullpage_default_fontsize", ""); // Parse XML PI elm = headerFragment.firstChild; if (elm.type == 7) { data.xml_pi = true; matches = /encoding="([^"]+)"/.exec(elm.value); if (matches) data.docencoding = matches[1]; } // Parse doctype elm = headerFragment.getAll('#doctype')[0]; if (elm) data.doctype = '<!DOCTYPE' + elm.value + ">"; // Parse title element elm = headerFragment.getAll('title')[0]; if (elm && elm.firstChild) { data.metatitle = elm.firstChild.value; } // Parse meta elements each(headerFragment.getAll('meta'), function(meta) { var name = meta.attr('name'), httpEquiv = meta.attr('http-equiv'), matches; if (name) data['meta' + name.toLowerCase()] = meta.attr('content'); else if (httpEquiv == "Content-Type") { matches = /charset\s*=\s*(.*)\s*/gi.exec(meta.attr('content')); if (matches) data.docencoding = matches[1]; } }); // Parse html attribs elm = headerFragment.getAll('html')[0]; if (elm) data.langcode = getAttr(elm, 'lang') || getAttr(elm, 'xml:lang'); // Parse stylesheet elm = headerFragment.getAll('link')[0]; if (elm && elm.attr('rel') == 'stylesheet') data.stylesheet = elm.attr('href'); // Parse body parts elm = headerFragment.getAll('body')[0]; if (elm) { data.langdir = getAttr(elm, 'dir'); data.style = getAttr(elm, 'style'); data.visited_color = getAttr(elm, 'vlink'); data.link_color = getAttr(elm, 'link'); data.active_color = getAttr(elm, 'alink'); } return data; }, _dataToHtml : function(data) { var headerFragment, headElement, html, elm, value, dom = this.editor.dom; function setAttr(elm, name, value) { elm.attr(name, value ? value : undefined); }; function addHeadNode(node) { if (headElement.firstChild) headElement.insert(node, headElement.firstChild); else headElement.append(node); }; headerFragment = this._parseHeader(); headElement = headerFragment.getAll('head')[0]; if (!headElement) { elm = headerFragment.getAll('html')[0]; headElement = new Node('head', 1); if (elm.firstChild) elm.insert(headElement, elm.firstChild, true); else elm.append(headElement); } // Add/update/remove XML-PI elm = headerFragment.firstChild; if (data.xml_pi) { value = 'version="1.0"'; if (data.docencoding) value += ' encoding="' + data.docencoding + '"'; if (elm.type != 7) { elm = new Node('xml', 7); headerFragment.insert(elm, headerFragment.firstChild, true); } elm.value = value; } else if (elm && elm.type == 7) elm.remove(); // Add/update/remove doctype elm = headerFragment.getAll('#doctype')[0]; if (data.doctype) { if (!elm) { elm = new Node('#doctype', 10); if (data.xml_pi) headerFragment.insert(elm, headerFragment.firstChild); else addHeadNode(elm); } elm.value = data.doctype.substring(9, data.doctype.length - 1); } else if (elm) elm.remove(); // Add/update/remove title elm = headerFragment.getAll('title')[0]; if (data.metatitle) { if (!elm) { elm = new Node('title', 1); elm.append(new Node('#text', 3)).value = data.metatitle; addHeadNode(elm); } } // Add meta encoding if (data.docencoding) { elm = null; each(headerFragment.getAll('meta'), function(meta) { if (meta.attr('http-equiv') == 'Content-Type') elm = meta; }); if (!elm) { elm = new Node('meta', 1); elm.attr('http-equiv', 'Content-Type'); elm.shortEnded = true; addHeadNode(elm); } elm.attr('content', 'text/html; charset=' + data.docencoding); } // Add/update/remove meta each('keywords,description,author,copyright,robots'.split(','), function(name) { var nodes = headerFragment.getAll('meta'), i, meta, value = data['meta' + name]; for (i = 0; i < nodes.length; i++) { meta = nodes[i]; if (meta.attr('name') == name) { if (value) meta.attr('content', value); else meta.remove(); return; } } if (value) { elm = new Node('meta', 1); elm.attr('name', name); elm.attr('content', value); elm.shortEnded = true; addHeadNode(elm); } }); // Add/update/delete link elm = headerFragment.getAll('link')[0]; if (elm && elm.attr('rel') == 'stylesheet') { if (data.stylesheet) elm.attr('href', data.stylesheet); else elm.remove(); } else if (data.stylesheet) { elm = new Node('link', 1); elm.attr({ rel : 'stylesheet', text : 'text/css', href : data.stylesheet }); elm.shortEnded = true; addHeadNode(elm); } // Update body attributes elm = headerFragment.getAll('body')[0]; if (elm) { setAttr(elm, 'dir', data.langdir); setAttr(elm, 'style', data.style); setAttr(elm, 'vlink', data.visited_color); setAttr(elm, 'link', data.link_color); setAttr(elm, 'alink', data.active_color); // Update iframe body as well dom.setAttribs(this.editor.getBody(), { style : data.style, dir : data.dir, vLink : data.visited_color, link : data.link_color, aLink : data.active_color }); } // Set html attributes elm = headerFragment.getAll('html')[0]; if (elm) { setAttr(elm, 'lang', data.langcode); setAttr(elm, 'xml:lang', data.langcode); } // Serialize header fragment and crop away body part html = new tinymce.html.Serializer({ validate: false, indent: true, apply_source_formatting : true, indent_before: 'head,html,body,meta,title,script,link,style', indent_after: 'head,html,body,meta,title,script,link,style' }).serialize(headerFragment); this.head = html.substring(0, html.indexOf('</body>')); }, _parseHeader : function() { // Parse the contents with a DOM parser return new tinymce.html.DomParser({ validate: false, root_name: '#document' }).parse(this.head); }, _setContent : function(ed, o) { var self = this, startPos, endPos, content = o.content, headerFragment, styles = '', dom = self.editor.dom, elm; function low(s) { return s.replace(/<\/?[A-Z]+/g, function(a) { return a.toLowerCase(); }) }; // Ignore raw updated if we already have a head, this will fix issues with undo/redo keeping the head/foot separate if (o.format == 'raw' && self.head) return; if (o.source_view && ed.getParam('fullpage_hide_in_source_view')) return; // Parse out head, body and footer content = content.replace(/<(\/?)BODY/gi, '<$1body'); startPos = content.indexOf('<body'); if (startPos != -1) { startPos = content.indexOf('>', startPos); self.head = low(content.substring(0, startPos + 1)); endPos = content.indexOf('</body', startPos); if (endPos == -1) endPos = content.length; o.content = content.substring(startPos + 1, endPos); self.foot = low(content.substring(endPos)); } else { self.head = this._getDefaultHeader(); self.foot = '\n</body>\n</html>'; } // Parse header and update iframe headerFragment = self._parseHeader(); each(headerFragment.getAll('style'), function(node) { if (node.firstChild) styles += node.firstChild.value; }); elm = headerFragment.getAll('body')[0]; if (elm) { dom.setAttribs(self.editor.getBody(), { style : elm.attr('style') || '', dir : elm.attr('dir') || '', vLink : elm.attr('vlink') || '', link : elm.attr('link') || '', aLink : elm.attr('alink') || '' }); } dom.remove('fullpage_styles'); if (styles) { dom.add(self.editor.getDoc().getElementsByTagName('head')[0], 'style', {id : 'fullpage_styles'}, styles); // Needed for IE 6/7 elm = dom.get('fullpage_styles'); if (elm.styleSheet) elm.styleSheet.cssText = styles; } }, _getDefaultHeader : function() { var header = '', editor = this.editor, value, styles = ''; if (editor.getParam('fullpage_default_xml_pi')) header += '<?xml version="1.0" encoding="' + editor.getParam('fullpage_default_encoding', 'ISO-8859-1') + '" ?>\n'; header += editor.getParam('fullpage_default_doctype', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'); header += '\n<html>\n<head>\n'; if (value = editor.getParam('fullpage_default_title')) header += '<title>' + value + '</title>\n'; if (value = editor.getParam('fullpage_default_encoding')) header += '<meta http-equiv="Content-Type" content="text/html; charset=' + value + '" />\n'; if (value = editor.getParam('fullpage_default_font_family')) styles += 'font-family: ' + value + ';'; if (value = editor.getParam('fullpage_default_font_size')) styles += 'font-size: ' + value + ';'; if (value = editor.getParam('fullpage_default_text_color')) styles += 'color: ' + value + ';'; header += '</head>\n<body' + (styles ? ' style="' + styles + '"' : '') + '>\n'; return header; }, _getContent : function(ed, o) { var self = this; if (!o.source_view || !ed.getParam('fullpage_hide_in_source_view')) o.content = tinymce.trim(self.head) + '\n' + tinymce.trim(o.content) + '\n' + tinymce.trim(self.foot); } }); // Register plugin tinymce.PluginManager.add('fullpage', tinymce.plugins.FullPagePlugin); })();
JavaScript
/** * fullpage.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinyMCEPopup.requireLangPack(); var defaultDocTypes = 'XHTML 1.0 Transitional=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">,' + 'XHTML 1.0 Frameset=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">,' + 'XHTML 1.0 Strict=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">,' + 'XHTML 1.1=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">,' + 'HTML 4.01 Transitional=<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">,' + 'HTML 4.01 Strict=<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">,' + 'HTML 4.01 Frameset=<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'; var defaultEncodings = 'Western european (iso-8859-1)=iso-8859-1,' + 'Central European (iso-8859-2)=iso-8859-2,' + 'Unicode (UTF-8)=utf-8,' + 'Chinese traditional (Big5)=big5,' + 'Cyrillic (iso-8859-5)=iso-8859-5,' + 'Japanese (iso-2022-jp)=iso-2022-jp,' + 'Greek (iso-8859-7)=iso-8859-7,' + 'Korean (iso-2022-kr)=iso-2022-kr,' + 'ASCII (us-ascii)=us-ascii'; var defaultFontNames = 'Arial=arial,helvetica,sans-serif;Courier New=courier new,courier,monospace;Georgia=georgia,times new roman,times,serif;Tahoma=tahoma,arial,helvetica,sans-serif;Times New Roman=times new roman,times,serif;Verdana=verdana,arial,helvetica,sans-serif;Impact=impact;WingDings=wingdings'; var defaultFontSizes = '10px,11px,12px,13px,14px,15px,16px'; function setVal(id, value) { var elm = document.getElementById(id); if (elm) { value = value || ''; if (elm.nodeName == "SELECT") selectByValue(document.forms[0], id, value); else if (elm.type == "checkbox") elm.checked = !!value; else elm.value = value; } }; function getVal(id) { var elm = document.getElementById(id); if (elm.nodeName == "SELECT") return elm.options[elm.selectedIndex].value; if (elm.type == "checkbox") return elm.checked; return elm.value; }; window.FullPageDialog = { changedStyle : function() { var val, styles = tinyMCEPopup.editor.dom.parseStyle(getVal('style')); setVal('fontface', styles['font-face']); setVal('fontsize', styles['font-size']); setVal('textcolor', styles['color']); if (val = styles['background-image']) setVal('bgimage', val.replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1")); else setVal('bgimage', ''); setVal('bgcolor', styles['background-color']); // Reset margin form elements setVal('topmargin', ''); setVal('rightmargin', ''); setVal('bottommargin', ''); setVal('leftmargin', ''); // Expand margin if (val = styles['margin']) { val = val.split(' '); styles['margin-top'] = val[0] || ''; styles['margin-right'] = val[1] || val[0] || ''; styles['margin-bottom'] = val[2] || val[0] || ''; styles['margin-left'] = val[3] || val[0] || ''; } if (val = styles['margin-top']) setVal('topmargin', val.replace(/px/, '')); if (val = styles['margin-right']) setVal('rightmargin', val.replace(/px/, '')); if (val = styles['margin-bottom']) setVal('bottommargin', val.replace(/px/, '')); if (val = styles['margin-left']) setVal('leftmargin', val.replace(/px/, '')); updateColor('bgcolor_pick', 'bgcolor'); updateColor('textcolor_pick', 'textcolor'); }, changedStyleProp : function() { var val, dom = tinyMCEPopup.editor.dom, styles = dom.parseStyle(getVal('style')); styles['font-face'] = getVal('fontface'); styles['font-size'] = getVal('fontsize'); styles['color'] = getVal('textcolor'); styles['background-color'] = getVal('bgcolor'); if (val = getVal('bgimage')) styles['background-image'] = "url('" + val + "')"; else styles['background-image'] = ''; delete styles['margin']; if (val = getVal('topmargin')) styles['margin-top'] = val + "px"; else styles['margin-top'] = ''; if (val = getVal('rightmargin')) styles['margin-right'] = val + "px"; else styles['margin-right'] = ''; if (val = getVal('bottommargin')) styles['margin-bottom'] = val + "px"; else styles['margin-bottom'] = ''; if (val = getVal('leftmargin')) styles['margin-left'] = val + "px"; else styles['margin-left'] = ''; // Serialize, parse and reserialize this will compress redundant styles setVal('style', dom.serializeStyle(dom.parseStyle(dom.serializeStyle(styles)))); this.changedStyle(); }, update : function() { var data = {}; tinymce.each(tinyMCEPopup.dom.select('select,input,textarea'), function(node) { data[node.id] = getVal(node.id); }); tinyMCEPopup.editor.plugins.fullpage._dataToHtml(data); tinyMCEPopup.close(); } }; function init() { var form = document.forms[0], i, item, list, editor = tinyMCEPopup.editor; // Setup doctype select box list = editor.getParam("fullpage_doctypes", defaultDocTypes).split(','); for (i = 0; i < list.length; i++) { item = list[i].split('='); if (item.length > 1) addSelectValue(form, 'doctype', item[0], item[1]); } // Setup fonts select box list = editor.getParam("fullpage_fonts", defaultFontNames).split(';'); for (i = 0; i < list.length; i++) { item = list[i].split('='); if (item.length > 1) addSelectValue(form, 'fontface', item[0], item[1]); } // Setup fontsize select box list = editor.getParam("fullpage_fontsizes", defaultFontSizes).split(','); for (i = 0; i < list.length; i++) addSelectValue(form, 'fontsize', list[i], list[i]); // Setup encodings select box list = editor.getParam("fullpage_encodings", defaultEncodings).split(','); for (i = 0; i < list.length; i++) { item = list[i].split('='); if (item.length > 1) addSelectValue(form, 'docencoding', item[0], item[1]); } // Setup color pickers document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor'); document.getElementById('link_color_pickcontainer').innerHTML = getColorPickerHTML('link_color_pick','link_color'); document.getElementById('visited_color_pickcontainer').innerHTML = getColorPickerHTML('visited_color_pick','visited_color'); document.getElementById('active_color_pickcontainer').innerHTML = getColorPickerHTML('active_color_pick','active_color'); document.getElementById('textcolor_pickcontainer').innerHTML = getColorPickerHTML('textcolor_pick','textcolor'); document.getElementById('stylesheet_browsercontainer').innerHTML = getBrowserHTML('stylesheetbrowser','stylesheet','file','fullpage'); document.getElementById('bgimage_pickcontainer').innerHTML = getBrowserHTML('bgimage_browser','bgimage','image','fullpage'); // Resize some elements if (isVisible('stylesheetbrowser')) document.getElementById('stylesheet').style.width = '220px'; if (isVisible('link_href_browser')) document.getElementById('element_link_href').style.width = '230px'; if (isVisible('bgimage_browser')) document.getElementById('bgimage').style.width = '210px'; // Update form tinymce.each(tinyMCEPopup.getWindowArg('data'), function(value, key) { setVal(key, value); }); FullPageDialog.changedStyle(); // Update colors updateColor('textcolor_pick', 'textcolor'); updateColor('bgcolor_pick', 'bgcolor'); updateColor('visited_color_pick', 'visited_color'); updateColor('active_color_pick', 'active_color'); updateColor('link_color_pick', 'link_color'); }; tinyMCEPopup.onInit.add(init); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.PageBreakPlugin', { init : function(ed, url) { var pb = '<img src="' + ed.theme.url + '/img/trans.gif" class="mcePageBreak mceItemNoResize" />', cls = 'mcePageBreak', sep = ed.getParam('pagebreak_separator', '<!-- pagebreak -->'), pbRE; pbRE = new RegExp(sep.replace(/[\?\.\*\[\]\(\)\{\}\+\^\$\:]/g, function(a) {return '\\' + a;}), 'g'); // Register commands ed.addCommand('mcePageBreak', function() { ed.execCommand('mceInsertContent', 0, pb); }); // Register buttons ed.addButton('pagebreak', {title : 'pagebreak.desc', cmd : cls}); ed.onInit.add(function() { if (ed.theme.onResolveName) { ed.theme.onResolveName.add(function(th, o) { if (o.node.nodeName == 'IMG' && ed.dom.hasClass(o.node, cls)) o.name = 'pagebreak'; }); } }); ed.onClick.add(function(ed, e) { e = e.target; if (e.nodeName === 'IMG' && ed.dom.hasClass(e, cls)) ed.selection.select(e); }); ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('pagebreak', n.nodeName === 'IMG' && ed.dom.hasClass(n, cls)); }); ed.onBeforeSetContent.add(function(ed, o) { o.content = o.content.replace(pbRE, pb); }); ed.onPostProcess.add(function(ed, o) { if (o.get) o.content = o.content.replace(/<img[^>]+>/g, function(im) { if (im.indexOf('class="mcePageBreak') !== -1) im = sep; return im; }); }); }, getInfo : function() { return { longname : 'PageBreak', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/pagebreak', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('pagebreak', tinymce.plugins.PageBreakPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function(tinymce) { tinymce.create('tinymce.plugins.EmotionsPlugin', { init : function(ed, url) { // Register commands ed.addCommand('mceEmotion', function() { ed.windowManager.open({ file : url + '/emotions.htm', width : 250 + parseInt(ed.getLang('emotions.delta_width', 0)), height : 160 + parseInt(ed.getLang('emotions.delta_height', 0)), inline : 1 }, { plugin_url : url }); }); // Register buttons ed.addButton('emotions', {title : 'emotions.emotions_desc', cmd : 'mceEmotion'}); }, getInfo : function() { return { longname : 'Emotions', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/emotions', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('emotions', tinymce.plugins.EmotionsPlugin); })(tinymce);
JavaScript
tinyMCEPopup.requireLangPack(); var EmotionsDialog = { addKeyboardNavigation: function(){ var tableElm, cells, settings; cells = tinyMCEPopup.dom.select("a.emoticon_link", "emoticon_table"); settings ={ root: "emoticon_table", items: cells }; cells[0].tabindex=0; tinyMCEPopup.dom.addClass(cells[0], "mceFocus"); if (tinymce.isGecko) { cells[0].focus(); } else { setTimeout(function(){ cells[0].focus(); }, 100); } tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', settings, tinyMCEPopup.dom); }, init : function(ed) { tinyMCEPopup.resizeToInnerSize(); this.addKeyboardNavigation(); }, insert : function(file, title) { var ed = tinyMCEPopup.editor, dom = ed.dom; tinyMCEPopup.execCommand('mceInsertContent', false, dom.createHTML('img', { src : tinyMCEPopup.getWindowArg('plugin_url') + '/img/' + file, alt : ed.getLang(title), title : ed.getLang(title), border : 0 })); tinyMCEPopup.close(); } }; tinyMCEPopup.onInit.add(EmotionsDialog.init, EmotionsDialog);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var each = tinymce.each; tinymce.create('tinymce.plugins.AdvListPlugin', { init : function(ed, url) { var t = this; t.editor = ed; function buildFormats(str) { var formats = []; each(str.split(/,/), function(type) { formats.push({ title : 'advlist.' + (type == 'default' ? 'def' : type.replace(/-/g, '_')), styles : { listStyleType : type == 'default' ? '' : type } }); }); return formats; }; // Setup number formats from config or default t.numlist = ed.getParam("advlist_number_styles") || buildFormats("default,lower-alpha,lower-greek,lower-roman,upper-alpha,upper-roman"); t.bullist = ed.getParam("advlist_bullet_styles") || buildFormats("default,circle,disc,square"); if (tinymce.isIE && /MSIE [2-7]/.test(navigator.userAgent)) t.isIE7 = true; }, createControl: function(name, cm) { var t = this, btn, format, editor = t.editor; if (name == 'numlist' || name == 'bullist') { // Default to first item if it's a default item if (t[name][0].title == 'advlist.def') format = t[name][0]; function hasFormat(node, format) { var state = true; each(format.styles, function(value, name) { // Format doesn't match if (editor.dom.getStyle(node, name) != value) { state = false; return false; } }); return state; }; function applyListFormat() { var list, dom = editor.dom, sel = editor.selection; // Check for existing list element list = dom.getParent(sel.getNode(), 'ol,ul'); // Switch/add list type if needed if (!list || list.nodeName == (name == 'bullist' ? 'OL' : 'UL') || hasFormat(list, format)) editor.execCommand(name == 'bullist' ? 'InsertUnorderedList' : 'InsertOrderedList'); // Append styles to new list element if (format) { list = dom.getParent(sel.getNode(), 'ol,ul'); if (list) { dom.setStyles(list, format.styles); list.removeAttribute('data-mce-style'); } } editor.focus(); }; btn = cm.createSplitButton(name, { title : 'advanced.' + name + '_desc', 'class' : 'mce_' + name, onclick : function() { applyListFormat(); } }); btn.onRenderMenu.add(function(btn, menu) { menu.onHideMenu.add(function() { if (t.bookmark) { editor.selection.moveToBookmark(t.bookmark); t.bookmark = 0; } }); menu.onShowMenu.add(function() { var dom = editor.dom, list = dom.getParent(editor.selection.getNode(), 'ol,ul'), fmtList; if (list || format) { fmtList = t[name]; // Unselect existing items each(menu.items, function(item) { var state = true; item.setSelected(0); if (list && !item.isDisabled()) { each(fmtList, function(fmt) { if (fmt.id == item.id) { if (!hasFormat(list, fmt)) { state = false; return false; } } }); if (state) item.setSelected(1); } }); // Select the current format if (!list) menu.items[format.id].setSelected(1); } editor.focus(); // IE looses it's selection so store it away and restore it later if (tinymce.isIE) { t.bookmark = editor.selection.getBookmark(1); } }); menu.add({id : editor.dom.uniqueId(), title : 'advlist.types', 'class' : 'mceMenuItemTitle', titleItem: true}).setDisabled(1); each(t[name], function(item) { // IE<8 doesn't support lower-greek, skip it if (t.isIE7 && item.styles.listStyleType == 'lower-greek') return; item.id = editor.dom.uniqueId(); menu.add({id : item.id, title : item.title, onclick : function() { format = item; applyListFormat(); }}); }); }); return btn; } }, getInfo : function() { return { longname : 'Advanced lists', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advlist', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('advlist', tinymce.plugins.AdvListPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.VisualChars', { init : function(ed, url) { var t = this; t.editor = ed; // Register commands ed.addCommand('mceVisualChars', t._toggleVisualChars, t); // Register buttons ed.addButton('visualchars', {title : 'visualchars.desc', cmd : 'mceVisualChars'}); ed.onBeforeGetContent.add(function(ed, o) { if (t.state && o.format != 'raw' && !o.draft) { t.state = true; t._toggleVisualChars(false); } }); }, getInfo : function() { return { longname : 'Visual characters', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/visualchars', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _toggleVisualChars : function(bookmark) { var t = this, ed = t.editor, nl, i, h, d = ed.getDoc(), b = ed.getBody(), nv, s = ed.selection, bo, div, bm; t.state = !t.state; ed.controlManager.setActive('visualchars', t.state); if (bookmark) bm = s.getBookmark(); if (t.state) { nl = []; tinymce.walk(b, function(n) { if (n.nodeType == 3 && n.nodeValue && n.nodeValue.indexOf('\u00a0') != -1) nl.push(n); }, 'childNodes'); for (i = 0; i < nl.length; i++) { nv = nl[i].nodeValue; nv = nv.replace(/(\u00a0)/g, '<span data-mce-bogus="1" class="mceItemHidden mceItemNbsp">$1</span>'); div = ed.dom.create('div', null, nv); while (node = div.lastChild) ed.dom.insertAfter(node, nl[i]); ed.dom.remove(nl[i]); } } else { nl = ed.dom.select('span.mceItemNbsp', b); for (i = nl.length - 1; i >= 0; i--) ed.dom.remove(nl[i], 1); } s.moveToBookmark(bm); } }); // Register plugin tinymce.PluginManager.add('visualchars', tinymce.plugins.VisualChars); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.XHTMLXtrasPlugin', { init : function(ed, url) { // Register commands ed.addCommand('mceCite', function() { ed.windowManager.open({ file : url + '/cite.htm', width : 350 + parseInt(ed.getLang('xhtmlxtras.cite_delta_width', 0)), height : 250 + parseInt(ed.getLang('xhtmlxtras.cite_delta_height', 0)), inline : 1 }, { plugin_url : url }); }); ed.addCommand('mceAcronym', function() { ed.windowManager.open({ file : url + '/acronym.htm', width : 350 + parseInt(ed.getLang('xhtmlxtras.acronym_delta_width', 0)), height : 250 + parseInt(ed.getLang('xhtmlxtras.acronym_delta_height', 0)), inline : 1 }, { plugin_url : url }); }); ed.addCommand('mceAbbr', function() { ed.windowManager.open({ file : url + '/abbr.htm', width : 350 + parseInt(ed.getLang('xhtmlxtras.abbr_delta_width', 0)), height : 250 + parseInt(ed.getLang('xhtmlxtras.abbr_delta_height', 0)), inline : 1 }, { plugin_url : url }); }); ed.addCommand('mceDel', function() { ed.windowManager.open({ file : url + '/del.htm', width : 340 + parseInt(ed.getLang('xhtmlxtras.del_delta_width', 0)), height : 310 + parseInt(ed.getLang('xhtmlxtras.del_delta_height', 0)), inline : 1 }, { plugin_url : url }); }); ed.addCommand('mceIns', function() { ed.windowManager.open({ file : url + '/ins.htm', width : 340 + parseInt(ed.getLang('xhtmlxtras.ins_delta_width', 0)), height : 310 + parseInt(ed.getLang('xhtmlxtras.ins_delta_height', 0)), inline : 1 }, { plugin_url : url }); }); ed.addCommand('mceAttributes', function() { ed.windowManager.open({ file : url + '/attributes.htm', width : 380 + parseInt(ed.getLang('xhtmlxtras.attr_delta_width', 0)), height : 370 + parseInt(ed.getLang('xhtmlxtras.attr_delta_height', 0)), inline : 1 }, { plugin_url : url }); }); // Register buttons ed.addButton('cite', {title : 'xhtmlxtras.cite_desc', cmd : 'mceCite'}); ed.addButton('acronym', {title : 'xhtmlxtras.acronym_desc', cmd : 'mceAcronym'}); ed.addButton('abbr', {title : 'xhtmlxtras.abbr_desc', cmd : 'mceAbbr'}); ed.addButton('del', {title : 'xhtmlxtras.del_desc', cmd : 'mceDel'}); ed.addButton('ins', {title : 'xhtmlxtras.ins_desc', cmd : 'mceIns'}); ed.addButton('attribs', {title : 'xhtmlxtras.attribs_desc', cmd : 'mceAttributes'}); ed.onNodeChange.add(function(ed, cm, n, co) { n = ed.dom.getParent(n, 'CITE,ACRONYM,ABBR,DEL,INS'); cm.setDisabled('cite', co); cm.setDisabled('acronym', co); cm.setDisabled('abbr', co); cm.setDisabled('del', co); cm.setDisabled('ins', co); cm.setDisabled('attribs', n && n.nodeName == 'BODY'); cm.setActive('cite', 0); cm.setActive('acronym', 0); cm.setActive('abbr', 0); cm.setActive('del', 0); cm.setActive('ins', 0); // Activate all if (n) { do { cm.setDisabled(n.nodeName.toLowerCase(), 0); cm.setActive(n.nodeName.toLowerCase(), 1); } while (n = n.parentNode); } }); ed.onPreInit.add(function() { // Fixed IE issue where it can't handle these elements correctly ed.dom.create('abbr'); }); }, getInfo : function() { return { longname : 'XHTML Xtras Plugin', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/xhtmlxtras', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('xhtmlxtras', tinymce.plugins.XHTMLXtrasPlugin); })();
JavaScript
/** * ins.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ function init() { SXE.initElementDialog('ins'); if (SXE.currentAction == "update") { setFormValue('datetime', tinyMCEPopup.editor.dom.getAttrib(SXE.updateElement, 'datetime')); setFormValue('cite', tinyMCEPopup.editor.dom.getAttrib(SXE.updateElement, 'cite')); SXE.showRemoveButton(); } } function setElementAttribs(elm) { setAllCommonAttribs(elm); setAttrib(elm, 'datetime'); setAttrib(elm, 'cite'); elm.removeAttribute('data-mce-new'); } function insertIns() { var elm = tinyMCEPopup.editor.dom.getParent(SXE.focusElement, 'INS'); if (elm == null) { var s = SXE.inst.selection.getContent(); if(s.length > 0) { insertInlineElement('ins'); var elementArray = SXE.inst.dom.select('ins[data-mce-new]'); for (var i=0; i<elementArray.length; i++) { var elm = elementArray[i]; setElementAttribs(elm); } } } else { setElementAttribs(elm); } tinyMCEPopup.editor.nodeChanged(); tinyMCEPopup.execCommand('mceEndUndoLevel'); tinyMCEPopup.close(); } function removeIns() { SXE.removeElement('ins'); tinyMCEPopup.close(); } tinyMCEPopup.onInit.add(init);
JavaScript
/** * del.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ function init() { SXE.initElementDialog('del'); if (SXE.currentAction == "update") { setFormValue('datetime', tinyMCEPopup.editor.dom.getAttrib(SXE.updateElement, 'datetime')); setFormValue('cite', tinyMCEPopup.editor.dom.getAttrib(SXE.updateElement, 'cite')); SXE.showRemoveButton(); } } function setElementAttribs(elm) { setAllCommonAttribs(elm); setAttrib(elm, 'datetime'); setAttrib(elm, 'cite'); elm.removeAttribute('data-mce-new'); } function insertDel() { var elm = tinyMCEPopup.editor.dom.getParent(SXE.focusElement, 'DEL'); if (elm == null) { var s = SXE.inst.selection.getContent(); if(s.length > 0) { insertInlineElement('del'); var elementArray = SXE.inst.dom.select('del[data-mce-new]'); for (var i=0; i<elementArray.length; i++) { var elm = elementArray[i]; setElementAttribs(elm); } } } else { setElementAttribs(elm); } tinyMCEPopup.editor.nodeChanged(); tinyMCEPopup.execCommand('mceEndUndoLevel'); tinyMCEPopup.close(); } function removeDel() { SXE.removeElement('del'); tinyMCEPopup.close(); } tinyMCEPopup.onInit.add(init);
JavaScript
/** * element_common.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ tinyMCEPopup.requireLangPack(); function initCommonAttributes(elm) { var formObj = document.forms[0], dom = tinyMCEPopup.editor.dom; // Setup form data for common element attributes setFormValue('title', dom.getAttrib(elm, 'title')); setFormValue('id', dom.getAttrib(elm, 'id')); selectByValue(formObj, 'class', dom.getAttrib(elm, 'class'), true); setFormValue('style', dom.getAttrib(elm, 'style')); selectByValue(formObj, 'dir', dom.getAttrib(elm, 'dir')); setFormValue('lang', dom.getAttrib(elm, 'lang')); setFormValue('onfocus', dom.getAttrib(elm, 'onfocus')); setFormValue('onblur', dom.getAttrib(elm, 'onblur')); setFormValue('onclick', dom.getAttrib(elm, 'onclick')); setFormValue('ondblclick', dom.getAttrib(elm, 'ondblclick')); setFormValue('onmousedown', dom.getAttrib(elm, 'onmousedown')); setFormValue('onmouseup', dom.getAttrib(elm, 'onmouseup')); setFormValue('onmouseover', dom.getAttrib(elm, 'onmouseover')); setFormValue('onmousemove', dom.getAttrib(elm, 'onmousemove')); setFormValue('onmouseout', dom.getAttrib(elm, 'onmouseout')); setFormValue('onkeypress', dom.getAttrib(elm, 'onkeypress')); setFormValue('onkeydown', dom.getAttrib(elm, 'onkeydown')); setFormValue('onkeyup', dom.getAttrib(elm, 'onkeyup')); } function setFormValue(name, value) { if(document.forms[0].elements[name]) document.forms[0].elements[name].value = value; } function insertDateTime(id) { document.getElementById(id).value = getDateTime(new Date(), "%Y-%m-%dT%H:%M:%S"); } function getDateTime(d, fmt) { fmt = fmt.replace("%D", "%m/%d/%y"); fmt = fmt.replace("%r", "%I:%M:%S %p"); fmt = fmt.replace("%Y", "" + d.getFullYear()); fmt = fmt.replace("%y", "" + d.getYear()); fmt = fmt.replace("%m", addZeros(d.getMonth()+1, 2)); fmt = fmt.replace("%d", addZeros(d.getDate(), 2)); fmt = fmt.replace("%H", "" + addZeros(d.getHours(), 2)); fmt = fmt.replace("%M", "" + addZeros(d.getMinutes(), 2)); fmt = fmt.replace("%S", "" + addZeros(d.getSeconds(), 2)); fmt = fmt.replace("%I", "" + ((d.getHours() + 11) % 12 + 1)); fmt = fmt.replace("%p", "" + (d.getHours() < 12 ? "AM" : "PM")); fmt = fmt.replace("%%", "%"); return fmt; } function addZeros(value, len) { var i; value = "" + value; if (value.length < len) { for (i=0; i<(len-value.length); i++) value = "0" + value; } return value; } function selectByValue(form_obj, field_name, value, add_custom, ignore_case) { if (!form_obj || !form_obj.elements[field_name]) return; var sel = form_obj.elements[field_name]; var found = false; for (var i=0; i<sel.options.length; i++) { var option = sel.options[i]; if (option.value == value || (ignore_case && option.value.toLowerCase() == value.toLowerCase())) { option.selected = true; found = true; } else option.selected = false; } if (!found && add_custom && value != '') { var option = new Option('Value: ' + value, value); option.selected = true; sel.options[sel.options.length] = option; } return found; } function setAttrib(elm, attrib, value) { var formObj = document.forms[0]; var valueElm = formObj.elements[attrib.toLowerCase()]; tinyMCEPopup.editor.dom.setAttrib(elm, attrib, value || valueElm.value); } function setAllCommonAttribs(elm) { setAttrib(elm, 'title'); setAttrib(elm, 'id'); setAttrib(elm, 'class'); setAttrib(elm, 'style'); setAttrib(elm, 'dir'); setAttrib(elm, 'lang'); /*setAttrib(elm, 'onfocus'); setAttrib(elm, 'onblur'); setAttrib(elm, 'onclick'); setAttrib(elm, 'ondblclick'); setAttrib(elm, 'onmousedown'); setAttrib(elm, 'onmouseup'); setAttrib(elm, 'onmouseover'); setAttrib(elm, 'onmousemove'); setAttrib(elm, 'onmouseout'); setAttrib(elm, 'onkeypress'); setAttrib(elm, 'onkeydown'); setAttrib(elm, 'onkeyup');*/ } SXE = { currentAction : "insert", inst : tinyMCEPopup.editor, updateElement : null } SXE.focusElement = SXE.inst.selection.getNode(); SXE.initElementDialog = function(element_name) { addClassesToList('class', 'xhtmlxtras_styles'); TinyMCE_EditableSelects.init(); element_name = element_name.toLowerCase(); var elm = SXE.inst.dom.getParent(SXE.focusElement, element_name.toUpperCase()); if (elm != null && elm.nodeName.toUpperCase() == element_name.toUpperCase()) { SXE.currentAction = "update"; } if (SXE.currentAction == "update") { initCommonAttributes(elm); SXE.updateElement = elm; } document.forms[0].insert.value = tinyMCEPopup.getLang(SXE.currentAction, 'Insert', true); } SXE.insertElement = function(element_name) { var elm = SXE.inst.dom.getParent(SXE.focusElement, element_name.toUpperCase()), h, tagName; if (elm == null) { var s = SXE.inst.selection.getContent(); if(s.length > 0) { tagName = element_name; insertInlineElement(element_name); var elementArray = tinymce.grep(SXE.inst.dom.select(element_name)); for (var i=0; i<elementArray.length; i++) { var elm = elementArray[i]; if (SXE.inst.dom.getAttrib(elm, 'data-mce-new')) { elm.id = ''; elm.setAttribute('id', ''); elm.removeAttribute('id'); elm.removeAttribute('data-mce-new'); setAllCommonAttribs(elm); } } } } else { setAllCommonAttribs(elm); } SXE.inst.nodeChanged(); tinyMCEPopup.execCommand('mceEndUndoLevel'); } SXE.removeElement = function(element_name){ element_name = element_name.toLowerCase(); elm = SXE.inst.dom.getParent(SXE.focusElement, element_name.toUpperCase()); if(elm && elm.nodeName.toUpperCase() == element_name.toUpperCase()){ tinyMCE.execCommand('mceRemoveNode', false, elm); SXE.inst.nodeChanged(); tinyMCEPopup.execCommand('mceEndUndoLevel'); } } SXE.showRemoveButton = function() { document.getElementById("remove").style.display = ''; } SXE.containsClass = function(elm,cl) { return (elm.className.indexOf(cl) > -1) ? true : false; } SXE.removeClass = function(elm,cl) { if(elm.className == null || elm.className == "" || !SXE.containsClass(elm,cl)) { return true; } var classNames = elm.className.split(" "); var newClassNames = ""; for (var x = 0, cnl = classNames.length; x < cnl; x++) { if (classNames[x] != cl) { newClassNames += (classNames[x] + " "); } } elm.className = newClassNames.substring(0,newClassNames.length-1); //removes extra space at the end } SXE.addClass = function(elm,cl) { if(!SXE.containsClass(elm,cl)) elm.className ? elm.className += " " + cl : elm.className = cl; return true; } function insertInlineElement(en) { var ed = tinyMCEPopup.editor, dom = ed.dom; ed.getDoc().execCommand('FontName', false, 'mceinline'); tinymce.each(dom.select('span,font'), function(n) { if (n.style.fontFamily == 'mceinline' || n.face == 'mceinline') dom.replace(dom.create(en, {'data-mce-new' : 1}), n, 1); }); }
JavaScript
/** * cite.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ function init() { SXE.initElementDialog('cite'); if (SXE.currentAction == "update") { SXE.showRemoveButton(); } } function insertCite() { SXE.insertElement('cite'); tinyMCEPopup.close(); } function removeCite() { SXE.removeElement('cite'); tinyMCEPopup.close(); } tinyMCEPopup.onInit.add(init);
JavaScript
/** * attributes.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ function init() { tinyMCEPopup.resizeToInnerSize(); var inst = tinyMCEPopup.editor; var dom = inst.dom; var elm = inst.selection.getNode(); var f = document.forms[0]; var onclick = dom.getAttrib(elm, 'onclick'); setFormValue('title', dom.getAttrib(elm, 'title')); setFormValue('id', dom.getAttrib(elm, 'id')); setFormValue('style', dom.getAttrib(elm, "style")); setFormValue('dir', dom.getAttrib(elm, 'dir')); setFormValue('lang', dom.getAttrib(elm, 'lang')); setFormValue('tabindex', dom.getAttrib(elm, 'tabindex', typeof(elm.tabindex) != "undefined" ? elm.tabindex : "")); setFormValue('accesskey', dom.getAttrib(elm, 'accesskey', typeof(elm.accesskey) != "undefined" ? elm.accesskey : "")); setFormValue('onfocus', dom.getAttrib(elm, 'onfocus')); setFormValue('onblur', dom.getAttrib(elm, 'onblur')); setFormValue('onclick', onclick); setFormValue('ondblclick', dom.getAttrib(elm, 'ondblclick')); setFormValue('onmousedown', dom.getAttrib(elm, 'onmousedown')); setFormValue('onmouseup', dom.getAttrib(elm, 'onmouseup')); setFormValue('onmouseover', dom.getAttrib(elm, 'onmouseover')); setFormValue('onmousemove', dom.getAttrib(elm, 'onmousemove')); setFormValue('onmouseout', dom.getAttrib(elm, 'onmouseout')); setFormValue('onkeypress', dom.getAttrib(elm, 'onkeypress')); setFormValue('onkeydown', dom.getAttrib(elm, 'onkeydown')); setFormValue('onkeyup', dom.getAttrib(elm, 'onkeyup')); className = dom.getAttrib(elm, 'class'); addClassesToList('classlist', 'advlink_styles'); selectByValue(f, 'classlist', className, true); TinyMCE_EditableSelects.init(); } function setFormValue(name, value) { if(value && document.forms[0].elements[name]){ document.forms[0].elements[name].value = value; } } function insertAction() { var inst = tinyMCEPopup.editor; var elm = inst.selection.getNode(); setAllAttribs(elm); tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); } function setAttrib(elm, attrib, value) { var formObj = document.forms[0]; var valueElm = formObj.elements[attrib.toLowerCase()]; var inst = tinyMCEPopup.editor; var dom = inst.dom; if (typeof(value) == "undefined" || value == null) { value = ""; if (valueElm) value = valueElm.value; } dom.setAttrib(elm, attrib.toLowerCase(), value); } function setAllAttribs(elm) { var f = document.forms[0]; setAttrib(elm, 'title'); setAttrib(elm, 'id'); setAttrib(elm, 'style'); setAttrib(elm, 'class', getSelectValue(f, 'classlist')); setAttrib(elm, 'dir'); setAttrib(elm, 'lang'); setAttrib(elm, 'tabindex'); setAttrib(elm, 'accesskey'); setAttrib(elm, 'onfocus'); setAttrib(elm, 'onblur'); setAttrib(elm, 'onclick'); setAttrib(elm, 'ondblclick'); setAttrib(elm, 'onmousedown'); setAttrib(elm, 'onmouseup'); setAttrib(elm, 'onmouseover'); setAttrib(elm, 'onmousemove'); setAttrib(elm, 'onmouseout'); setAttrib(elm, 'onkeypress'); setAttrib(elm, 'onkeydown'); setAttrib(elm, 'onkeyup'); // Refresh in old MSIE // if (tinyMCE.isMSIE5) // elm.outerHTML = elm.outerHTML; } function insertAttribute() { tinyMCEPopup.close(); } tinyMCEPopup.onInit.add(init); tinyMCEPopup.requireLangPack();
JavaScript
/** * acronym.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ function init() { SXE.initElementDialog('acronym'); if (SXE.currentAction == "update") { SXE.showRemoveButton(); } } function insertAcronym() { SXE.insertElement('acronym'); tinyMCEPopup.close(); } function removeAcronym() { SXE.removeElement('acronym'); tinyMCEPopup.close(); } tinyMCEPopup.onInit.add(init);
JavaScript
/** * abbr.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ function init() { SXE.initElementDialog('abbr'); if (SXE.currentAction == "update") { SXE.showRemoveButton(); } } function insertAbbr() { SXE.insertElement('abbr'); tinyMCEPopup.close(); } function removeAbbr() { SXE.removeElement('abbr'); tinyMCEPopup.close(); } tinyMCEPopup.onInit.add(init);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var each = tinymce.each, defs = { paste_auto_cleanup_on_paste : true, paste_enable_default_filters : true, paste_block_drop : false, paste_retain_style_properties : "none", paste_strip_class_attributes : "mso", paste_remove_spans : false, paste_remove_styles : false, paste_remove_styles_if_webkit : true, paste_convert_middot_lists : true, paste_convert_headers_to_strong : false, paste_dialog_width : "450", paste_dialog_height : "400", paste_max_consecutive_linebreaks: 2, paste_text_use_dialog : false, paste_text_sticky : false, paste_text_sticky_default : false, paste_text_notifyalways : false, paste_text_linebreaktype : "combined", paste_text_replacements : [ [/\u2026/g, "..."], [/[\x93\x94\u201c\u201d]/g, '"'], [/[\x60\x91\x92\u2018\u2019]/g, "'"] ] }; function getParam(ed, name) { return ed.getParam(name, defs[name]); } tinymce.create('tinymce.plugins.PastePlugin', { init : function(ed, url) { var t = this; t.editor = ed; t.url = url; // Setup plugin events t.onPreProcess = new tinymce.util.Dispatcher(t); t.onPostProcess = new tinymce.util.Dispatcher(t); // Register default handlers t.onPreProcess.add(t._preProcess); t.onPostProcess.add(t._postProcess); // Register optional preprocess handler t.onPreProcess.add(function(pl, o) { ed.execCallback('paste_preprocess', pl, o); }); // Register optional postprocess t.onPostProcess.add(function(pl, o) { ed.execCallback('paste_postprocess', pl, o); }); ed.onKeyDown.addToTop(function(ed, e) { // Block ctrl+v from adding an undo level since the default logic in tinymce.Editor will add that if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45)) return false; // Stop other listeners }); // Initialize plain text flag ed.pasteAsPlainText = getParam(ed, 'paste_text_sticky_default'); // This function executes the process handlers and inserts the contents // force_rich overrides plain text mode set by user, important for pasting with execCommand function process(o, force_rich) { var dom = ed.dom, rng; // Execute pre process handlers t.onPreProcess.dispatch(t, o); // Create DOM structure o.node = dom.create('div', 0, o.content); // If pasting inside the same element and the contents is only one block // remove the block and keep the text since Firefox will copy parts of pre and h1-h6 as a pre element if (tinymce.isGecko) { rng = ed.selection.getRng(true); if (rng.startContainer == rng.endContainer && rng.startContainer.nodeType == 3) { // Is only one block node and it doesn't contain word stuff if (o.node.childNodes.length === 1 && /^(p|h[1-6]|pre)$/i.test(o.node.firstChild.nodeName) && o.content.indexOf('__MCE_ITEM__') === -1) dom.remove(o.node.firstChild, true); } } // Execute post process handlers t.onPostProcess.dispatch(t, o); // Serialize content o.content = ed.serializer.serialize(o.node, {getInner : 1, forced_root_block : ''}); // Plain text option active? if ((!force_rich) && (ed.pasteAsPlainText)) { t._insertPlainText(o.content); if (!getParam(ed, "paste_text_sticky")) { ed.pasteAsPlainText = false; ed.controlManager.setActive("pastetext", false); } } else { t._insert(o.content); } } // Add command for external usage ed.addCommand('mceInsertClipboardContent', function(u, o) { process(o, true); }); if (!getParam(ed, "paste_text_use_dialog")) { ed.addCommand('mcePasteText', function(u, v) { var cookie = tinymce.util.Cookie; ed.pasteAsPlainText = !ed.pasteAsPlainText; ed.controlManager.setActive('pastetext', ed.pasteAsPlainText); if ((ed.pasteAsPlainText) && (!cookie.get("tinymcePasteText"))) { if (getParam(ed, "paste_text_sticky")) { ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky')); } else { ed.windowManager.alert(ed.translate('paste.plaintext_mode')); } if (!getParam(ed, "paste_text_notifyalways")) { cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31)) } } }); } ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'}); ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'}); // This function grabs the contents from the clipboard by adding a // hidden div and placing the caret inside it and after the browser paste // is done it grabs that contents and processes that function grabContent(e) { var n, or, rng, oldRng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY, textContent; // Check if browser supports direct plaintext access if (e.clipboardData || dom.doc.dataTransfer) { textContent = (e.clipboardData || dom.doc.dataTransfer).getData('Text'); if (ed.pasteAsPlainText) { e.preventDefault(); process({content : dom.encode(textContent).replace(/\r?\n/g, '<br />')}); return; } } if (dom.get('_mcePaste')) return; // Create container to paste into n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste', 'data-mce-bogus' : '1'}, '\uFEFF\uFEFF'); // If contentEditable mode we need to find out the position of the closest element if (body != ed.getDoc().body) posY = dom.getPos(ed.selection.getStart(), body).y; else posY = body.scrollTop + dom.getViewPort(ed.getWin()).y; // Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles // If also needs to be in view on IE or the paste would fail dom.setStyles(n, { position : 'absolute', left : tinymce.isGecko ? -40 : 0, // Need to move it out of site on Gecko since it will othewise display a ghost resize rect for the div top : posY - 25, width : 1, height : 1, overflow : 'hidden' }); if (tinymce.isIE) { // Store away the old range oldRng = sel.getRng(); // Select the container rng = dom.doc.body.createTextRange(); rng.moveToElementText(n); rng.execCommand('Paste'); // Remove container dom.remove(n); // Check if the contents was changed, if it wasn't then clipboard extraction failed probably due // to IE security settings so we pass the junk though better than nothing right if (n.innerHTML === '\uFEFF\uFEFF') { ed.execCommand('mcePasteWord'); e.preventDefault(); return; } // Restore the old range and clear the contents before pasting sel.setRng(oldRng); sel.setContent(''); // For some odd reason we need to detach the the mceInsertContent call from the paste event // It's like IE has a reference to the parent element that you paste in and the selection gets messed up // when it tries to restore the selection setTimeout(function() { // Process contents process({content : n.innerHTML}); }, 0); // Block the real paste event return tinymce.dom.Event.cancel(e); } else { function block(e) { e.preventDefault(); }; // Block mousedown and click to prevent selection change dom.bind(ed.getDoc(), 'mousedown', block); dom.bind(ed.getDoc(), 'keydown', block); or = ed.selection.getRng(); // Move select contents inside DIV n = n.firstChild; rng = ed.getDoc().createRange(); rng.setStart(n, 0); rng.setEnd(n, 2); sel.setRng(rng); // Wait a while and grab the pasted contents window.setTimeout(function() { var h = '', nl; // Paste divs duplicated in paste divs seems to happen when you paste plain text so lets first look for that broken behavior in WebKit if (!dom.select('div.mcePaste > div.mcePaste').length) { nl = dom.select('div.mcePaste'); // WebKit will split the div into multiple ones so this will loop through then all and join them to get the whole HTML string each(nl, function(n) { var child = n.firstChild; // WebKit inserts a DIV container with lots of odd styles if (child && child.nodeName == 'DIV' && child.style.marginTop && child.style.backgroundColor) { dom.remove(child, 1); } // Remove apply style spans each(dom.select('span.Apple-style-span', n), function(n) { dom.remove(n, 1); }); // Remove bogus br elements each(dom.select('br[data-mce-bogus]', n), function(n) { dom.remove(n); }); // WebKit will make a copy of the DIV for each line of plain text pasted and insert them into the DIV if (n.parentNode.className != 'mcePaste') h += n.innerHTML; }); } else { // Found WebKit weirdness so force the content into paragraphs this seems to happen when you paste plain text from Nodepad etc // So this logic will replace double enter with paragraphs and single enter with br so it kind of looks the same h = '<p>' + dom.encode(textContent).replace(/\r?\n\r?\n/g, '</p><p>').replace(/\r?\n/g, '<br />') + '</p>'; } // Remove the nodes each(dom.select('div.mcePaste'), function(n) { dom.remove(n); }); // Restore the old selection if (or) sel.setRng(or); process({content : h}); // Unblock events ones we got the contents dom.unbind(ed.getDoc(), 'mousedown', block); dom.unbind(ed.getDoc(), 'keydown', block); }, 0); } } // Check if we should use the new auto process method if (getParam(ed, "paste_auto_cleanup_on_paste")) { // Is it's Opera or older FF use key handler if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) { ed.onKeyDown.addToTop(function(ed, e) { if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45)) grabContent(e); }); } else { // Grab contents on paste event on Gecko and WebKit ed.onPaste.addToTop(function(ed, e) { return grabContent(e); }); } } ed.onInit.add(function() { ed.controlManager.setActive("pastetext", ed.pasteAsPlainText); // Block all drag/drop events if (getParam(ed, "paste_block_drop")) { ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) { e.preventDefault(); e.stopPropagation(); return false; }); } }); // Add legacy support t._legacySupport(); }, getInfo : function() { return { longname : 'Paste text/word', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, _preProcess : function(pl, o) { var ed = this.editor, h = o.content, grep = tinymce.grep, explode = tinymce.explode, trim = tinymce.trim, len, stripClass; //console.log('Before preprocess:' + o.content); function process(items) { each(items, function(v) { // Remove or replace if (v.constructor == RegExp) h = h.replace(v, ''); else h = h.replace(v[0], v[1]); }); } if (ed.settings.paste_enable_default_filters == false) { return; } // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser if (tinymce.isIE && document.documentMode >= 9 && /<(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)/.test(o.content)) { // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser process([[/(?:<br>&nbsp;[\s\r\n]+|<br>)*(<\/?(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)[^>]*>)(?:<br>&nbsp;[\s\r\n]+|<br>)*/g, '$1']]); // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break process([ [/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact [/<br>/g, ' '], // Replace single br elements with space since they are word wrap BR:s [/<BR><BR>/g, '<br>'] // Replace back the double brs but into a single BR ]); } // Detect Word content and process it more aggressive if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) { o.wordContent = true; // Mark the pasted contents as word specific content //console.log('Word contents detected.'); // Process away some basic content process([ /^\s*(&nbsp;)+/gi, // &nbsp; entities at the start of contents /(&nbsp;|<br[^>]*>)+\s*$/gi // &nbsp; entities at the end of contents ]); if (getParam(ed, "paste_convert_headers_to_strong")) { h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>"); } if (getParam(ed, "paste_convert_middot_lists")) { process([ [/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'], // Convert supportLists to a list item marker [/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'], // Convert mso-list and symbol spans to item markers [/(<p[^>]+(?:MsoListParagraph)[^>]+>)/gi, '$1__MCE_ITEM__'] // Convert mso-list and symbol paragraphs to item markers (FF) ]); } process([ // Word comments like conditional comments etc /<!--[\s\S]+?-->/gi, // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, // Convert <s> into <strike> for line-though [/<(\/?)s>/gi, "<$1strike>"], // Replace nsbp entites to char since it's easier to handle [/&nbsp;/gi, "\u00a0"] ]); // Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag. // If JavaScript had a RegExp look-behind, we could have integrated this with the last process() array and got rid of the loop. But alas, it does not, so we cannot. do { len = h.length; h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1"); } while (len != h.length); // Remove all spans if no styles is to be retained if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) { h = h.replace(/<\/?span[^>]*>/gi, ""); } else { // We're keeping styles, so at least clean them up. // CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx process([ // Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi, function(str, spaces) { return (spaces.length > 0)? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : ""; } ], // Examine all styles: delete junk, transform some, and keep the rest [/(<[a-z][^>]*)\sstyle="([^"]*)"/gi, function(str, tag, style) { var n = [], i = 0, s = explode(trim(style).replace(/&quot;/gi, "'"), ";"); // Examine each style definition within the tag's style attribute each(s, function(v) { var name, value, parts = explode(v, ":"); function ensureUnits(v) { return v + ((v !== "0") && (/\d$/.test(v)))? "px" : ""; } if (parts.length == 2) { name = parts[0].toLowerCase(); value = parts[1].toLowerCase(); // Translate certain MS Office styles into their CSS equivalents switch (name) { case "mso-padding-alt": case "mso-padding-top-alt": case "mso-padding-right-alt": case "mso-padding-bottom-alt": case "mso-padding-left-alt": case "mso-margin-alt": case "mso-margin-top-alt": case "mso-margin-right-alt": case "mso-margin-bottom-alt": case "mso-margin-left-alt": case "mso-table-layout-alt": case "mso-height": case "mso-width": case "mso-vertical-align-alt": n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value); return; case "horiz-align": n[i++] = "text-align:" + value; return; case "vert-align": n[i++] = "vertical-align:" + value; return; case "font-color": case "mso-foreground": n[i++] = "color:" + value; return; case "mso-background": case "mso-highlight": n[i++] = "background:" + value; return; case "mso-default-height": n[i++] = "min-height:" + ensureUnits(value); return; case "mso-default-width": n[i++] = "min-width:" + ensureUnits(value); return; case "mso-padding-between-alt": n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value); return; case "text-line-through": if ((value == "single") || (value == "double")) { n[i++] = "text-decoration:line-through"; } return; case "mso-zero-height": if (value == "yes") { n[i++] = "display:none"; } return; } // Eliminate all MS Office style definitions that have no CSS equivalent by examining the first characters in the name if (/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?!align|decor|indent|trans)|top-bar|version|vnd|word-break)/.test(name)) { return; } // If it reached this point, it must be a valid CSS style n[i++] = name + ":" + parts[1]; // Lower-case name, but keep value case } }); // If style attribute contained any valid styles the re-write it; otherwise delete style attribute. if (i > 0) { return tag + ' style="' + n.join(';') + '"'; } else { return tag; } } ] ]); } } // Replace headers with <strong> if (getParam(ed, "paste_convert_headers_to_strong")) { process([ [/<h[1-6][^>]*>/gi, "<p><strong>"], [/<\/h[1-6][^>]*>/gi, "</strong></p>"] ]); } process([ // Copy paste from Java like Open Office will produce this junk on FF [/Version:[\d.]+\nStartHTML:\d+\nEndHTML:\d+\nStartFragment:\d+\nEndFragment:\d+/gi, ''] ]); // Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso"). // Note:- paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation. stripClass = getParam(ed, "paste_strip_class_attributes"); if (stripClass !== "none") { function removeClasses(match, g1) { if (stripClass === "all") return ''; var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "), function(v) { return (/^(?!mso)/i.test(v)); } ); return cls.length ? ' class="' + cls.join(" ") + '"' : ''; }; h = h.replace(/ class="([^"]+)"/gi, removeClasses); h = h.replace(/ class=([\-\w]+)/gi, removeClasses); } // Remove spans option if (getParam(ed, "paste_remove_spans")) { h = h.replace(/<\/?span[^>]*>/gi, ""); } //console.log('After preprocess:' + h); o.content = h; }, /** * Various post process items. */ _postProcess : function(pl, o) { var t = this, ed = t.editor, dom = ed.dom, styleProps; if (ed.settings.paste_enable_default_filters == false) { return; } if (o.wordContent) { // Remove named anchors or TOC links each(dom.select('a', o.node), function(a) { if (!a.href || a.href.indexOf('#_Toc') != -1) dom.remove(a, 1); }); if (getParam(ed, "paste_convert_middot_lists")) { t._convertLists(pl, o); } // Process styles styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties // Process only if a string was specified and not equal to "all" or "*" if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) { styleProps = tinymce.explode(styleProps.replace(/^none$/i, "")); // Retains some style properties each(dom.select('*', o.node), function(el) { var newStyle = {}, npc = 0, i, sp, sv; // Store a subset of the existing styles if (styleProps) { for (i = 0; i < styleProps.length; i++) { sp = styleProps[i]; sv = dom.getStyle(el, sp); if (sv) { newStyle[sp] = sv; npc++; } } } // Remove all of the existing styles dom.setAttrib(el, 'style', ''); if (styleProps && npc > 0) dom.setStyles(el, newStyle); // Add back the stored subset of styles else // Remove empty span tags that do not have class attributes if (el.nodeName == 'SPAN' && !el.className) dom.remove(el, true); }); } } // Remove all style information or only specifically on WebKit to avoid the style bug on that browser if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) { each(dom.select('*[style]', o.node), function(el) { el.removeAttribute('style'); el.removeAttribute('data-mce-style'); }); } else { if (tinymce.isWebKit) { // We need to compress the styles on WebKit since if you paste <img border="0" /> it will become <img border="0" style="... lots of junk ..." /> // Removing the mce_style that contains the real value will force the Serializer engine to compress the styles each(dom.select('*', o.node), function(el) { el.removeAttribute('data-mce-style'); }); } } }, /** * Converts the most common bullet and number formats in Office into a real semantic UL/LI list. */ _convertLists : function(pl, o) { var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html; // Convert middot lists into real semantic lists each(dom.select('p', o.node), function(p) { var sib, val = '', type, html, idx, parents; // Get text node value at beginning of paragraph for (sib = p.firstChild; sib && sib.nodeType == 3; sib = sib.nextSibling) val += sib.nodeValue; val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/&nbsp;/g, '\u00a0'); // Detect unordered lists look for bullets if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*\u00a0*/.test(val)) type = 'ul'; // Detect ordered lists 1., a. or ixv. if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0+/.test(val)) type = 'ol'; // Check if node value matches the list pattern: o&nbsp;&nbsp; if (type) { margin = parseFloat(p.style.marginLeft || 0); if (margin > lastMargin) levels.push(margin); if (!listElm || type != lastType) { listElm = dom.create(type); dom.insertAfter(listElm, p); } else { // Nested list element if (margin > lastMargin) { listElm = li.appendChild(dom.create(type)); } else if (margin < lastMargin) { // Find parent level based on margin value idx = tinymce.inArray(levels, margin); parents = dom.getParents(listElm.parentNode, type); listElm = parents[parents.length - 1 - idx] || listElm; } } // Remove middot or number spans if they exists each(dom.select('span', p), function(span) { var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, ''); // Remove span with the middot or the number if (type == 'ul' && /^__MCE_ITEM__[\u2022\u00b7\u00a7\u00d8o\u25CF]/.test(html)) dom.remove(span); else if (/^__MCE_ITEM__[\s\S]*\w+\.(&nbsp;|\u00a0)*\s*/.test(html)) dom.remove(span); }); html = p.innerHTML; // Remove middot/list items if (type == 'ul') html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*(&nbsp;|\u00a0)+\s*/, ''); else html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.(&nbsp;|\u00a0)+\s*/, ''); // Create li and add paragraph data into the new li li = listElm.appendChild(dom.create('li', 0, html)); dom.remove(p); lastMargin = margin; lastType = type; } else listElm = lastMargin = 0; // End list element }); // Remove any left over makers html = o.node.innerHTML; if (html.indexOf('__MCE_ITEM__') != -1) o.node.innerHTML = html.replace(/__MCE_ITEM__/g, ''); }, /** * Inserts the specified contents at the caret position. */ _insert : function(h, skip_undo) { var ed = this.editor, r = ed.selection.getRng(); // First delete the contents seems to work better on WebKit when the selection spans multiple list items or multiple table cells. if (!ed.selection.isCollapsed() && r.startContainer != r.endContainer) ed.getDoc().execCommand('Delete', false, null); ed.execCommand('mceInsertContent', false, h, {skip_undo : skip_undo}); }, /** * Instead of the old plain text method which tried to re-create a paste operation, the * new approach adds a plain text mode toggle switch that changes the behavior of paste. * This function is passed the same input that the regular paste plugin produces. * It performs additional scrubbing and produces (and inserts) the plain text. * This approach leverages all of the great existing functionality in the paste * plugin, and requires minimal changes to add the new functionality. * Speednet - June 2009 */ _insertPlainText : function(content) { var ed = this.editor, linebr = getParam(ed, "paste_text_linebreaktype"), rl = getParam(ed, "paste_text_replacements"), is = tinymce.is; function process(items) { each(items, function(v) { if (v.constructor == RegExp) content = content.replace(v, ""); else content = content.replace(v[0], v[1]); }); }; if ((typeof(content) === "string") && (content.length > 0)) { // If HTML content with line-breaking tags, then remove all cr/lf chars because only tags will break a line if (/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(content)) { process([ /[\n\r]+/g ]); } else { // Otherwise just get rid of carriage returns (only need linefeeds) process([ /\r+/g ]); } process([ [/<\/(?:p|h[1-6]|ul|ol|dl|table|div|blockquote|fieldset|pre|address|center)>/gi, "\n\n"], // Block tags get a blank line after them [/<br[^>]*>|<\/tr>/gi, "\n"], // Single linebreak for <br /> tags and table rows [/<\/t[dh]>\s*<t[dh][^>]*>/gi, "\t"], // Table cells get tabs betweem them /<[a-z!\/?][^>]*>/gi, // Delete all remaining tags [/&nbsp;/gi, " "], // Convert non-break spaces to regular spaces (remember, *plain text*) [/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi, "$1"] // Cool little RegExp deletes whitespace around linebreak chars. ]); var maxLinebreaks = Number(getParam(ed, "paste_max_consecutive_linebreaks")); if (maxLinebreaks > -1) { var maxLinebreaksRegex = new RegExp("\n{" + (maxLinebreaks + 1) + ",}", "g"); var linebreakReplacement = ""; while (linebreakReplacement.length < maxLinebreaks) { linebreakReplacement += "\n"; } process([ [maxLinebreaksRegex, linebreakReplacement] // Limit max consecutive linebreaks ]); } content = ed.dom.decode(tinymce.html.Entities.encodeRaw(content)); // Perform default or custom replacements if (is(rl, "array")) { process(rl); } else if (is(rl, "string")) { process(new RegExp(rl, "gi")); } // Treat paragraphs as specified in the config if (linebr == "none") { // Convert all line breaks to space process([ [/\n+/g, " "] ]); } else if (linebr == "br") { // Convert all line breaks to <br /> process([ [/\n/g, "<br />"] ]); } else if (linebr == "p") { // Convert all line breaks to <p>...</p> process([ [/\n+/g, "</p><p>"], [/^(.*<\/p>)(<p>)$/, '<p>$1'] ]); } else { // defaults to "combined" // Convert single line breaks to <br /> and double line breaks to <p>...</p> process([ [/\n\n/g, "</p><p>"], [/^(.*<\/p>)(<p>)$/, '<p>$1'], [/\n/g, "<br />"] ]); } ed.execCommand('mceInsertContent', false, content); } }, /** * This method will open the old style paste dialogs. Some users might want the old behavior but still use the new cleanup engine. */ _legacySupport : function() { var t = this, ed = t.editor; // Register command(s) for backwards compatibility ed.addCommand("mcePasteWord", function() { ed.windowManager.open({ file: t.url + "/pasteword.htm", width: parseInt(getParam(ed, "paste_dialog_width")), height: parseInt(getParam(ed, "paste_dialog_height")), inline: 1 }); }); if (getParam(ed, "paste_text_use_dialog")) { ed.addCommand("mcePasteText", function() { ed.windowManager.open({ file : t.url + "/pastetext.htm", width: parseInt(getParam(ed, "paste_dialog_width")), height: parseInt(getParam(ed, "paste_dialog_height")), inline : 1 }); }); } // Register button for backwards compatibility ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"}); } }); // Register plugin tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin); })();
JavaScript
tinyMCEPopup.requireLangPack(); var PasteTextDialog = { init : function() { this.resize(); }, insert : function() { var h = tinyMCEPopup.dom.encode(document.getElementById('content').value), lines; // Convert linebreaks into paragraphs if (document.getElementById('linebreaks').checked) { lines = h.split(/\r?\n/); if (lines.length > 1) { h = ''; tinymce.each(lines, function(row) { h += '<p>' + row + '</p>'; }); } } tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, {content : h}); tinyMCEPopup.close(); }, resize : function() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('content'); el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 90) + 'px'; } }; tinyMCEPopup.onInit.add(PasteTextDialog.init, PasteTextDialog);
JavaScript
tinyMCEPopup.requireLangPack(); var PasteWordDialog = { init : function() { var ed = tinyMCEPopup.editor, el = document.getElementById('iframecontainer'), ifr, doc, css, cssHTML = ''; // Create iframe el.innerHTML = '<iframe id="iframe" src="javascript:\'\';" frameBorder="0" style="border: 1px solid gray"></iframe>'; ifr = document.getElementById('iframe'); doc = ifr.contentWindow.document; // Force absolute CSS urls css = [ed.baseURI.toAbsolute("themes/" + ed.settings.theme + "/skins/" + ed.settings.skin + "/content.css")]; css = css.concat(tinymce.explode(ed.settings.content_css) || []); tinymce.each(css, function(u) { cssHTML += '<link href="' + ed.documentBaseURI.toAbsolute('' + u) + '" rel="stylesheet" type="text/css" />'; }); // Write content into iframe doc.open(); doc.write('<html><head>' + cssHTML + '</head><body class="mceContentBody" spellcheck="false"></body></html>'); doc.close(); doc.designMode = 'on'; this.resize(); window.setTimeout(function() { ifr.contentWindow.focus(); }, 10); }, insert : function() { var h = document.getElementById('iframe').contentWindow.document.body.innerHTML; tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, {content : h, wordContent : true}); tinyMCEPopup.close(); }, resize : function() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('iframe'); if (el) { el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 90) + 'px'; } } }; tinyMCEPopup.onInit.add(PasteWordDialog.init, PasteWordDialog);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.BBCodePlugin', { init : function(ed, url) { var t = this, dialect = ed.getParam('bbcode_dialect', 'punbb').toLowerCase(); ed.onBeforeSetContent.add(function(ed, o) { o.content = t['_' + dialect + '_bbcode2html'](o.content); }); ed.onPostProcess.add(function(ed, o) { if (o.set) o.content = t['_' + dialect + '_bbcode2html'](o.content); if (o.get) o.content = t['_' + dialect + '_html2bbcode'](o.content); }); }, getInfo : function() { return { longname : 'BBCode Plugin', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/bbcode', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods // HTML -> BBCode in PunBB dialect _punbb_html2bbcode : function(s) { s = tinymce.trim(s); function rep(re, str) { s = s.replace(re, str); }; // example: <strong> to [b] rep(/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/gi,"[url=$1]$2[/url]"); rep(/<font.*?color=\"(.*?)\".*?class=\"codeStyle\".*?>(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]"); rep(/<font.*?color=\"(.*?)\".*?class=\"quoteStyle\".*?>(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]"); rep(/<font.*?class=\"codeStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]"); rep(/<font.*?class=\"quoteStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]"); rep(/<span style=\"color: ?(.*?);\">(.*?)<\/span>/gi,"[color=$1]$2[/color]"); rep(/<font.*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[color=$1]$2[/color]"); rep(/<span style=\"font-size:(.*?);\">(.*?)<\/span>/gi,"[size=$1]$2[/size]"); rep(/<font>(.*?)<\/font>/gi,"$1"); rep(/<img.*?src=\"(.*?)\".*?\/>/gi,"[img]$1[/img]"); rep(/<span class=\"codeStyle\">(.*?)<\/span>/gi,"[code]$1[/code]"); rep(/<span class=\"quoteStyle\">(.*?)<\/span>/gi,"[quote]$1[/quote]"); rep(/<strong class=\"codeStyle\">(.*?)<\/strong>/gi,"[code][b]$1[/b][/code]"); rep(/<strong class=\"quoteStyle\">(.*?)<\/strong>/gi,"[quote][b]$1[/b][/quote]"); rep(/<em class=\"codeStyle\">(.*?)<\/em>/gi,"[code][i]$1[/i][/code]"); rep(/<em class=\"quoteStyle\">(.*?)<\/em>/gi,"[quote][i]$1[/i][/quote]"); rep(/<u class=\"codeStyle\">(.*?)<\/u>/gi,"[code][u]$1[/u][/code]"); rep(/<u class=\"quoteStyle\">(.*?)<\/u>/gi,"[quote][u]$1[/u][/quote]"); rep(/<\/(strong|b)>/gi,"[/b]"); rep(/<(strong|b)>/gi,"[b]"); rep(/<\/(em|i)>/gi,"[/i]"); rep(/<(em|i)>/gi,"[i]"); rep(/<\/u>/gi,"[/u]"); rep(/<span style=\"text-decoration: ?underline;\">(.*?)<\/span>/gi,"[u]$1[/u]"); rep(/<u>/gi,"[u]"); rep(/<blockquote[^>]*>/gi,"[quote]"); rep(/<\/blockquote>/gi,"[/quote]"); rep(/<br \/>/gi,"\n"); rep(/<br\/>/gi,"\n"); rep(/<br>/gi,"\n"); rep(/<p>/gi,""); rep(/<\/p>/gi,"\n"); rep(/&nbsp;|\u00a0/gi," "); rep(/&quot;/gi,"\""); rep(/&lt;/gi,"<"); rep(/&gt;/gi,">"); rep(/&amp;/gi,"&"); return s; }, // BBCode -> HTML from PunBB dialect _punbb_bbcode2html : function(s) { s = tinymce.trim(s); function rep(re, str) { s = s.replace(re, str); }; // example: [b] to <strong> rep(/\n/gi,"<br />"); rep(/\[b\]/gi,"<strong>"); rep(/\[\/b\]/gi,"</strong>"); rep(/\[i\]/gi,"<em>"); rep(/\[\/i\]/gi,"</em>"); rep(/\[u\]/gi,"<u>"); rep(/\[\/u\]/gi,"</u>"); rep(/\[url=([^\]]+)\](.*?)\[\/url\]/gi,"<a href=\"$1\">$2</a>"); rep(/\[url\](.*?)\[\/url\]/gi,"<a href=\"$1\">$1</a>"); rep(/\[img\](.*?)\[\/img\]/gi,"<img src=\"$1\" />"); rep(/\[color=(.*?)\](.*?)\[\/color\]/gi,"<font color=\"$1\">$2</font>"); rep(/\[code\](.*?)\[\/code\]/gi,"<span class=\"codeStyle\">$1</span>&nbsp;"); rep(/\[quote.*?\](.*?)\[\/quote\]/gi,"<span class=\"quoteStyle\">$1</span>&nbsp;"); return s; } }); // Register plugin tinymce.PluginManager.add('bbcode', tinymce.plugins.BBCodePlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.Nonbreaking', { init : function(ed, url) { var t = this; t.editor = ed; // Register commands ed.addCommand('mceNonBreaking', function() { ed.execCommand('mceInsertContent', false, (ed.plugins.visualchars && ed.plugins.visualchars.state) ? '<span data-mce-bogus="1" class="mceItemHidden mceItemNbsp">&nbsp;</span>' : '&nbsp;'); }); // Register buttons ed.addButton('nonbreaking', {title : 'nonbreaking.nonbreaking_desc', cmd : 'mceNonBreaking'}); if (ed.getParam('nonbreaking_force_tab')) { ed.onKeyDown.add(function(ed, e) { if (e.keyCode == 9) { e.preventDefault(); ed.execCommand('mceNonBreaking'); ed.execCommand('mceNonBreaking'); ed.execCommand('mceNonBreaking'); } }); } }, getInfo : function() { return { longname : 'Nonbreaking space', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/nonbreaking', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } // Private methods }); // Register plugin tinymce.PluginManager.add('nonbreaking', tinymce.plugins.Nonbreaking); })();
JavaScript
/** * @license Highcharts JS v3.0.2 (2013-06-05) * MooTools adapter * * (c) 2010-2013 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Fx, $, $extend, $each, $merge, Events, Event, DOMEvent */ (function () { var win = window, doc = document, mooVersion = win.MooTools.version.substring(0, 3), // Get the first three characters of the version number legacy = mooVersion === '1.2' || mooVersion === '1.1', // 1.1 && 1.2 considered legacy, 1.3 is not. legacyEvent = legacy || mooVersion === '1.3', // In versions 1.1 - 1.3 the event class is named Event, in newer versions it is named DOMEvent. $extend = win.$extend || function () { return Object.append.apply(Object, arguments); }; win.HighchartsAdapter = { /** * Initialize the adapter. This is run once as Highcharts is first run. * @param {Object} pathAnim The helper object to do animations across adapters. */ init: function (pathAnim) { var fxProto = Fx.prototype, fxStart = fxProto.start, morphProto = Fx.Morph.prototype, morphCompute = morphProto.compute; // override Fx.start to allow animation of SVG element wrappers /*jslint unparam: true*//* allow unused parameters in fx functions */ fxProto.start = function (from, to) { var fx = this, elem = fx.element; // special for animating paths if (from.d) { //this.fromD = this.element.d.split(' '); fx.paths = pathAnim.init( elem, elem.d, fx.toD ); } fxStart.apply(fx, arguments); return this; // chainable }; // override Fx.step to allow animation of SVG element wrappers morphProto.compute = function (from, to, delta) { var fx = this, paths = fx.paths; if (paths) { fx.element.attr( 'd', pathAnim.step(paths[0], paths[1], delta, fx.toD) ); } else { return morphCompute.apply(fx, arguments); } }; /*jslint unparam: false*/ }, /** * Run a general method on the framework, following jQuery syntax * @param {Object} el The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (el, method) { // This currently works for getting inner width and height. If adding // more methods later, we need a conditional implementation for each. if (method === 'width' || method === 'height') { return parseInt($(el).getStyle(method), 10); } }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: function (scriptLocation, callback) { // We cannot assume that Assets class from mootools-more is available so instead insert a script tag to download script. var head = doc.getElementsByTagName('head')[0]; var script = doc.createElement('script'); script.type = 'text/javascript'; script.src = scriptLocation; script.onload = callback; head.appendChild(script); }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var isSVGElement = el.attr, effect, complete = options && options.complete; if (isSVGElement && !el.setStyle) { // add setStyle and getStyle methods for internal use in Moo el.getStyle = el.attr; el.setStyle = function () { // property value is given as array in Moo - break it down var args = arguments; this.attr.call(this, args[0], args[1][0]); }; // dirty hack to trick Moo into handling el as an element wrapper el.$family = function () { return true; }; } // stop running animations win.HighchartsAdapter.stop(el); // define and run the effect effect = new Fx.Morph( isSVGElement ? el : $(el), $extend({ transition: Fx.Transitions.Quad.easeInOut }, options) ); // Make sure that the element reference is set when animating svg elements if (isSVGElement) { effect.element = el; } // special treatment for paths if (params.d) { effect.toD = params.d; } // jQuery-like events if (complete) { effect.addEvent('complete', complete); } // run effect.start(params); // record for use in stop method el.fx = effect; }, /** * MooTool's each function * */ each: function (arr, fn) { return legacy ? $each(arr, fn) : Array.each(arr, fn); }, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { return arr.map(fn); }, /** * Grep or filter an array * @param {Array} arr * @param {Function} fn */ grep: function (arr, fn) { return arr.filter(fn); }, /** * Return the index of an item in an array, or -1 if not matched */ inArray: function (item, arr, from) { return arr ? arr.indexOf(item, from) : -1; }, /** * Get the offset of an element relative to the top left corner of the web page */ offset: function (el) { var offsets = el.getPosition(); // #1496 return { left: offsets.x, top: offsets.y }; }, /** * Extends an object with Events, if its not done */ extendWithEvents: function (el) { // if the addEvent method is not defined, el is a custom Highcharts object // like series or point if (!el.addEvent) { if (el.nodeName) { el = $(el); // a dynamically generated node } else { $extend(el, new Events()); // a custom object } } }, /** * Add an event listener * @param {Object} el HTML element or custom object * @param {String} type Event type * @param {Function} fn Event handler */ addEvent: function (el, type, fn) { if (typeof type === 'string') { // chart broke due to el being string, type function if (type === 'unload') { // Moo self destructs before custom unload events type = 'beforeunload'; } win.HighchartsAdapter.extendWithEvents(el); el.addEvent(type, fn); } }, removeEvent: function (el, type, fn) { if (typeof el === 'string') { // el.removeEvents below apperantly calls this method again. Do not quite understand why, so for now just bail out. return; } if (el.addEvent) { // If el doesn't have an addEvent method, there are no events to remove if (type) { if (type === 'unload') { // Moo self destructs before custom unload events type = 'beforeunload'; } if (fn) { el.removeEvent(type, fn); } else if (el.removeEvents) { // #958 el.removeEvents(type); } } else { el.removeEvents(); } } }, fireEvent: function (el, event, eventArguments, defaultFunction) { var eventArgs = { type: event, target: el }; // create an event object that keeps all functions event = legacyEvent ? new Event(eventArgs) : new DOMEvent(eventArgs); event = $extend(event, eventArguments); // When running an event on the Chart.prototype, MooTools nests the target in event.event if (!event.target && event.event) { event.target = event.event.target; } // override the preventDefault function to be able to use // this for custom events event.preventDefault = function () { defaultFunction = null; }; // if fireEvent is not available on the object, there hasn't been added // any events to it above if (el.fireEvent) { el.fireEvent(event.type, event); } // fire the default if it is passed and it is not prevented above if (defaultFunction) { defaultFunction(event); } }, /** * Set back e.pageX and e.pageY that MooTools has abstracted away. #1165, #1346. */ washMouseEvent: function (e) { if (e.page) { e.pageX = e.page.x; e.pageY = e.page.y; } return e; }, /** * Stop running animations on the object */ stop: function (el) { if (el.fx) { el.fx.cancel(); } } }; }());
JavaScript
/** * Dark blue theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: [0, 0, 250, 500], stops: [ [0, 'rgb(48, 96, 48)'], [1, 'rgb(0, 0, 0)'] ] }, borderColor: '#000000', borderWidth: 2, className: 'dark-container', plotBackgroundColor: 'rgba(255, 255, 255, .1)', plotBorderColor: '#CCCCCC', plotBorderWidth: 1 }, title: { style: { color: '#C0C0C0', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineColor: '#333333', gridLineWidth: 1, labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', tickColor: '#A0A0A0', title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { gridLineColor: '#333333', labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', minorTickInterval: null, tickColor: '#A0A0A0', tickWidth: 1, title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, tooltip: { backgroundColor: 'rgba(0, 0, 0, 0.75)', style: { color: '#F0F0F0' } }, toolbar: { itemStyle: { color: 'silver' } }, plotOptions: { line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } }, candlestick: { lineColor: 'white' } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: '#A0A0A0' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#444' } }, credits: { style: { color: '#666' } }, labels: { style: { color: '#CCC' } }, navigation: { buttonOptions: { symbolStroke: '#DDDDDD', hoverSymbolStroke: '#FFFFFF', theme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, stroke: '#000000' } } }, // scroll charts rangeSelector: { buttonTheme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, stroke: '#000000', style: { color: '#CCC', fontWeight: 'bold' }, states: { hover: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#BBB'], [0.6, '#888'] ] }, stroke: '#000000', style: { color: 'white' } }, select: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.1, '#000'], [0.3, '#333'] ] }, stroke: '#000000', style: { color: 'yellow' } } } }, inputStyle: { backgroundColor: '#333', color: 'silver' }, labelStyle: { color: 'silver' } }, navigator: { handles: { backgroundColor: '#666', borderColor: '#AAA' }, outlineColor: '#CCC', maskFill: 'rgba(16, 16, 16, 0.5)', series: { color: '#7798BF', lineColor: '#A6C7ED' } }, scrollbar: { barBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, barBorderColor: '#CCC', buttonArrowColor: '#CCC', buttonBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, buttonBorderColor: '#CCC', rifleColor: '#FFF', trackBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, '#000'], [1, '#333'] ] }, trackBorderColor: '#666' }, // special colors for some of the legendBackgroundColor: 'rgba(0, 0, 0, 0.5)', legendBackgroundColorSolid: 'rgb(35, 35, 70)', dataLabelsColor: '#444', textColor: '#C0C0C0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Skies theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#514F78", "#42A07B", "#9B5E4A", "#72727F", "#1F949A", "#82914E", "#86777F", "#42A07B"], chart: { className: 'skies', borderWidth: 0, plotShadow: true, plotBackgroundImage: '/demo/gfx/skies.jpg', plotBackgroundColor: { linearGradient: [0, 0, 250, 500], stops: [ [0, 'rgba(255, 255, 255, 1)'], [1, 'rgba(255, 255, 255, 0)'] ] }, plotBorderWidth: 1 }, title: { style: { color: '#3E576F', font: '16px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, subtitle: { style: { color: '#6D869F', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, xAxis: { gridLineWidth: 0, lineColor: '#C0D0E0', tickColor: '#C0D0E0', labels: { style: { color: '#666', fontWeight: 'bold' } }, title: { style: { color: '#666', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, yAxis: { alternateGridColor: 'rgba(255, 255, 255, .5)', lineColor: '#C0D0E0', tickColor: '#C0D0E0', tickWidth: 1, labels: { style: { color: '#666', fontWeight: 'bold' } }, title: { style: { color: '#666', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: '#3E576F' }, itemHoverStyle: { color: 'black' }, itemHiddenStyle: { color: 'silver' } }, labels: { style: { color: '#3E576F' } } }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Gray theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#7798BF", "#55BF3B", "#DF5353", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, 'rgb(96, 96, 96)'], [1, 'rgb(16, 16, 16)'] ] }, borderWidth: 0, borderRadius: 15, plotBackgroundColor: null, plotShadow: false, plotBorderWidth: 0 }, title: { style: { color: '#FFF', font: '16px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, subtitle: { style: { color: '#DDD', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, xAxis: { gridLineWidth: 0, lineColor: '#999', tickColor: '#999', labels: { style: { color: '#999', fontWeight: 'bold' } }, title: { style: { color: '#AAA', font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, yAxis: { alternateGridColor: null, minorTickInterval: null, gridLineColor: 'rgba(255, 255, 255, .1)', minorGridLineColor: 'rgba(255,255,255,0.07)', lineWidth: 0, tickWidth: 0, labels: { style: { color: '#999', fontWeight: 'bold' } }, title: { style: { color: '#AAA', font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, legend: { itemStyle: { color: '#CCC' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#333' } }, labels: { style: { color: '#CCC' } }, tooltip: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, 'rgba(96, 96, 96, .8)'], [1, 'rgba(16, 16, 16, .8)'] ] }, borderWidth: 0, style: { color: '#FFF' } }, plotOptions: { series: { shadow: true }, line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } }, candlestick: { lineColor: 'white' } }, toolbar: { itemStyle: { color: '#CCC' } }, navigation: { buttonOptions: { symbolStroke: '#DDDDDD', hoverSymbolStroke: '#FFFFFF', theme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, stroke: '#000000' } } }, // scroll charts rangeSelector: { buttonTheme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, stroke: '#000000', style: { color: '#CCC', fontWeight: 'bold' }, states: { hover: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#BBB'], [0.6, '#888'] ] }, stroke: '#000000', style: { color: 'white' } }, select: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.1, '#000'], [0.3, '#333'] ] }, stroke: '#000000', style: { color: 'yellow' } } } }, inputStyle: { backgroundColor: '#333', color: 'silver' }, labelStyle: { color: 'silver' } }, navigator: { handles: { backgroundColor: '#666', borderColor: '#AAA' }, outlineColor: '#CCC', maskFill: 'rgba(16, 16, 16, 0.5)', series: { color: '#7798BF', lineColor: '#A6C7ED' } }, scrollbar: { barBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, barBorderColor: '#CCC', buttonArrowColor: '#CCC', buttonBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, buttonBorderColor: '#CCC', rifleColor: '#FFF', trackBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, '#000'], [1, '#333'] ] }, trackBorderColor: '#666' }, // special colors for some of the demo examples legendBackgroundColor: 'rgba(48, 48, 48, 0.8)', legendBackgroundColorSolid: 'rgb(70, 70, 70)', dataLabelsColor: '#444', textColor: '#E0E0E0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Dark blue theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 }, stops: [ [0, 'rgb(48, 48, 96)'], [1, 'rgb(0, 0, 0)'] ] }, borderColor: '#000000', borderWidth: 2, className: 'dark-container', plotBackgroundColor: 'rgba(255, 255, 255, .1)', plotBorderColor: '#CCCCCC', plotBorderWidth: 1 }, title: { style: { color: '#C0C0C0', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineColor: '#333333', gridLineWidth: 1, labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', tickColor: '#A0A0A0', title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { gridLineColor: '#333333', labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', minorTickInterval: null, tickColor: '#A0A0A0', tickWidth: 1, title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, tooltip: { backgroundColor: 'rgba(0, 0, 0, 0.75)', style: { color: '#F0F0F0' } }, toolbar: { itemStyle: { color: 'silver' } }, plotOptions: { line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } }, candlestick: { lineColor: 'white' } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: '#A0A0A0' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#444' } }, credits: { style: { color: '#666' } }, labels: { style: { color: '#CCC' } }, navigation: { buttonOptions: { symbolStroke: '#DDDDDD', hoverSymbolStroke: '#FFFFFF', theme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, stroke: '#000000' } } }, // scroll charts rangeSelector: { buttonTheme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, stroke: '#000000', style: { color: '#CCC', fontWeight: 'bold' }, states: { hover: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#BBB'], [0.6, '#888'] ] }, stroke: '#000000', style: { color: 'white' } }, select: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.1, '#000'], [0.3, '#333'] ] }, stroke: '#000000', style: { color: 'yellow' } } } }, inputStyle: { backgroundColor: '#333', color: 'silver' }, labelStyle: { color: 'silver' } }, navigator: { handles: { backgroundColor: '#666', borderColor: '#AAA' }, outlineColor: '#CCC', maskFill: 'rgba(16, 16, 16, 0.5)', series: { color: '#7798BF', lineColor: '#A6C7ED' } }, scrollbar: { barBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, barBorderColor: '#CCC', buttonArrowColor: '#CCC', buttonBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, buttonBorderColor: '#CCC', rifleColor: '#FFF', trackBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, '#000'], [1, '#333'] ] }, trackBorderColor: '#666' }, // special colors for some of the legendBackgroundColor: 'rgba(0, 0, 0, 0.5)', legendBackgroundColorSolid: 'rgb(35, 35, 70)', dataLabelsColor: '#444', textColor: '#C0C0C0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Grid theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'], chart: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 }, stops: [ [0, 'rgb(255, 255, 255)'], [1, 'rgb(240, 240, 255)'] ] }, borderWidth: 2, plotBackgroundColor: 'rgba(255, 255, 255, .9)', plotShadow: true, plotBorderWidth: 1 }, title: { style: { color: '#000', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineWidth: 1, lineColor: '#000', tickColor: '#000', labels: { style: { color: '#000', font: '11px Trebuchet MS, Verdana, sans-serif' } }, title: { style: { color: '#333', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { minorTickInterval: 'auto', lineColor: '#000', lineWidth: 1, tickWidth: 1, tickColor: '#000', labels: { style: { color: '#000', font: '11px Trebuchet MS, Verdana, sans-serif' } }, title: { style: { color: '#333', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: 'black' }, itemHoverStyle: { color: '#039' }, itemHiddenStyle: { color: 'gray' } }, labels: { style: { color: '#99b' } }, navigation: { buttonOptions: { theme: { stroke: '#CCCCCC' } } } }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * @license Highcharts JS v3.0.2 (2013-06-05) * Exporting module * * (c) 2010-2013 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, document, window, Math, setTimeout */ (function (Highcharts) { // encapsulate // create shortcuts var Chart = Highcharts.Chart, addEvent = Highcharts.addEvent, removeEvent = Highcharts.removeEvent, createElement = Highcharts.createElement, discardElement = Highcharts.discardElement, css = Highcharts.css, merge = Highcharts.merge, each = Highcharts.each, extend = Highcharts.extend, math = Math, mathMax = math.max, doc = document, win = window, isTouchDevice = Highcharts.isTouchDevice, M = 'M', L = 'L', DIV = 'div', HIDDEN = 'hidden', NONE = 'none', PREFIX = 'highcharts-', ABSOLUTE = 'absolute', PX = 'px', UNDEFINED, symbols = Highcharts.Renderer.prototype.symbols, defaultOptions = Highcharts.getOptions(), buttonOffset; // Add language extend(defaultOptions.lang, { printChart: 'Print chart', downloadPNG: 'Download PNG image', downloadJPEG: 'Download JPEG image', downloadPDF: 'Download PDF document', downloadSVG: 'Download SVG vector image', contextButtonTitle: 'Chart context menu' }); // Buttons and menus are collected in a separate config option set called 'navigation'. // This can be extended later to add control buttons like zoom and pan right click menus. defaultOptions.navigation = { menuStyle: { border: '1px solid #A0A0A0', background: '#FFFFFF', padding: '5px 0' }, menuItemStyle: { padding: '0 10px', background: NONE, color: '#303030', fontSize: isTouchDevice ? '14px' : '11px' }, menuItemHoverStyle: { background: '#4572A5', color: '#FFFFFF' }, buttonOptions: { symbolFill: '#E0E0E0', symbolSize: 14, symbolStroke: '#666', symbolStrokeWidth: 3, symbolX: 12.5, symbolY: 10.5, align: 'right', buttonSpacing: 3, height: 22, // text: null, theme: { fill: 'white', // capture hover stroke: 'none' }, verticalAlign: 'top', width: 24 } }; // Add the export related options defaultOptions.exporting = { //enabled: true, //filename: 'chart', type: 'image/png', url: 'http://export.highcharts.com/', //width: undefined, //scale: 2 buttons: { contextButton: { //x: -10, symbol: 'menu', _titleKey: 'contextButtonTitle', menuItems: [{ textKey: 'printChart', onclick: function () { this.print(); } }, { separator: true }, { textKey: 'downloadPNG', onclick: function () { this.exportChart(); } }, { textKey: 'downloadJPEG', onclick: function () { this.exportChart({ type: 'image/jpeg' }); } }, { textKey: 'downloadPDF', onclick: function () { this.exportChart({ type: 'application/pdf' }); } }, { textKey: 'downloadSVG', onclick: function () { this.exportChart({ type: 'image/svg+xml' }); } } // Enable this block to add "View SVG" to the dropdown menu /* ,{ text: 'View SVG', onclick: function () { var svg = this.getSVG() .replace(/</g, '\n&lt;') .replace(/>/g, '&gt;'); doc.body.innerHTML = '<pre>' + svg + '</pre>'; } } // */ ] } } }; // Add the Highcharts.post utility Highcharts.post = function (url, data) { var name, form; // create the form form = createElement('form', { method: 'post', action: url, enctype: 'multipart/form-data' }, { display: NONE }, doc.body); // add the data for (name in data) { createElement('input', { type: HIDDEN, name: name, value: data[name] }, null, form); } // submit form.submit(); // clean up discardElement(form); }; extend(Chart.prototype, { /** * Return an SVG representation of the chart * * @param additionalOptions {Object} Additional chart options for the generated SVG representation */ getSVG: function (additionalOptions) { var chart = this, chartCopy, sandbox, svg, seriesOptions, sourceWidth, sourceHeight, cssWidth, cssHeight, options = merge(chart.options, additionalOptions); // copy the options and add extra options // IE compatibility hack for generating SVG content that it doesn't really understand if (!doc.createElementNS) { /*jslint unparam: true*//* allow unused parameter ns in function below */ doc.createElementNS = function (ns, tagName) { return doc.createElement(tagName); }; /*jslint unparam: false*/ } // create a sandbox where a new chart will be generated sandbox = createElement(DIV, null, { position: ABSOLUTE, top: '-9999em', width: chart.chartWidth + PX, height: chart.chartHeight + PX }, doc.body); // get the source size cssWidth = chart.renderTo.style.width; cssHeight = chart.renderTo.style.height; sourceWidth = options.exporting.sourceWidth || options.chart.width || (/px$/.test(cssWidth) && parseInt(cssWidth, 10)) || 600; sourceHeight = options.exporting.sourceHeight || options.chart.height || (/px$/.test(cssHeight) && parseInt(cssHeight, 10)) || 400; // override some options extend(options.chart, { animation: false, renderTo: sandbox, forExport: true, width: sourceWidth, height: sourceHeight }); options.exporting.enabled = false; // hide buttons in print // prepare for replicating the chart options.series = []; each(chart.series, function (serie) { seriesOptions = merge(serie.options, { animation: false, // turn off animation showCheckbox: false, visible: serie.visible }); if (!seriesOptions.isInternal) { // used for the navigator series that has its own option set options.series.push(seriesOptions); } }); // generate the chart copy chartCopy = new Highcharts.Chart(options, chart.callback); // reflect axis extremes in the export each(['xAxis', 'yAxis'], function (axisType) { each(chart[axisType], function (axis, i) { var axisCopy = chartCopy[axisType][i], extremes = axis.getExtremes(), userMin = extremes.userMin, userMax = extremes.userMax; if (userMin !== UNDEFINED || userMax !== UNDEFINED) { axisCopy.setExtremes(userMin, userMax, true, false); } }); }); // get the SVG from the container's innerHTML svg = chartCopy.container.innerHTML; // free up memory options = null; chartCopy.destroy(); discardElement(sandbox); // sanitize svg = svg .replace(/zIndex="[^"]+"/g, '') .replace(/isShadow="[^"]+"/g, '') .replace(/symbolName="[^"]+"/g, '') .replace(/jQuery[0-9]+="[^"]+"/g, '') .replace(/url\([^#]+#/g, 'url(#') .replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ') .replace(/ href=/g, ' xlink:href=') .replace(/\n/, ' ') .replace(/<\/svg>.*?$/, '</svg>') // any HTML added to the container after the SVG (#894) /* This fails in IE < 8 .replace(/([0-9]+)\.([0-9]+)/g, function(s1, s2, s3) { // round off to save weight return s2 +'.'+ s3[0]; })*/ // Replace HTML entities, issue #347 .replace(/&nbsp;/g, '\u00A0') // no-break space .replace(/&shy;/g, '\u00AD') // soft hyphen // IE specific .replace(/<IMG /g, '<image ') .replace(/height=([^" ]+)/g, 'height="$1"') .replace(/width=([^" ]+)/g, 'width="$1"') .replace(/hc-svg-href="([^"]+)">/g, 'xlink:href="$1"/>') .replace(/id=([^" >]+)/g, 'id="$1"') .replace(/class=([^" >]+)/g, 'class="$1"') .replace(/ transform /g, ' ') .replace(/:(path|rect)/g, '$1') .replace(/style="([^"]+)"/g, function (s) { return s.toLowerCase(); }); // IE9 beta bugs with innerHTML. Test again with final IE9. svg = svg.replace(/(url\(#highcharts-[0-9]+)&quot;/g, '$1') .replace(/&quot;/g, "'"); if (svg.match(/ xmlns="/g).length === 2) { svg = svg.replace(/xmlns="[^"]+"/, ''); } return svg; }, /** * Submit the SVG representation of the chart to the server * @param {Object} options Exporting options. Possible members are url, type and width. * @param {Object} chartOptions Additional chart options for the SVG representation of the chart */ exportChart: function (options, chartOptions) { options = options || {}; var chart = this, chartExportingOptions = chart.options.exporting, svg = chart.getSVG(merge( { chart: { borderRadius: 0 } }, chartExportingOptions.chartOptions, chartOptions, { exporting: { sourceWidth: options.sourceWidth || chartExportingOptions.sourceWidth, // docs: option and parameter in exportChart() sourceHeight: options.sourceHeight || chartExportingOptions.sourceHeight // docs } } )); // merge the options options = merge(chart.options.exporting, options); // do the post Highcharts.post(options.url, { filename: options.filename || 'chart', type: options.type, width: options.width || 0, // IE8 fails to post undefined correctly, so use 0 scale: options.scale || 2, svg: svg }); }, /** * Print the chart */ print: function () { var chart = this, container = chart.container, origDisplay = [], origParent = container.parentNode, body = doc.body, childNodes = body.childNodes; if (chart.isPrinting) { // block the button while in printing mode return; } chart.isPrinting = true; // hide all body content each(childNodes, function (node, i) { if (node.nodeType === 1) { origDisplay[i] = node.style.display; node.style.display = NONE; } }); // pull out the chart body.appendChild(container); // print win.focus(); // #1510 win.print(); // allow the browser to prepare before reverting setTimeout(function () { // put the chart back in origParent.appendChild(container); // restore all body content each(childNodes, function (node, i) { if (node.nodeType === 1) { node.style.display = origDisplay[i]; } }); chart.isPrinting = false; }, 1000); }, /** * Display a popup menu for choosing the export type * * @param {String} name An identifier for the menu * @param {Array} items A collection with text and onclicks for the items * @param {Number} x The x position of the opener button * @param {Number} y The y position of the opener button * @param {Number} width The width of the opener button * @param {Number} height The height of the opener button */ contextMenu: function (name, items, x, y, width, height, button) { var chart = this, navOptions = chart.options.navigation, menuItemStyle = navOptions.menuItemStyle, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, cacheName = 'cache-' + name, menu = chart[cacheName], menuPadding = mathMax(width, height), // for mouse leave detection boxShadow = '3px 3px 10px #888', innerMenu, hide, hideTimer, menuStyle; // create the menu only the first time if (!menu) { // create a HTML element above the SVG chart[cacheName] = menu = createElement(DIV, { className: PREFIX + name }, { position: ABSOLUTE, zIndex: 1000, padding: menuPadding + PX }, chart.container); innerMenu = createElement(DIV, null, extend({ MozBoxShadow: boxShadow, WebkitBoxShadow: boxShadow, boxShadow: boxShadow }, navOptions.menuStyle), menu); // hide on mouse out hide = function () { css(menu, { display: NONE }); if (button) { button.setState(0); } chart.openMenu = false; }; // Hide the menu some time after mouse leave (#1357) addEvent(menu, 'mouseleave', function () { hideTimer = setTimeout(hide, 500); }); addEvent(menu, 'mouseenter', function () { clearTimeout(hideTimer); }); // create the items each(items, function (item) { if (item) { var element = item.separator ? createElement('hr', null, null, innerMenu) : createElement(DIV, { onmouseover: function () { css(this, navOptions.menuItemHoverStyle); }, onmouseout: function () { css(this, menuItemStyle); }, onclick: function () { hide(); item.onclick.apply(chart, arguments); }, innerHTML: item.text || chart.options.lang[item.textKey] }, extend({ cursor: 'pointer' }, menuItemStyle), innerMenu); // Keep references to menu divs to be able to destroy them chart.exportDivElements.push(element); } }); // Keep references to menu and innerMenu div to be able to destroy them chart.exportDivElements.push(innerMenu, menu); chart.exportMenuWidth = menu.offsetWidth; chart.exportMenuHeight = menu.offsetHeight; } menuStyle = { display: 'block' }; // if outside right, right align it if (x + chart.exportMenuWidth > chartWidth) { menuStyle.right = (chartWidth - x - width - menuPadding) + PX; } else { menuStyle.left = (x - menuPadding) + PX; } // if outside bottom, bottom align it if (y + height + chart.exportMenuHeight > chartHeight) { menuStyle.bottom = (chartHeight - y - menuPadding) + PX; } else { menuStyle.top = (y + height - menuPadding) + PX; } css(menu, menuStyle); chart.openMenu = true; }, /** * Add the export button to the chart */ addButton: function (options) { var chart = this, renderer = chart.renderer, btnOptions = merge(chart.options.navigation.buttonOptions, options), onclick = btnOptions.onclick, menuItems = btnOptions.menuItems, symbol, button, symbolAttr = { stroke: btnOptions.symbolStroke, fill: btnOptions.symbolFill }, symbolSize = btnOptions.symbolSize || 12, menuKey; if (!chart.btnCount) { chart.btnCount = 0; } menuKey = chart.btnCount++; // Keeps references to the button elements if (!chart.exportDivElements) { chart.exportDivElements = []; chart.exportSVGElements = []; } if (btnOptions.enabled === false) { return; } var attr = btnOptions.theme, states = attr.states, hover = states && states.hover, select = states && states.select, callback; delete attr.states; if (onclick) { callback = function () { onclick.apply(chart, arguments); }; } else if (menuItems) { callback = function () { chart.contextMenu( 'contextmenu', menuItems, button.translateX, button.translateY, button.width, button.height, button ); button.setState(2); }; } if (btnOptions.text && btnOptions.symbol) { attr.paddingLeft = Highcharts.pick(attr.paddingLeft, 25); } else if (!btnOptions.text) { extend(attr, { width: btnOptions.width, height: btnOptions.height, padding: 0 }); } button = renderer.button(btnOptions.text, 0, 0, callback, attr, hover, select) .attr({ title: chart.options.lang[btnOptions._titleKey], 'stroke-linecap': 'round' }); if (btnOptions.symbol) { symbol = renderer.symbol( btnOptions.symbol, btnOptions.symbolX - (symbolSize / 2), btnOptions.symbolY - (symbolSize / 2), symbolSize, symbolSize ) .attr(extend(symbolAttr, { 'stroke-width': btnOptions.symbolStrokeWidth || 1, zIndex: 1 })).add(button); } button.add() .align(extend(btnOptions, { width: button.width, x: Highcharts.pick(btnOptions.x, buttonOffset) // #1654 }), true, 'spacingBox'); buttonOffset += (button.width + btnOptions.buttonSpacing) * (btnOptions.align === 'right' ? -1 : 1); chart.exportSVGElements.push(button, symbol); }, /** * Destroy the buttons. */ destroyExport: function (e) { var chart = e.target, i, elem; // Destroy the extra buttons added for (i = 0; i < chart.exportSVGElements.length; i++) { elem = chart.exportSVGElements[i]; // Destroy and null the svg/vml elements if (elem) { // #1822 elem.onclick = elem.ontouchstart = null; chart.exportSVGElements[i] = elem.destroy(); } } // Destroy the divs for the menu for (i = 0; i < chart.exportDivElements.length; i++) { elem = chart.exportDivElements[i]; // Remove the event handler removeEvent(elem, 'mouseleave'); // Remove inline events chart.exportDivElements[i] = elem.onmouseout = elem.onmouseover = elem.ontouchstart = elem.onclick = null; // Destroy the div by moving to garbage bin discardElement(elem); } } }); symbols.menu = function (x, y, width, height) { var arr = [ M, x, y + 2.5, L, x + width, y + 2.5, M, x, y + height / 2 + 0.5, L, x + width, y + height / 2 + 0.5, M, x, y + height - 1.5, L, x + width, y + height - 1.5 ]; return arr; }; // Add the buttons on chart load Chart.prototype.callbacks.push(function (chart) { var n, exportingOptions = chart.options.exporting, buttons = exportingOptions.buttons; buttonOffset = 0; if (exportingOptions.enabled !== false) { for (n in buttons) { chart.addButton(buttons[n]); } // Destroy the export elements at chart destroy addEvent(chart, 'destroy', chart.destroyExport); } }); }(Highcharts));
JavaScript
/** * @license A class to parse color values * @author Stoyan Stefanov <sstoo@gmail.com> * @link http://www.phpied.com/rgb-color-parser-in-javascript/ * Use it if you like it * */ function RGBColor(color_string) { this.ok = false; // strip any leading # if (color_string.charAt(0) == '#') { // remove # if any color_string = color_string.substr(1,6); } color_string = color_string.replace(/ /g,''); color_string = color_string.toLowerCase(); // before getting into regexps, try simple matches // and overwrite the input var simple_colors = { aliceblue: 'f0f8ff', antiquewhite: 'faebd7', aqua: '00ffff', aquamarine: '7fffd4', azure: 'f0ffff', beige: 'f5f5dc', bisque: 'ffe4c4', black: '000000', blanchedalmond: 'ffebcd', blue: '0000ff', 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', darkkhaki: 'bdb76b', darkmagenta: '8b008b', darkolivegreen: '556b2f', darkorange: 'ff8c00', darkorchid: '9932cc', darkred: '8b0000', darksalmon: 'e9967a', darkseagreen: '8fbc8f', darkslateblue: '483d8b', darkslategray: '2f4f4f', darkturquoise: '00ced1', darkviolet: '9400d3', deeppink: 'ff1493', deepskyblue: '00bfff', dimgray: '696969', dodgerblue: '1e90ff', feldspar: 'd19275', firebrick: 'b22222', floralwhite: 'fffaf0', forestgreen: '228b22', fuchsia: 'ff00ff', gainsboro: 'dcdcdc', ghostwhite: 'f8f8ff', gold: 'ffd700', goldenrod: 'daa520', gray: '808080', green: '008000', 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', lightgrey: 'd3d3d3', lightgreen: '90ee90', lightpink: 'ffb6c1', lightsalmon: 'ffa07a', lightseagreen: '20b2aa', lightskyblue: '87cefa', lightslateblue: '8470ff', lightslategray: '778899', lightsteelblue: 'b0c4de', lightyellow: 'ffffe0', lime: '00ff00', limegreen: '32cd32', linen: 'faf0e6', magenta: 'ff00ff', maroon: '800000', mediumaquamarine: '66cdaa', mediumblue: '0000cd', mediumorchid: 'ba55d3', mediumpurple: '9370d8', mediumseagreen: '3cb371', mediumslateblue: '7b68ee', mediumspringgreen: '00fa9a', mediumturquoise: '48d1cc', mediumvioletred: 'c71585', midnightblue: '191970', mintcream: 'f5fffa', mistyrose: 'ffe4e1', moccasin: 'ffe4b5', navajowhite: 'ffdead', navy: '000080', oldlace: 'fdf5e6', olive: '808000', olivedrab: '6b8e23', orange: 'ffa500', orangered: 'ff4500', orchid: 'da70d6', palegoldenrod: 'eee8aa', palegreen: '98fb98', paleturquoise: 'afeeee', palevioletred: 'd87093', papayawhip: 'ffefd5', peachpuff: 'ffdab9', peru: 'cd853f', pink: 'ffc0cb', plum: 'dda0dd', powderblue: 'b0e0e6', purple: '800080', red: 'ff0000', rosybrown: 'bc8f8f', royalblue: '4169e1', saddlebrown: '8b4513', salmon: 'fa8072', sandybrown: 'f4a460', seagreen: '2e8b57', seashell: 'fff5ee', sienna: 'a0522d', silver: 'c0c0c0', skyblue: '87ceeb', slateblue: '6a5acd', slategray: '708090', snow: 'fffafa', springgreen: '00ff7f', steelblue: '4682b4', tan: 'd2b48c', teal: '008080', thistle: 'd8bfd8', tomato: 'ff6347', turquoise: '40e0d0', violet: 'ee82ee', violetred: 'd02090', wheat: 'f5deb3', white: 'ffffff', whitesmoke: 'f5f5f5', yellow: 'ffff00', yellowgreen: '9acd32' }; for (var key in simple_colors) { if (color_string == key) { color_string = simple_colors[key]; } } // emd of simple type-in colors // array of color definition objects var color_defs = [ { re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'], process: function (bits){ return [ parseInt(bits[1]), parseInt(bits[2]), parseInt(bits[3]) ]; } }, { re: /^(\w{2})(\w{2})(\w{2})$/, example: ['#00ff00', '336699'], process: function (bits){ return [ parseInt(bits[1], 16), parseInt(bits[2], 16), parseInt(bits[3], 16) ]; } }, { re: /^(\w{1})(\w{1})(\w{1})$/, example: ['#fb0', 'f0f'], process: function (bits){ return [ parseInt(bits[1] + bits[1], 16), parseInt(bits[2] + bits[2], 16), parseInt(bits[3] + bits[3], 16) ]; } } ]; // search through the definitions to find a match for (var i = 0; i < color_defs.length; i++) { var re = color_defs[i].re; var processor = color_defs[i].process; var bits = re.exec(color_string); if (bits) { channels = processor(bits); this.r = channels[0]; this.g = channels[1]; this.b = channels[2]; this.ok = true; } } // validate/cleanup values this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r); this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g); this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b); // some getters this.toRGB = function () { return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')'; } this.toHex = function () { var r = this.r.toString(16); var g = this.g.toString(16); var b = this.b.toString(16); if (r.length == 1) r = '0' + r; if (g.length == 1) g = '0' + g; if (b.length == 1) b = '0' + b; return '#' + r + g + b; } // help this.getHelpXML = function () { var examples = new Array(); // add regexps for (var i = 0; i < color_defs.length; i++) { var example = color_defs[i].example; for (var j = 0; j < example.length; j++) { examples[examples.length] = example[j]; } } // add type-in colors for (var sc in simple_colors) { examples[examples.length] = sc; } var xml = document.createElement('ul'); xml.setAttribute('id', 'rgbcolor-examples'); for (var i = 0; i < examples.length; i++) { try { var list_item = document.createElement('li'); var list_color = new RGBColor(examples[i]); var example_div = document.createElement('div'); example_div.style.cssText = 'margin: 3px; ' + 'border: 1px solid black; ' + 'background:' + list_color.toHex() + '; ' + 'color:' + list_color.toHex() ; example_div.appendChild(document.createTextNode('test')); var list_item_value = document.createTextNode( ' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex() ); list_item.appendChild(example_div); list_item.appendChild(list_item_value); xml.appendChild(list_item); } catch(e){} } return xml; } } /** * @license canvg.js - Javascript SVG parser and renderer on Canvas * MIT Licensed * Gabe Lerner (gabelerner@gmail.com) * http://code.google.com/p/canvg/ * * Requires: rgbcolor.js - http://www.phpied.com/rgb-color-parser-in-javascript/ * */ if(!window.console) { window.console = {}; window.console.log = function(str) {}; window.console.dir = function(str) {}; } if(!Array.prototype.indexOf){ Array.prototype.indexOf = function(obj){ for(var i=0; i<this.length; i++){ if(this[i]==obj){ return i; } } return -1; } } (function(){ // canvg(target, s) // empty parameters: replace all 'svg' elements on page with 'canvas' elements // target: canvas element or the id of a canvas element // s: svg string, url to svg file, or xml document // opts: optional hash of options // ignoreMouse: true => ignore mouse events // ignoreAnimation: true => ignore animations // ignoreDimensions: true => does not try to resize canvas // ignoreClear: true => does not clear canvas // offsetX: int => draws at a x offset // offsetY: int => draws at a y offset // scaleWidth: int => scales horizontally to width // scaleHeight: int => scales vertically to height // renderCallback: function => will call the function after the first render is completed // forceRedraw: function => will call the function on every frame, if it returns true, will redraw this.canvg = function (target, s, opts) { // no parameters if (target == null && s == null && opts == null) { var svgTags = document.getElementsByTagName('svg'); for (var i=0; i<svgTags.length; i++) { var svgTag = svgTags[i]; var c = document.createElement('canvas'); c.width = svgTag.clientWidth; c.height = svgTag.clientHeight; svgTag.parentNode.insertBefore(c, svgTag); svgTag.parentNode.removeChild(svgTag); var div = document.createElement('div'); div.appendChild(svgTag); canvg(c, div.innerHTML); } return; } opts = opts || {}; if (typeof target == 'string') { target = document.getElementById(target); } // reuse class per canvas var svg; if (target.svg == null) { svg = build(); target.svg = svg; } else { svg = target.svg; svg.stop(); } svg.opts = opts; var ctx = target.getContext('2d'); if (typeof(s.documentElement) != 'undefined') { // load from xml doc svg.loadXmlDoc(ctx, s); } else if (s.substr(0,1) == '<') { // load from xml string svg.loadXml(ctx, s); } else { // load from url svg.load(ctx, s); } } function build() { var svg = { }; svg.FRAMERATE = 30; svg.MAX_VIRTUAL_PIXELS = 30000; // globals svg.init = function(ctx) { svg.Definitions = {}; svg.Styles = {}; svg.Animations = []; svg.Images = []; svg.ctx = ctx; svg.ViewPort = new (function () { this.viewPorts = []; this.Clear = function() { this.viewPorts = []; } this.SetCurrent = function(width, height) { this.viewPorts.push({ width: width, height: height }); } this.RemoveCurrent = function() { this.viewPorts.pop(); } this.Current = function() { return this.viewPorts[this.viewPorts.length - 1]; } this.width = function() { return this.Current().width; } this.height = function() { return this.Current().height; } this.ComputeSize = function(d) { if (d != null && typeof(d) == 'number') return d; if (d == 'x') return this.width(); if (d == 'y') return this.height(); return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2); } }); } svg.init(); // images loaded svg.ImagesLoaded = function() { for (var i=0; i<svg.Images.length; i++) { if (!svg.Images[i].loaded) return false; } return true; } // trim svg.trim = function(s) { return s.replace(/^\s+|\s+$/g, ''); } // compress spaces svg.compressSpaces = function(s) { return s.replace(/[\s\r\t\n]+/gm,' '); } // ajax svg.ajax = function(url) { var AJAX; if(window.XMLHttpRequest){AJAX=new XMLHttpRequest();} else{AJAX=new ActiveXObject('Microsoft.XMLHTTP');} if(AJAX){ AJAX.open('GET',url,false); AJAX.send(null); return AJAX.responseText; } return null; } // parse xml svg.parseXml = function(xml) { if (window.DOMParser) { var parser = new DOMParser(); return parser.parseFromString(xml, 'text/xml'); } else { xml = xml.replace(/<!DOCTYPE svg[^>]*>/, ''); var xmlDoc = new ActiveXObject('Microsoft.XMLDOM'); xmlDoc.async = 'false'; xmlDoc.loadXML(xml); return xmlDoc; } } svg.Property = function(name, value) { this.name = name; this.value = value; this.hasValue = function() { return (this.value != null && this.value !== ''); } // return the numerical value of the property this.numValue = function() { if (!this.hasValue()) return 0; var n = parseFloat(this.value); if ((this.value + '').match(/%$/)) { n = n / 100.0; } return n; } this.valueOrDefault = function(def) { if (this.hasValue()) return this.value; return def; } this.numValueOrDefault = function(def) { if (this.hasValue()) return this.numValue(); return def; } /* EXTENSIONS */ var that = this; // color extensions this.Color = { // augment the current color value with the opacity addOpacity: function(opacity) { var newValue = that.value; if (opacity != null && opacity != '') { var color = new RGBColor(that.value); if (color.ok) { newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacity + ')'; } } return new svg.Property(that.name, newValue); } } // definition extensions this.Definition = { // get the definition from the definitions table getDefinition: function() { var name = that.value.replace(/^(url\()?#([^\)]+)\)?$/, '$2'); return svg.Definitions[name]; }, isUrl: function() { return that.value.indexOf('url(') == 0 }, getFillStyle: function(e) { var def = this.getDefinition(); // gradient if (def != null && def.createGradient) { return def.createGradient(svg.ctx, e); } // pattern if (def != null && def.createPattern) { return def.createPattern(svg.ctx, e); } return null; } } // length extensions this.Length = { DPI: function(viewPort) { return 96.0; // TODO: compute? }, EM: function(viewPort) { var em = 12; var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); if (fontSize.hasValue()) em = fontSize.Length.toPixels(viewPort); return em; }, // get the length as pixels toPixels: function(viewPort) { if (!that.hasValue()) return 0; var s = that.value+''; if (s.match(/em$/)) return that.numValue() * this.EM(viewPort); if (s.match(/ex$/)) return that.numValue() * this.EM(viewPort) / 2.0; if (s.match(/px$/)) return that.numValue(); if (s.match(/pt$/)) return that.numValue() * 1.25; if (s.match(/pc$/)) return that.numValue() * 15; if (s.match(/cm$/)) return that.numValue() * this.DPI(viewPort) / 2.54; if (s.match(/mm$/)) return that.numValue() * this.DPI(viewPort) / 25.4; if (s.match(/in$/)) return that.numValue() * this.DPI(viewPort); if (s.match(/%$/)) return that.numValue() * svg.ViewPort.ComputeSize(viewPort); return that.numValue(); } } // time extensions this.Time = { // get the time as milliseconds toMilliseconds: function() { if (!that.hasValue()) return 0; var s = that.value+''; if (s.match(/s$/)) return that.numValue() * 1000; if (s.match(/ms$/)) return that.numValue(); return that.numValue(); } } // angle extensions this.Angle = { // get the angle as radians toRadians: function() { if (!that.hasValue()) return 0; var s = that.value+''; if (s.match(/deg$/)) return that.numValue() * (Math.PI / 180.0); if (s.match(/grad$/)) return that.numValue() * (Math.PI / 200.0); if (s.match(/rad$/)) return that.numValue(); return that.numValue() * (Math.PI / 180.0); } } } // fonts svg.Font = new (function() { this.Styles = ['normal','italic','oblique','inherit']; this.Variants = ['normal','small-caps','inherit']; this.Weights = ['normal','bold','bolder','lighter','100','200','300','400','500','600','700','800','900','inherit']; this.CreateFont = function(fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) { var f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font); return { fontFamily: fontFamily || f.fontFamily, fontSize: fontSize || f.fontSize, fontStyle: fontStyle || f.fontStyle, fontWeight: fontWeight || f.fontWeight, fontVariant: fontVariant || f.fontVariant, toString: function () { return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' ') } } } var that = this; this.Parse = function(s) { var f = {}; var d = svg.trim(svg.compressSpaces(s || '')).split(' '); var set = { fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false } var ff = ''; for (var i=0; i<d.length; i++) { if (!set.fontStyle && that.Styles.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontStyle = d[i]; set.fontStyle = true; } else if (!set.fontVariant && that.Variants.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontVariant = d[i]; set.fontStyle = set.fontVariant = true; } else if (!set.fontWeight && that.Weights.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontWeight = d[i]; set.fontStyle = set.fontVariant = set.fontWeight = true; } else if (!set.fontSize) { if (d[i] != 'inherit') f.fontSize = d[i].split('/')[0]; set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; } else { if (d[i] != 'inherit') ff += d[i]; } } if (ff != '') f.fontFamily = ff; return f; } }); // points and paths svg.ToNumberArray = function(s) { var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' '); for (var i=0; i<a.length; i++) { a[i] = parseFloat(a[i]); } return a; } svg.Point = function(x, y) { this.x = x; this.y = y; this.angleTo = function(p) { return Math.atan2(p.y - this.y, p.x - this.x); } this.applyTransform = function(v) { var xp = this.x * v[0] + this.y * v[2] + v[4]; var yp = this.x * v[1] + this.y * v[3] + v[5]; this.x = xp; this.y = yp; } } svg.CreatePoint = function(s) { var a = svg.ToNumberArray(s); return new svg.Point(a[0], a[1]); } svg.CreatePath = function(s) { var a = svg.ToNumberArray(s); var path = []; for (var i=0; i<a.length; i+=2) { path.push(new svg.Point(a[i], a[i+1])); } return path; } // bounding box svg.BoundingBox = function(x1, y1, x2, y2) { // pass in initial points if you want this.x1 = Number.NaN; this.y1 = Number.NaN; this.x2 = Number.NaN; this.y2 = Number.NaN; this.x = function() { return this.x1; } this.y = function() { return this.y1; } this.width = function() { return this.x2 - this.x1; } this.height = function() { return this.y2 - this.y1; } this.addPoint = function(x, y) { if (x != null) { if (isNaN(this.x1) || isNaN(this.x2)) { this.x1 = x; this.x2 = x; } if (x < this.x1) this.x1 = x; if (x > this.x2) this.x2 = x; } if (y != null) { if (isNaN(this.y1) || isNaN(this.y2)) { this.y1 = y; this.y2 = y; } if (y < this.y1) this.y1 = y; if (y > this.y2) this.y2 = y; } } this.addX = function(x) { this.addPoint(x, null); } this.addY = function(y) { this.addPoint(null, y); } this.addBoundingBox = function(bb) { this.addPoint(bb.x1, bb.y1); this.addPoint(bb.x2, bb.y2); } this.addQuadraticCurve = function(p0x, p0y, p1x, p1y, p2x, p2y) { var cp1x = p0x + 2/3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0) var cp1y = p0y + 2/3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0) var cp2x = cp1x + 1/3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0) var cp2y = cp1y + 1/3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0) this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y); } this.addBezierCurve = function(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) { // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html var p0 = [p0x, p0y], p1 = [p1x, p1y], p2 = [p2x, p2y], p3 = [p3x, p3y]; this.addPoint(p0[0], p0[1]); this.addPoint(p3[0], p3[1]); for (i=0; i<=1; i++) { var f = function(t) { return Math.pow(1-t, 3) * p0[i] + 3 * Math.pow(1-t, 2) * t * p1[i] + 3 * (1-t) * Math.pow(t, 2) * p2[i] + Math.pow(t, 3) * p3[i]; } var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; var c = 3 * p1[i] - 3 * p0[i]; if (a == 0) { if (b == 0) continue; var t = -c / b; if (0 < t && t < 1) { if (i == 0) this.addX(f(t)); if (i == 1) this.addY(f(t)); } continue; } var b2ac = Math.pow(b, 2) - 4 * c * a; if (b2ac < 0) continue; var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); if (0 < t1 && t1 < 1) { if (i == 0) this.addX(f(t1)); if (i == 1) this.addY(f(t1)); } var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); if (0 < t2 && t2 < 1) { if (i == 0) this.addX(f(t2)); if (i == 1) this.addY(f(t2)); } } } this.isPointInBox = function(x, y) { return (this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2); } this.addPoint(x1, y1); this.addPoint(x2, y2); } // transforms svg.Transform = function(v) { var that = this; this.Type = {} // translate this.Type.translate = function(s) { this.p = svg.CreatePoint(s); this.apply = function(ctx) { ctx.translate(this.p.x || 0.0, this.p.y || 0.0); } this.applyToPoint = function(p) { p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); } } // rotate this.Type.rotate = function(s) { var a = svg.ToNumberArray(s); this.angle = new svg.Property('angle', a[0]); this.cx = a[1] || 0; this.cy = a[2] || 0; this.apply = function(ctx) { ctx.translate(this.cx, this.cy); ctx.rotate(this.angle.Angle.toRadians()); ctx.translate(-this.cx, -this.cy); } this.applyToPoint = function(p) { var a = this.angle.Angle.toRadians(); p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]); p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]); } } this.Type.scale = function(s) { this.p = svg.CreatePoint(s); this.apply = function(ctx) { ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0); } this.applyToPoint = function(p) { p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]); } } this.Type.matrix = function(s) { this.m = svg.ToNumberArray(s); this.apply = function(ctx) { ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]); } this.applyToPoint = function(p) { p.applyTransform(this.m); } } this.Type.SkewBase = function(s) { this.base = that.Type.matrix; this.base(s); this.angle = new svg.Property('angle', s); } this.Type.SkewBase.prototype = new this.Type.matrix; this.Type.skewX = function(s) { this.base = that.Type.SkewBase; this.base(s); this.m = [1, 0, Math.tan(this.angle.Angle.toRadians()), 1, 0, 0]; } this.Type.skewX.prototype = new this.Type.SkewBase; this.Type.skewY = function(s) { this.base = that.Type.SkewBase; this.base(s); this.m = [1, Math.tan(this.angle.Angle.toRadians()), 0, 1, 0, 0]; } this.Type.skewY.prototype = new this.Type.SkewBase; this.transforms = []; this.apply = function(ctx) { for (var i=0; i<this.transforms.length; i++) { this.transforms[i].apply(ctx); } } this.applyToPoint = function(p) { for (var i=0; i<this.transforms.length; i++) { this.transforms[i].applyToPoint(p); } } var data = svg.trim(svg.compressSpaces(v)).split(/\s(?=[a-z])/); for (var i=0; i<data.length; i++) { var type = data[i].split('(')[0]; var s = data[i].split('(')[1].replace(')',''); var transform = new this.Type[type](s); this.transforms.push(transform); } } // aspect ratio svg.AspectRatio = function(ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) { // aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute aspectRatio = svg.compressSpaces(aspectRatio); aspectRatio = aspectRatio.replace(/^defer\s/,''); // ignore defer var align = aspectRatio.split(' ')[0] || 'xMidYMid'; var meetOrSlice = aspectRatio.split(' ')[1] || 'meet'; // calculate scale var scaleX = width / desiredWidth; var scaleY = height / desiredHeight; var scaleMin = Math.min(scaleX, scaleY); var scaleMax = Math.max(scaleX, scaleY); if (meetOrSlice == 'meet') { desiredWidth *= scaleMin; desiredHeight *= scaleMin; } if (meetOrSlice == 'slice') { desiredWidth *= scaleMax; desiredHeight *= scaleMax; } refX = new svg.Property('refX', refX); refY = new svg.Property('refY', refY); if (refX.hasValue() && refY.hasValue()) { ctx.translate(-scaleMin * refX.Length.toPixels('x'), -scaleMin * refY.Length.toPixels('y')); } else { // align if (align.match(/^xMid/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0); if (align.match(/YMid$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0); if (align.match(/^xMax/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width - desiredWidth, 0); if (align.match(/YMax$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height - desiredHeight); } // scale if (align == 'none') ctx.scale(scaleX, scaleY); else if (meetOrSlice == 'meet') ctx.scale(scaleMin, scaleMin); else if (meetOrSlice == 'slice') ctx.scale(scaleMax, scaleMax); // translate ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY); } // elements svg.Element = {} svg.Element.ElementBase = function(node) { this.attributes = {}; this.styles = {}; this.children = []; // get or create attribute this.attribute = function(name, createIfNotExists) { var a = this.attributes[name]; if (a != null) return a; a = new svg.Property(name, ''); if (createIfNotExists == true) this.attributes[name] = a; return a; } // get or create style, crawls up node tree this.style = function(name, createIfNotExists) { var s = this.styles[name]; if (s != null) return s; var a = this.attribute(name); if (a != null && a.hasValue()) { return a; } var p = this.parent; if (p != null) { var ps = p.style(name); if (ps != null && ps.hasValue()) { return ps; } } s = new svg.Property(name, ''); if (createIfNotExists == true) this.styles[name] = s; return s; } // base render this.render = function(ctx) { // don't render display=none if (this.style('display').value == 'none') return; // don't render visibility=hidden if (this.attribute('visibility').value == 'hidden') return; ctx.save(); this.setContext(ctx); // mask if (this.attribute('mask').hasValue()) { var mask = this.attribute('mask').Definition.getDefinition(); if (mask != null) mask.apply(ctx, this); } else if (this.style('filter').hasValue()) { var filter = this.style('filter').Definition.getDefinition(); if (filter != null) filter.apply(ctx, this); } else this.renderChildren(ctx); this.clearContext(ctx); ctx.restore(); } // base set context this.setContext = function(ctx) { // OVERRIDE ME! } // base clear context this.clearContext = function(ctx) { // OVERRIDE ME! } // base render children this.renderChildren = function(ctx) { for (var i=0; i<this.children.length; i++) { this.children[i].render(ctx); } } this.addChild = function(childNode, create) { var child = childNode; if (create) child = svg.CreateElement(childNode); child.parent = this; this.children.push(child); } if (node != null && node.nodeType == 1) { //ELEMENT_NODE // add children for (var i=0; i<node.childNodes.length; i++) { var childNode = node.childNodes[i]; if (childNode.nodeType == 1) this.addChild(childNode, true); //ELEMENT_NODE } // add attributes for (var i=0; i<node.attributes.length; i++) { var attribute = node.attributes[i]; this.attributes[attribute.nodeName] = new svg.Property(attribute.nodeName, attribute.nodeValue); } // add tag styles var styles = svg.Styles[node.nodeName]; if (styles != null) { for (var name in styles) { this.styles[name] = styles[name]; } } // add class styles if (this.attribute('class').hasValue()) { var classes = svg.compressSpaces(this.attribute('class').value).split(' '); for (var j=0; j<classes.length; j++) { styles = svg.Styles['.'+classes[j]]; if (styles != null) { for (var name in styles) { this.styles[name] = styles[name]; } } styles = svg.Styles[node.nodeName+'.'+classes[j]]; if (styles != null) { for (var name in styles) { this.styles[name] = styles[name]; } } } } // add inline styles if (this.attribute('style').hasValue()) { var styles = this.attribute('style').value.split(';'); for (var i=0; i<styles.length; i++) { if (svg.trim(styles[i]) != '') { var style = styles[i].split(':'); var name = svg.trim(style[0]); var value = svg.trim(style[1]); this.styles[name] = new svg.Property(name, value); } } } // add id if (this.attribute('id').hasValue()) { if (svg.Definitions[this.attribute('id').value] == null) { svg.Definitions[this.attribute('id').value] = this; } } } } svg.Element.RenderedElementBase = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.setContext = function(ctx) { // fill if (this.style('fill').Definition.isUrl()) { var fs = this.style('fill').Definition.getFillStyle(this); if (fs != null) ctx.fillStyle = fs; } else if (this.style('fill').hasValue()) { var fillStyle = this.style('fill'); if (this.style('fill-opacity').hasValue()) fillStyle = fillStyle.Color.addOpacity(this.style('fill-opacity').value); ctx.fillStyle = (fillStyle.value == 'none' ? 'rgba(0,0,0,0)' : fillStyle.value); } // stroke if (this.style('stroke').Definition.isUrl()) { var fs = this.style('stroke').Definition.getFillStyle(this); if (fs != null) ctx.strokeStyle = fs; } else if (this.style('stroke').hasValue()) { var strokeStyle = this.style('stroke'); if (this.style('stroke-opacity').hasValue()) strokeStyle = strokeStyle.Color.addOpacity(this.style('stroke-opacity').value); ctx.strokeStyle = (strokeStyle.value == 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value); } if (this.style('stroke-width').hasValue()) ctx.lineWidth = this.style('stroke-width').Length.toPixels(); if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value; if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value; if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value; // font if (typeof(ctx.font) != 'undefined') { ctx.font = svg.Font.CreateFont( this.style('font-style').value, this.style('font-variant').value, this.style('font-weight').value, this.style('font-size').hasValue() ? this.style('font-size').Length.toPixels() + 'px' : '', this.style('font-family').value).toString(); } // transform if (this.attribute('transform').hasValue()) { var transform = new svg.Transform(this.attribute('transform').value); transform.apply(ctx); } // clip if (this.attribute('clip-path').hasValue()) { var clip = this.attribute('clip-path').Definition.getDefinition(); if (clip != null) clip.apply(ctx); } // opacity if (this.style('opacity').hasValue()) { ctx.globalAlpha = this.style('opacity').numValue(); } } } svg.Element.RenderedElementBase.prototype = new svg.Element.ElementBase; svg.Element.PathElementBase = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.path = function(ctx) { if (ctx != null) ctx.beginPath(); return new svg.BoundingBox(); } this.renderChildren = function(ctx) { this.path(ctx); svg.Mouse.checkPath(this, ctx); if (ctx.fillStyle != '') ctx.fill(); if (ctx.strokeStyle != '') ctx.stroke(); var markers = this.getMarkers(); if (markers != null) { if (this.style('marker-start').Definition.isUrl()) { var marker = this.style('marker-start').Definition.getDefinition(); marker.render(ctx, markers[0][0], markers[0][1]); } if (this.style('marker-mid').Definition.isUrl()) { var marker = this.style('marker-mid').Definition.getDefinition(); for (var i=1;i<markers.length-1;i++) { marker.render(ctx, markers[i][0], markers[i][1]); } } if (this.style('marker-end').Definition.isUrl()) { var marker = this.style('marker-end').Definition.getDefinition(); marker.render(ctx, markers[markers.length-1][0], markers[markers.length-1][1]); } } } this.getBoundingBox = function() { return this.path(); } this.getMarkers = function() { return null; } } svg.Element.PathElementBase.prototype = new svg.Element.RenderedElementBase; // svg element svg.Element.svg = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.baseClearContext = this.clearContext; this.clearContext = function(ctx) { this.baseClearContext(ctx); svg.ViewPort.RemoveCurrent(); } this.baseSetContext = this.setContext; this.setContext = function(ctx) { // initial values ctx.strokeStyle = 'rgba(0,0,0,0)'; ctx.lineCap = 'butt'; ctx.lineJoin = 'miter'; ctx.miterLimit = 4; this.baseSetContext(ctx); // create new view port if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) { ctx.translate(this.attribute('x').Length.toPixels('x'), this.attribute('y').Length.toPixels('y')); } var width = svg.ViewPort.width(); var height = svg.ViewPort.height(); if (typeof(this.root) == 'undefined' && this.attribute('width').hasValue() && this.attribute('height').hasValue()) { width = this.attribute('width').Length.toPixels('x'); height = this.attribute('height').Length.toPixels('y'); var x = 0; var y = 0; if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) { x = -this.attribute('refX').Length.toPixels('x'); y = -this.attribute('refY').Length.toPixels('y'); } ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(width, y); ctx.lineTo(width, height); ctx.lineTo(x, height); ctx.closePath(); ctx.clip(); } svg.ViewPort.SetCurrent(width, height); // viewbox if (this.attribute('viewBox').hasValue()) { var viewBox = svg.ToNumberArray(this.attribute('viewBox').value); var minX = viewBox[0]; var minY = viewBox[1]; width = viewBox[2]; height = viewBox[3]; svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, svg.ViewPort.width(), width, svg.ViewPort.height(), height, minX, minY, this.attribute('refX').value, this.attribute('refY').value); svg.ViewPort.RemoveCurrent(); svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]); } } } svg.Element.svg.prototype = new svg.Element.RenderedElementBase; // rect element svg.Element.rect = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.path = function(ctx) { var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); var width = this.attribute('width').Length.toPixels('x'); var height = this.attribute('height').Length.toPixels('y'); var rx = this.attribute('rx').Length.toPixels('x'); var ry = this.attribute('ry').Length.toPixels('y'); if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx; if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry; if (ctx != null) { ctx.beginPath(); ctx.moveTo(x + rx, y); ctx.lineTo(x + width - rx, y); ctx.quadraticCurveTo(x + width, y, x + width, y + ry) ctx.lineTo(x + width, y + height - ry); ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height) ctx.lineTo(x + rx, y + height); ctx.quadraticCurveTo(x, y + height, x, y + height - ry) ctx.lineTo(x, y + ry); ctx.quadraticCurveTo(x, y, x + rx, y) ctx.closePath(); } return new svg.BoundingBox(x, y, x + width, y + height); } } svg.Element.rect.prototype = new svg.Element.PathElementBase; // circle element svg.Element.circle = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.path = function(ctx) { var cx = this.attribute('cx').Length.toPixels('x'); var cy = this.attribute('cy').Length.toPixels('y'); var r = this.attribute('r').Length.toPixels(); if (ctx != null) { ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2, true); ctx.closePath(); } return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r); } } svg.Element.circle.prototype = new svg.Element.PathElementBase; // ellipse element svg.Element.ellipse = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.path = function(ctx) { var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3); var rx = this.attribute('rx').Length.toPixels('x'); var ry = this.attribute('ry').Length.toPixels('y'); var cx = this.attribute('cx').Length.toPixels('x'); var cy = this.attribute('cy').Length.toPixels('y'); if (ctx != null) { ctx.beginPath(); ctx.moveTo(cx, cy - ry); ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy); ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry); ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy); ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry); ctx.closePath(); } return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry); } } svg.Element.ellipse.prototype = new svg.Element.PathElementBase; // line element svg.Element.line = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.getPoints = function() { return [ new svg.Point(this.attribute('x1').Length.toPixels('x'), this.attribute('y1').Length.toPixels('y')), new svg.Point(this.attribute('x2').Length.toPixels('x'), this.attribute('y2').Length.toPixels('y'))]; } this.path = function(ctx) { var points = this.getPoints(); if (ctx != null) { ctx.beginPath(); ctx.moveTo(points[0].x, points[0].y); ctx.lineTo(points[1].x, points[1].y); } return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y); } this.getMarkers = function() { var points = this.getPoints(); var a = points[0].angleTo(points[1]); return [[points[0], a], [points[1], a]]; } } svg.Element.line.prototype = new svg.Element.PathElementBase; // polyline element svg.Element.polyline = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.points = svg.CreatePath(this.attribute('points').value); this.path = function(ctx) { var bb = new svg.BoundingBox(this.points[0].x, this.points[0].y); if (ctx != null) { ctx.beginPath(); ctx.moveTo(this.points[0].x, this.points[0].y); } for (var i=1; i<this.points.length; i++) { bb.addPoint(this.points[i].x, this.points[i].y); if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y); } return bb; } this.getMarkers = function() { var markers = []; for (var i=0; i<this.points.length - 1; i++) { markers.push([this.points[i], this.points[i].angleTo(this.points[i+1])]); } markers.push([this.points[this.points.length-1], markers[markers.length-1][1]]); return markers; } } svg.Element.polyline.prototype = new svg.Element.PathElementBase; // polygon element svg.Element.polygon = function(node) { this.base = svg.Element.polyline; this.base(node); this.basePath = this.path; this.path = function(ctx) { var bb = this.basePath(ctx); if (ctx != null) { ctx.lineTo(this.points[0].x, this.points[0].y); ctx.closePath(); } return bb; } } svg.Element.polygon.prototype = new svg.Element.polyline; // path element svg.Element.path = function(node) { this.base = svg.Element.PathElementBase; this.base(node); var d = this.attribute('d').value; // TODO: convert to real lexer based on http://www.w3.org/TR/SVG11/paths.html#PathDataBNF d = d.replace(/,/gm,' '); // get rid of all commas d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\s])/gm,'$1 $2'); // separate commands from points d = d.replace(/([^\s])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from points d = d.replace(/([0-9])([+\-])/gm,'$1 $2'); // separate digits when no comma d = d.replace(/(\.[0-9]*)(\.)/gm,'$1 $2'); // separate digits when no comma d = d.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm,'$1 $3 $4 '); // shorthand elliptical arc path syntax d = svg.compressSpaces(d); // compress multiple spaces d = svg.trim(d); this.PathParser = new (function(d) { this.tokens = d.split(' '); this.reset = function() { this.i = -1; this.command = ''; this.previousCommand = ''; this.start = new svg.Point(0, 0); this.control = new svg.Point(0, 0); this.current = new svg.Point(0, 0); this.points = []; this.angles = []; } this.isEnd = function() { return this.i >= this.tokens.length - 1; } this.isCommandOrEnd = function() { if (this.isEnd()) return true; return this.tokens[this.i + 1].match(/^[A-Za-z]$/) != null; } this.isRelativeCommand = function() { return this.command == this.command.toLowerCase(); } this.getToken = function() { this.i = this.i + 1; return this.tokens[this.i]; } this.getScalar = function() { return parseFloat(this.getToken()); } this.nextCommand = function() { this.previousCommand = this.command; this.command = this.getToken(); } this.getPoint = function() { var p = new svg.Point(this.getScalar(), this.getScalar()); return this.makeAbsolute(p); } this.getAsControlPoint = function() { var p = this.getPoint(); this.control = p; return p; } this.getAsCurrentPoint = function() { var p = this.getPoint(); this.current = p; return p; } this.getReflectedControlPoint = function() { if (this.previousCommand.toLowerCase() != 'c' && this.previousCommand.toLowerCase() != 's') { return this.current; } // reflect point var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y); return p; } this.makeAbsolute = function(p) { if (this.isRelativeCommand()) { p.x = this.current.x + p.x; p.y = this.current.y + p.y; } return p; } this.addMarker = function(p, from, priorTo) { // if the last angle isn't filled in because we didn't have this point yet ... if (priorTo != null && this.angles.length > 0 && this.angles[this.angles.length-1] == null) { this.angles[this.angles.length-1] = this.points[this.points.length-1].angleTo(priorTo); } this.addMarkerAngle(p, from == null ? null : from.angleTo(p)); } this.addMarkerAngle = function(p, a) { this.points.push(p); this.angles.push(a); } this.getMarkerPoints = function() { return this.points; } this.getMarkerAngles = function() { for (var i=0; i<this.angles.length; i++) { if (this.angles[i] == null) { for (var j=i+1; j<this.angles.length; j++) { if (this.angles[j] != null) { this.angles[i] = this.angles[j]; break; } } } } return this.angles; } })(d); this.path = function(ctx) { var pp = this.PathParser; pp.reset(); var bb = new svg.BoundingBox(); if (ctx != null) ctx.beginPath(); while (!pp.isEnd()) { pp.nextCommand(); switch (pp.command.toUpperCase()) { case 'M': var p = pp.getAsCurrentPoint(); pp.addMarker(p); bb.addPoint(p.x, p.y); if (ctx != null) ctx.moveTo(p.x, p.y); pp.start = pp.current; while (!pp.isCommandOrEnd()) { var p = pp.getAsCurrentPoint(); pp.addMarker(p, pp.start); bb.addPoint(p.x, p.y); if (ctx != null) ctx.lineTo(p.x, p.y); } break; case 'L': while (!pp.isCommandOrEnd()) { var c = pp.current; var p = pp.getAsCurrentPoint(); pp.addMarker(p, c); bb.addPoint(p.x, p.y); if (ctx != null) ctx.lineTo(p.x, p.y); } break; case 'H': while (!pp.isCommandOrEnd()) { var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y); pp.addMarker(newP, pp.current); pp.current = newP; bb.addPoint(pp.current.x, pp.current.y); if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y); } break; case 'V': while (!pp.isCommandOrEnd()) { var newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar()); pp.addMarker(newP, pp.current); pp.current = newP; bb.addPoint(pp.current.x, pp.current.y); if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y); } break; case 'C': while (!pp.isCommandOrEnd()) { var curr = pp.current; var p1 = pp.getPoint(); var cntrl = pp.getAsControlPoint(); var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl, p1); bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'S': while (!pp.isCommandOrEnd()) { var curr = pp.current; var p1 = pp.getReflectedControlPoint(); var cntrl = pp.getAsControlPoint(); var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl, p1); bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'Q': while (!pp.isCommandOrEnd()) { var curr = pp.current; var cntrl = pp.getAsControlPoint(); var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl, cntrl); bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'T': while (!pp.isCommandOrEnd()) { var curr = pp.current; var cntrl = pp.getReflectedControlPoint(); pp.control = cntrl; var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl, cntrl); bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'A': while (!pp.isCommandOrEnd()) { var curr = pp.current; var rx = pp.getScalar(); var ry = pp.getScalar(); var xAxisRotation = pp.getScalar() * (Math.PI / 180.0); var largeArcFlag = pp.getScalar(); var sweepFlag = pp.getScalar(); var cp = pp.getAsCurrentPoint(); // Conversion from endpoint to center parameterization // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes // x1', y1' var currp = new svg.Point( Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0, -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0 ); // adjust radii var l = Math.pow(currp.x,2)/Math.pow(rx,2)+Math.pow(currp.y,2)/Math.pow(ry,2); if (l > 1) { rx *= Math.sqrt(l); ry *= Math.sqrt(l); } // cx', cy' var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt( ((Math.pow(rx,2)*Math.pow(ry,2))-(Math.pow(rx,2)*Math.pow(currp.y,2))-(Math.pow(ry,2)*Math.pow(currp.x,2))) / (Math.pow(rx,2)*Math.pow(currp.y,2)+Math.pow(ry,2)*Math.pow(currp.x,2)) ); if (isNaN(s)) s = 0; var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx); // cx, cy var centp = new svg.Point( (curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y, (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y ); // vector magnitude var m = function(v) { return Math.sqrt(Math.pow(v[0],2) + Math.pow(v[1],2)); } // ratio between two vectors var r = function(u, v) { return (u[0]*v[0]+u[1]*v[1]) / (m(u)*m(v)) } // angle between two vectors var a = function(u, v) { return (u[0]*v[1] < u[1]*v[0] ? -1 : 1) * Math.acos(r(u,v)); } // initial angle var a1 = a([1,0], [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]); // angle delta var u = [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]; var v = [(-currp.x-cpp.x)/rx,(-currp.y-cpp.y)/ry]; var ad = a(u, v); if (r(u,v) <= -1) ad = Math.PI; if (r(u,v) >= 1) ad = 0; if (sweepFlag == 0 && ad > 0) ad = ad - 2 * Math.PI; if (sweepFlag == 1 && ad < 0) ad = ad + 2 * Math.PI; // for markers var halfWay = new svg.Point( centp.x - rx * Math.cos((a1 + ad) / 2), centp.y - ry * Math.sin((a1 + ad) / 2) ); pp.addMarkerAngle(halfWay, (a1 + ad) / 2 + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2); pp.addMarkerAngle(cp, ad + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2); bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better if (ctx != null) { var r = rx > ry ? rx : ry; var sx = rx > ry ? 1 : rx / ry; var sy = rx > ry ? ry / rx : 1; ctx.translate(centp.x, centp.y); ctx.rotate(xAxisRotation); ctx.scale(sx, sy); ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag); ctx.scale(1/sx, 1/sy); ctx.rotate(-xAxisRotation); ctx.translate(-centp.x, -centp.y); } } break; case 'Z': if (ctx != null) ctx.closePath(); pp.current = pp.start; } } return bb; } this.getMarkers = function() { var points = this.PathParser.getMarkerPoints(); var angles = this.PathParser.getMarkerAngles(); var markers = []; for (var i=0; i<points.length; i++) { markers.push([points[i], angles[i]]); } return markers; } } svg.Element.path.prototype = new svg.Element.PathElementBase; // pattern element svg.Element.pattern = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.createPattern = function(ctx, element) { // render me using a temporary svg element var tempSvg = new svg.Element.svg(); tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value); tempSvg.attributes['x'] = new svg.Property('x', this.attribute('x').value); tempSvg.attributes['y'] = new svg.Property('y', this.attribute('y').value); tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value); tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value); tempSvg.children = this.children; var c = document.createElement('canvas'); c.width = this.attribute('width').Length.toPixels('x'); c.height = this.attribute('height').Length.toPixels('y'); tempSvg.render(c.getContext('2d')); return ctx.createPattern(c, 'repeat'); } } svg.Element.pattern.prototype = new svg.Element.ElementBase; // marker element svg.Element.marker = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.baseRender = this.render; this.render = function(ctx, point, angle) { ctx.translate(point.x, point.y); if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(angle); if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth); ctx.save(); // render me using a temporary svg element var tempSvg = new svg.Element.svg(); tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value); tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value); tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value); tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value); tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value); tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black')); tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none')); tempSvg.children = this.children; tempSvg.render(ctx); ctx.restore(); if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(1/ctx.lineWidth, 1/ctx.lineWidth); if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(-angle); ctx.translate(-point.x, -point.y); } } svg.Element.marker.prototype = new svg.Element.ElementBase; // definitions element svg.Element.defs = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.render = function(ctx) { // NOOP } } svg.Element.defs.prototype = new svg.Element.ElementBase; // base for gradients svg.Element.GradientBase = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.gradientUnits = this.attribute('gradientUnits').valueOrDefault('objectBoundingBox'); this.stops = []; for (var i=0; i<this.children.length; i++) { var child = this.children[i]; this.stops.push(child); } this.getGradient = function() { // OVERRIDE ME! } this.createGradient = function(ctx, element) { var stopsContainer = this; if (this.attribute('xlink:href').hasValue()) { stopsContainer = this.attribute('xlink:href').Definition.getDefinition(); } var g = this.getGradient(ctx, element); for (var i=0; i<stopsContainer.stops.length; i++) { g.addColorStop(stopsContainer.stops[i].offset, stopsContainer.stops[i].color); } if (this.attribute('gradientTransform').hasValue()) { // render as transformed pattern on temporary canvas var rootView = svg.ViewPort.viewPorts[0]; var rect = new svg.Element.rect(); rect.attributes['x'] = new svg.Property('x', -svg.MAX_VIRTUAL_PIXELS/3.0); rect.attributes['y'] = new svg.Property('y', -svg.MAX_VIRTUAL_PIXELS/3.0); rect.attributes['width'] = new svg.Property('width', svg.MAX_VIRTUAL_PIXELS); rect.attributes['height'] = new svg.Property('height', svg.MAX_VIRTUAL_PIXELS); var group = new svg.Element.g(); group.attributes['transform'] = new svg.Property('transform', this.attribute('gradientTransform').value); group.children = [ rect ]; var tempSvg = new svg.Element.svg(); tempSvg.attributes['x'] = new svg.Property('x', 0); tempSvg.attributes['y'] = new svg.Property('y', 0); tempSvg.attributes['width'] = new svg.Property('width', rootView.width); tempSvg.attributes['height'] = new svg.Property('height', rootView.height); tempSvg.children = [ group ]; var c = document.createElement('canvas'); c.width = rootView.width; c.height = rootView.height; var tempCtx = c.getContext('2d'); tempCtx.fillStyle = g; tempSvg.render(tempCtx); return tempCtx.createPattern(c, 'no-repeat'); } return g; } } svg.Element.GradientBase.prototype = new svg.Element.ElementBase; // linear gradient element svg.Element.linearGradient = function(node) { this.base = svg.Element.GradientBase; this.base(node); this.getGradient = function(ctx, element) { var bb = element.getBoundingBox(); var x1 = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('x1').numValue() : this.attribute('x1').Length.toPixels('x')); var y1 = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('y1').numValue() : this.attribute('y1').Length.toPixels('y')); var x2 = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('x2').numValue() : this.attribute('x2').Length.toPixels('x')); var y2 = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('y2').numValue() : this.attribute('y2').Length.toPixels('y')); return ctx.createLinearGradient(x1, y1, x2, y2); } } svg.Element.linearGradient.prototype = new svg.Element.GradientBase; // radial gradient element svg.Element.radialGradient = function(node) { this.base = svg.Element.GradientBase; this.base(node); this.getGradient = function(ctx, element) { var bb = element.getBoundingBox(); var cx = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('cx').numValue() : this.attribute('cx').Length.toPixels('x')); var cy = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('cy').numValue() : this.attribute('cy').Length.toPixels('y')); var fx = cx; var fy = cy; if (this.attribute('fx').hasValue()) { fx = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('fx').numValue() : this.attribute('fx').Length.toPixels('x')); } if (this.attribute('fy').hasValue()) { fy = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('fy').numValue() : this.attribute('fy').Length.toPixels('y')); } var r = (this.gradientUnits == 'objectBoundingBox' ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue() : this.attribute('r').Length.toPixels()); return ctx.createRadialGradient(fx, fy, 0, cx, cy, r); } } svg.Element.radialGradient.prototype = new svg.Element.GradientBase; // gradient stop element svg.Element.stop = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.offset = this.attribute('offset').numValue(); var stopColor = this.style('stop-color'); if (this.style('stop-opacity').hasValue()) stopColor = stopColor.Color.addOpacity(this.style('stop-opacity').value); this.color = stopColor.value; } svg.Element.stop.prototype = new svg.Element.ElementBase; // animation base element svg.Element.AnimateBase = function(node) { this.base = svg.Element.ElementBase; this.base(node); svg.Animations.push(this); this.duration = 0.0; this.begin = this.attribute('begin').Time.toMilliseconds(); this.maxDuration = this.begin + this.attribute('dur').Time.toMilliseconds(); this.getProperty = function() { var attributeType = this.attribute('attributeType').value; var attributeName = this.attribute('attributeName').value; if (attributeType == 'CSS') { return this.parent.style(attributeName, true); } return this.parent.attribute(attributeName, true); }; this.initialValue = null; this.removed = false; this.calcValue = function() { // OVERRIDE ME! return ''; } this.update = function(delta) { // set initial value if (this.initialValue == null) { this.initialValue = this.getProperty().value; } // if we're past the end time if (this.duration > this.maxDuration) { // loop for indefinitely repeating animations if (this.attribute('repeatCount').value == 'indefinite') { this.duration = 0.0 } else if (this.attribute('fill').valueOrDefault('remove') == 'remove' && !this.removed) { this.removed = true; this.getProperty().value = this.initialValue; return true; } else { return false; // no updates made } } this.duration = this.duration + delta; // if we're past the begin time var updated = false; if (this.begin < this.duration) { var newValue = this.calcValue(); // tween if (this.attribute('type').hasValue()) { // for transform, etc. var type = this.attribute('type').value; newValue = type + '(' + newValue + ')'; } this.getProperty().value = newValue; updated = true; } return updated; } // fraction of duration we've covered this.progress = function() { return ((this.duration - this.begin) / (this.maxDuration - this.begin)); } } svg.Element.AnimateBase.prototype = new svg.Element.ElementBase; // animate element svg.Element.animate = function(node) { this.base = svg.Element.AnimateBase; this.base(node); this.calcValue = function() { var from = this.attribute('from').numValue(); var to = this.attribute('to').numValue(); // tween value linearly return from + (to - from) * this.progress(); }; } svg.Element.animate.prototype = new svg.Element.AnimateBase; // animate color element svg.Element.animateColor = function(node) { this.base = svg.Element.AnimateBase; this.base(node); this.calcValue = function() { var from = new RGBColor(this.attribute('from').value); var to = new RGBColor(this.attribute('to').value); if (from.ok && to.ok) { // tween color linearly var r = from.r + (to.r - from.r) * this.progress(); var g = from.g + (to.g - from.g) * this.progress(); var b = from.b + (to.b - from.b) * this.progress(); return 'rgb('+parseInt(r,10)+','+parseInt(g,10)+','+parseInt(b,10)+')'; } return this.attribute('from').value; }; } svg.Element.animateColor.prototype = new svg.Element.AnimateBase; // animate transform element svg.Element.animateTransform = function(node) { this.base = svg.Element.animate; this.base(node); } svg.Element.animateTransform.prototype = new svg.Element.animate; // font element svg.Element.font = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.horizAdvX = this.attribute('horiz-adv-x').numValue(); this.isRTL = false; this.isArabic = false; this.fontFace = null; this.missingGlyph = null; this.glyphs = []; for (var i=0; i<this.children.length; i++) { var child = this.children[i]; if (child.type == 'font-face') { this.fontFace = child; if (child.style('font-family').hasValue()) { svg.Definitions[child.style('font-family').value] = this; } } else if (child.type == 'missing-glyph') this.missingGlyph = child; else if (child.type == 'glyph') { if (child.arabicForm != '') { this.isRTL = true; this.isArabic = true; if (typeof(this.glyphs[child.unicode]) == 'undefined') this.glyphs[child.unicode] = []; this.glyphs[child.unicode][child.arabicForm] = child; } else { this.glyphs[child.unicode] = child; } } } } svg.Element.font.prototype = new svg.Element.ElementBase; // font-face element svg.Element.fontface = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.ascent = this.attribute('ascent').value; this.descent = this.attribute('descent').value; this.unitsPerEm = this.attribute('units-per-em').numValue(); } svg.Element.fontface.prototype = new svg.Element.ElementBase; // missing-glyph element svg.Element.missingglyph = function(node) { this.base = svg.Element.path; this.base(node); this.horizAdvX = 0; } svg.Element.missingglyph.prototype = new svg.Element.path; // glyph element svg.Element.glyph = function(node) { this.base = svg.Element.path; this.base(node); this.horizAdvX = this.attribute('horiz-adv-x').numValue(); this.unicode = this.attribute('unicode').value; this.arabicForm = this.attribute('arabic-form').value; } svg.Element.glyph.prototype = new svg.Element.path; // text element svg.Element.text = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); if (node != null) { // add children this.children = []; for (var i=0; i<node.childNodes.length; i++) { var childNode = node.childNodes[i]; if (childNode.nodeType == 1) { // capture tspan and tref nodes this.addChild(childNode, true); } else if (childNode.nodeType == 3) { // capture text this.addChild(new svg.Element.tspan(childNode), false); } } } this.baseSetContext = this.setContext; this.setContext = function(ctx) { this.baseSetContext(ctx); if (this.style('dominant-baseline').hasValue()) ctx.textBaseline = this.style('dominant-baseline').value; if (this.style('alignment-baseline').hasValue()) ctx.textBaseline = this.style('alignment-baseline').value; } this.renderChildren = function(ctx) { var textAnchor = this.style('text-anchor').valueOrDefault('start'); var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); for (var i=0; i<this.children.length; i++) { var child = this.children[i]; if (child.attribute('x').hasValue()) { child.x = child.attribute('x').Length.toPixels('x'); } else { if (child.attribute('dx').hasValue()) x += child.attribute('dx').Length.toPixels('x'); child.x = x; } var childLength = child.measureText(ctx); if (textAnchor != 'start' && (i==0 || child.attribute('x').hasValue())) { // new group? // loop through rest of children var groupLength = childLength; for (var j=i+1; j<this.children.length; j++) { var childInGroup = this.children[j]; if (childInGroup.attribute('x').hasValue()) break; // new group groupLength += childInGroup.measureText(ctx); } child.x -= (textAnchor == 'end' ? groupLength : groupLength / 2.0); } x = child.x + childLength; if (child.attribute('y').hasValue()) { child.y = child.attribute('y').Length.toPixels('y'); } else { if (child.attribute('dy').hasValue()) y += child.attribute('dy').Length.toPixels('y'); child.y = y; } y = child.y; child.render(ctx); } } } svg.Element.text.prototype = new svg.Element.RenderedElementBase; // text base svg.Element.TextElementBase = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.getGlyph = function(font, text, i) { var c = text[i]; var glyph = null; if (font.isArabic) { var arabicForm = 'isolated'; if ((i==0 || text[i-1]==' ') && i<text.length-2 && text[i+1]!=' ') arabicForm = 'terminal'; if (i>0 && text[i-1]!=' ' && i<text.length-2 && text[i+1]!=' ') arabicForm = 'medial'; if (i>0 && text[i-1]!=' ' && (i == text.length-1 || text[i+1]==' ')) arabicForm = 'initial'; if (typeof(font.glyphs[c]) != 'undefined') { glyph = font.glyphs[c][arabicForm]; if (glyph == null && font.glyphs[c].type == 'glyph') glyph = font.glyphs[c]; } } else { glyph = font.glyphs[c]; } if (glyph == null) glyph = font.missingGlyph; return glyph; } this.renderChildren = function(ctx) { var customFont = this.parent.style('font-family').Definition.getDefinition(); if (customFont != null) { var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize); var fontStyle = this.parent.style('font-style').valueOrDefault(svg.Font.Parse(svg.ctx.font).fontStyle); var text = this.getText(); if (customFont.isRTL) text = text.split("").reverse().join(""); var dx = svg.ToNumberArray(this.parent.attribute('dx').value); for (var i=0; i<text.length; i++) { var glyph = this.getGlyph(customFont, text, i); var scale = fontSize / customFont.fontFace.unitsPerEm; ctx.translate(this.x, this.y); ctx.scale(scale, -scale); var lw = ctx.lineWidth; ctx.lineWidth = ctx.lineWidth * customFont.fontFace.unitsPerEm / fontSize; if (fontStyle == 'italic') ctx.transform(1, 0, .4, 1, 0, 0); glyph.render(ctx); if (fontStyle == 'italic') ctx.transform(1, 0, -.4, 1, 0, 0); ctx.lineWidth = lw; ctx.scale(1/scale, -1/scale); ctx.translate(-this.x, -this.y); this.x += fontSize * (glyph.horizAdvX || customFont.horizAdvX) / customFont.fontFace.unitsPerEm; if (typeof(dx[i]) != 'undefined' && !isNaN(dx[i])) { this.x += dx[i]; } } return; } if (ctx.strokeStyle != '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y); if (ctx.fillStyle != '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y); } this.getText = function() { // OVERRIDE ME } this.measureText = function(ctx) { var customFont = this.parent.style('font-family').Definition.getDefinition(); if (customFont != null) { var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize); var measure = 0; var text = this.getText(); if (customFont.isRTL) text = text.split("").reverse().join(""); var dx = svg.ToNumberArray(this.parent.attribute('dx').value); for (var i=0; i<text.length; i++) { var glyph = this.getGlyph(customFont, text, i); measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm; if (typeof(dx[i]) != 'undefined' && !isNaN(dx[i])) { measure += dx[i]; } } return measure; } var textToMeasure = svg.compressSpaces(this.getText()); if (!ctx.measureText) return textToMeasure.length * 10; ctx.save(); this.setContext(ctx); var width = ctx.measureText(textToMeasure).width; ctx.restore(); return width; } } svg.Element.TextElementBase.prototype = new svg.Element.RenderedElementBase; // tspan svg.Element.tspan = function(node) { this.base = svg.Element.TextElementBase; this.base(node); this.text = node.nodeType == 3 ? node.nodeValue : // text node.childNodes.length > 0 ? node.childNodes[0].nodeValue : // element node.text; this.getText = function() { return this.text; } } svg.Element.tspan.prototype = new svg.Element.TextElementBase; // tref svg.Element.tref = function(node) { this.base = svg.Element.TextElementBase; this.base(node); this.getText = function() { var element = this.attribute('xlink:href').Definition.getDefinition(); if (element != null) return element.children[0].getText(); } } svg.Element.tref.prototype = new svg.Element.TextElementBase; // a element svg.Element.a = function(node) { this.base = svg.Element.TextElementBase; this.base(node); this.hasText = true; for (var i=0; i<node.childNodes.length; i++) { if (node.childNodes[i].nodeType != 3) this.hasText = false; } // this might contain text this.text = this.hasText ? node.childNodes[0].nodeValue : ''; this.getText = function() { return this.text; } this.baseRenderChildren = this.renderChildren; this.renderChildren = function(ctx) { if (this.hasText) { // render as text element this.baseRenderChildren(ctx); var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.Length.toPixels('y'), this.x + this.measureText(ctx), this.y)); } else { // render as temporary group var g = new svg.Element.g(); g.children = this.children; g.parent = this; g.render(ctx); } } this.onclick = function() { window.open(this.attribute('xlink:href').value); } this.onmousemove = function() { svg.ctx.canvas.style.cursor = 'pointer'; } } svg.Element.a.prototype = new svg.Element.TextElementBase; // image element svg.Element.image = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); svg.Images.push(this); this.img = document.createElement('img'); this.loaded = false; var that = this; this.img.onload = function() { that.loaded = true; } this.img.src = this.attribute('xlink:href').value; this.renderChildren = function(ctx) { var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); var width = this.attribute('width').Length.toPixels('x'); var height = this.attribute('height').Length.toPixels('y'); if (width == 0 || height == 0) return; ctx.save(); ctx.translate(x, y); svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, width, this.img.width, height, this.img.height, 0, 0); ctx.drawImage(this.img, 0, 0); ctx.restore(); } } svg.Element.image.prototype = new svg.Element.RenderedElementBase; // group element svg.Element.g = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.getBoundingBox = function() { var bb = new svg.BoundingBox(); for (var i=0; i<this.children.length; i++) { bb.addBoundingBox(this.children[i].getBoundingBox()); } return bb; }; } svg.Element.g.prototype = new svg.Element.RenderedElementBase; // symbol element svg.Element.symbol = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.baseSetContext = this.setContext; this.setContext = function(ctx) { this.baseSetContext(ctx); // viewbox if (this.attribute('viewBox').hasValue()) { var viewBox = svg.ToNumberArray(this.attribute('viewBox').value); var minX = viewBox[0]; var minY = viewBox[1]; width = viewBox[2]; height = viewBox[3]; svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, this.attribute('width').Length.toPixels('x'), width, this.attribute('height').Length.toPixels('y'), height, minX, minY); svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]); } } } svg.Element.symbol.prototype = new svg.Element.RenderedElementBase; // style element svg.Element.style = function(node) { this.base = svg.Element.ElementBase; this.base(node); // text, or spaces then CDATA var css = node.childNodes[0].nodeValue + (node.childNodes.length > 1 ? node.childNodes[1].nodeValue : ''); css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(^[\s]*\/\/.*)/gm, ''); // remove comments css = svg.compressSpaces(css); // replace whitespace var cssDefs = css.split('}'); for (var i=0; i<cssDefs.length; i++) { if (svg.trim(cssDefs[i]) != '') { var cssDef = cssDefs[i].split('{'); var cssClasses = cssDef[0].split(','); var cssProps = cssDef[1].split(';'); for (var j=0; j<cssClasses.length; j++) { var cssClass = svg.trim(cssClasses[j]); if (cssClass != '') { var props = {}; for (var k=0; k<cssProps.length; k++) { var prop = cssProps[k].indexOf(':'); var name = cssProps[k].substr(0, prop); var value = cssProps[k].substr(prop + 1, cssProps[k].length - prop); if (name != null && value != null) { props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value)); } } svg.Styles[cssClass] = props; if (cssClass == '@font-face') { var fontFamily = props['font-family'].value.replace(/"/g,''); var srcs = props['src'].value.split(','); for (var s=0; s<srcs.length; s++) { if (srcs[s].indexOf('format("svg")') > 0) { var urlStart = srcs[s].indexOf('url'); var urlEnd = srcs[s].indexOf(')', urlStart); var url = srcs[s].substr(urlStart + 5, urlEnd - urlStart - 6); var doc = svg.parseXml(svg.ajax(url)); var fonts = doc.getElementsByTagName('font'); for (var f=0; f<fonts.length; f++) { var font = svg.CreateElement(fonts[f]); svg.Definitions[fontFamily] = font; } } } } } } } } } svg.Element.style.prototype = new svg.Element.ElementBase; // use element svg.Element.use = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.baseSetContext = this.setContext; this.setContext = function(ctx) { this.baseSetContext(ctx); if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').Length.toPixels('x'), 0); if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').Length.toPixels('y')); } this.getDefinition = function() { var element = this.attribute('xlink:href').Definition.getDefinition(); if (this.attribute('width').hasValue()) element.attribute('width', true).value = this.attribute('width').value; if (this.attribute('height').hasValue()) element.attribute('height', true).value = this.attribute('height').value; return element; } this.path = function(ctx) { var element = this.getDefinition(); if (element != null) element.path(ctx); } this.renderChildren = function(ctx) { var element = this.getDefinition(); if (element != null) element.render(ctx); } } svg.Element.use.prototype = new svg.Element.RenderedElementBase; // mask element svg.Element.mask = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.apply = function(ctx, element) { // render as temp svg var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); var width = this.attribute('width').Length.toPixels('x'); var height = this.attribute('height').Length.toPixels('y'); // temporarily remove mask to avoid recursion var mask = element.attribute('mask').value; element.attribute('mask').value = ''; var cMask = document.createElement('canvas'); cMask.width = x + width; cMask.height = y + height; var maskCtx = cMask.getContext('2d'); this.renderChildren(maskCtx); var c = document.createElement('canvas'); c.width = x + width; c.height = y + height; var tempCtx = c.getContext('2d'); element.render(tempCtx); tempCtx.globalCompositeOperation = 'destination-in'; tempCtx.fillStyle = maskCtx.createPattern(cMask, 'no-repeat'); tempCtx.fillRect(0, 0, x + width, y + height); ctx.fillStyle = tempCtx.createPattern(c, 'no-repeat'); ctx.fillRect(0, 0, x + width, y + height); // reassign mask element.attribute('mask').value = mask; } this.render = function(ctx) { // NO RENDER } } svg.Element.mask.prototype = new svg.Element.ElementBase; // clip element svg.Element.clipPath = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.apply = function(ctx) { for (var i=0; i<this.children.length; i++) { if (this.children[i].path) { this.children[i].path(ctx); ctx.clip(); } } } this.render = function(ctx) { // NO RENDER } } svg.Element.clipPath.prototype = new svg.Element.ElementBase; // filters svg.Element.filter = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.apply = function(ctx, element) { // render as temp svg var bb = element.getBoundingBox(); var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); if (x == 0 || y == 0) { x = bb.x1; y = bb.y1; } var width = this.attribute('width').Length.toPixels('x'); var height = this.attribute('height').Length.toPixels('y'); if (width == 0 || height == 0) { width = bb.width(); height = bb.height(); } // temporarily remove filter to avoid recursion var filter = element.style('filter').value; element.style('filter').value = ''; // max filter distance var extraPercent = .20; var px = extraPercent * width; var py = extraPercent * height; var c = document.createElement('canvas'); c.width = width + 2*px; c.height = height + 2*py; var tempCtx = c.getContext('2d'); tempCtx.translate(-x + px, -y + py); element.render(tempCtx); // apply filters for (var i=0; i<this.children.length; i++) { this.children[i].apply(tempCtx, 0, 0, width + 2*px, height + 2*py); } // render on me ctx.drawImage(c, 0, 0, width + 2*px, height + 2*py, x - px, y - py, width + 2*px, height + 2*py); // reassign filter element.style('filter', true).value = filter; } this.render = function(ctx) { // NO RENDER } } svg.Element.filter.prototype = new svg.Element.ElementBase; svg.Element.feGaussianBlur = function(node) { this.base = svg.Element.ElementBase; this.base(node); function make_fgauss(sigma) { sigma = Math.max(sigma, 0.01); var len = Math.ceil(sigma * 4.0) + 1; mask = []; for (var i = 0; i < len; i++) { mask[i] = Math.exp(-0.5 * (i / sigma) * (i / sigma)); } return mask; } function normalize(mask) { var sum = 0; for (var i = 1; i < mask.length; i++) { sum += Math.abs(mask[i]); } sum = 2 * sum + Math.abs(mask[0]); for (var i = 0; i < mask.length; i++) { mask[i] /= sum; } return mask; } function convolve_even(src, dst, mask, width, height) { for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var a = imGet(src, x, y, width, height, 3)/255; for (var rgba = 0; rgba < 4; rgba++) { var sum = mask[0] * (a==0?255:imGet(src, x, y, width, height, rgba)) * (a==0||rgba==3?1:a); for (var i = 1; i < mask.length; i++) { var a1 = imGet(src, Math.max(x-i,0), y, width, height, 3)/255; var a2 = imGet(src, Math.min(x+i, width-1), y, width, height, 3)/255; sum += mask[i] * ((a1==0?255:imGet(src, Math.max(x-i,0), y, width, height, rgba)) * (a1==0||rgba==3?1:a1) + (a2==0?255:imGet(src, Math.min(x+i, width-1), y, width, height, rgba)) * (a2==0||rgba==3?1:a2)); } imSet(dst, y, x, height, width, rgba, sum); } } } } function imGet(img, x, y, width, height, rgba) { return img[y*width*4 + x*4 + rgba]; } function imSet(img, x, y, width, height, rgba, val) { img[y*width*4 + x*4 + rgba] = val; } function blur(ctx, width, height, sigma) { var srcData = ctx.getImageData(0, 0, width, height); var mask = make_fgauss(sigma); mask = normalize(mask); tmp = []; convolve_even(srcData.data, tmp, mask, width, height); convolve_even(tmp, srcData.data, mask, height, width); ctx.clearRect(0, 0, width, height); ctx.putImageData(srcData, 0, 0); } this.apply = function(ctx, x, y, width, height) { // assuming x==0 && y==0 for now blur(ctx, width, height, this.attribute('stdDeviation').numValue()); } } svg.Element.filter.prototype = new svg.Element.feGaussianBlur; // title element, do nothing svg.Element.title = function(node) { } svg.Element.title.prototype = new svg.Element.ElementBase; // desc element, do nothing svg.Element.desc = function(node) { } svg.Element.desc.prototype = new svg.Element.ElementBase; svg.Element.MISSING = function(node) { console.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.'); } svg.Element.MISSING.prototype = new svg.Element.ElementBase; // element factory svg.CreateElement = function(node) { var className = node.nodeName.replace(/^[^:]+:/,''); // remove namespace className = className.replace(/\-/g,''); // remove dashes var e = null; if (typeof(svg.Element[className]) != 'undefined') { e = new svg.Element[className](node); } else { e = new svg.Element.MISSING(node); } e.type = node.nodeName; return e; } // load from url svg.load = function(ctx, url) { svg.loadXml(ctx, svg.ajax(url)); } // load from xml svg.loadXml = function(ctx, xml) { svg.loadXmlDoc(ctx, svg.parseXml(xml)); } svg.loadXmlDoc = function(ctx, dom) { svg.init(ctx); var mapXY = function(p) { var e = ctx.canvas; while (e) { p.x -= e.offsetLeft; p.y -= e.offsetTop; e = e.offsetParent; } if (window.scrollX) p.x += window.scrollX; if (window.scrollY) p.y += window.scrollY; return p; } // bind mouse if (svg.opts['ignoreMouse'] != true) { ctx.canvas.onclick = function(e) { var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY)); svg.Mouse.onclick(p.x, p.y); }; ctx.canvas.onmousemove = function(e) { var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY)); svg.Mouse.onmousemove(p.x, p.y); }; } var e = svg.CreateElement(dom.documentElement); e.root = true; // render loop var isFirstRender = true; var draw = function() { svg.ViewPort.Clear(); if (ctx.canvas.parentNode) svg.ViewPort.SetCurrent(ctx.canvas.parentNode.clientWidth, ctx.canvas.parentNode.clientHeight); if (svg.opts['ignoreDimensions'] != true) { // set canvas size if (e.style('width').hasValue()) { ctx.canvas.width = e.style('width').Length.toPixels('x'); ctx.canvas.style.width = ctx.canvas.width + 'px'; } if (e.style('height').hasValue()) { ctx.canvas.height = e.style('height').Length.toPixels('y'); ctx.canvas.style.height = ctx.canvas.height + 'px'; } } var cWidth = ctx.canvas.clientWidth || ctx.canvas.width; var cHeight = ctx.canvas.clientHeight || ctx.canvas.height; svg.ViewPort.SetCurrent(cWidth, cHeight); if (svg.opts != null && svg.opts['offsetX'] != null) e.attribute('x', true).value = svg.opts['offsetX']; if (svg.opts != null && svg.opts['offsetY'] != null) e.attribute('y', true).value = svg.opts['offsetY']; if (svg.opts != null && svg.opts['scaleWidth'] != null && svg.opts['scaleHeight'] != null) { var xRatio = 1, yRatio = 1; if (e.attribute('width').hasValue()) xRatio = e.attribute('width').Length.toPixels('x') / svg.opts['scaleWidth']; if (e.attribute('height').hasValue()) yRatio = e.attribute('height').Length.toPixels('y') / svg.opts['scaleHeight']; e.attribute('width', true).value = svg.opts['scaleWidth']; e.attribute('height', true).value = svg.opts['scaleHeight']; e.attribute('viewBox', true).value = '0 0 ' + (cWidth * xRatio) + ' ' + (cHeight * yRatio); e.attribute('preserveAspectRatio', true).value = 'none'; } // clear and render if (svg.opts['ignoreClear'] != true) { ctx.clearRect(0, 0, cWidth, cHeight); } e.render(ctx); if (isFirstRender) { isFirstRender = false; if (svg.opts != null && typeof(svg.opts['renderCallback']) == 'function') svg.opts['renderCallback'](); } } var waitingForImages = true; if (svg.ImagesLoaded()) { waitingForImages = false; draw(); } svg.intervalID = setInterval(function() { var needUpdate = false; if (waitingForImages && svg.ImagesLoaded()) { waitingForImages = false; needUpdate = true; } // need update from mouse events? if (svg.opts['ignoreMouse'] != true) { needUpdate = needUpdate | svg.Mouse.hasEvents(); } // need update from animations? if (svg.opts['ignoreAnimation'] != true) { for (var i=0; i<svg.Animations.length; i++) { needUpdate = needUpdate | svg.Animations[i].update(1000 / svg.FRAMERATE); } } // need update from redraw? if (svg.opts != null && typeof(svg.opts['forceRedraw']) == 'function') { if (svg.opts['forceRedraw']() == true) needUpdate = true; } // render if needed if (needUpdate) { draw(); svg.Mouse.runEvents(); // run and clear our events } }, 1000 / svg.FRAMERATE); } svg.stop = function() { if (svg.intervalID) { clearInterval(svg.intervalID); } } svg.Mouse = new (function() { this.events = []; this.hasEvents = function() { return this.events.length != 0; } this.onclick = function(x, y) { this.events.push({ type: 'onclick', x: x, y: y, run: function(e) { if (e.onclick) e.onclick(); } }); } this.onmousemove = function(x, y) { this.events.push({ type: 'onmousemove', x: x, y: y, run: function(e) { if (e.onmousemove) e.onmousemove(); } }); } this.eventElements = []; this.checkPath = function(element, ctx) { for (var i=0; i<this.events.length; i++) { var e = this.events[i]; if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element; } } this.checkBoundingBox = function(element, bb) { for (var i=0; i<this.events.length; i++) { var e = this.events[i]; if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element; } } this.runEvents = function() { svg.ctx.canvas.style.cursor = ''; for (var i=0; i<this.events.length; i++) { var e = this.events[i]; var element = this.eventElements[i]; while (element) { e.run(element); element = element.parent; } } // done running, clear this.events = []; this.eventElements = []; } }); return svg; } })(); if (CanvasRenderingContext2D) { CanvasRenderingContext2D.prototype.drawSvg = function(s, dx, dy, dw, dh) { canvg(this.canvas, s, { ignoreMouse: true, ignoreAnimation: true, ignoreDimensions: true, ignoreClear: true, offsetX: dx, offsetY: dy, scaleWidth: dw, scaleHeight: dh }); } }/** * @license Highcharts JS v3.0.2 (2013-06-05) * CanVGRenderer Extension module * * (c) 2011-2012 Torstein Hønsi, Erik Olsson * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts */ (function (Highcharts) { // encapsulate var UNDEFINED, DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', VISIBLE = 'visible', PX = 'px', css = Highcharts.css, CanVGRenderer = Highcharts.CanVGRenderer, SVGRenderer = Highcharts.SVGRenderer, extend = Highcharts.extend, merge = Highcharts.merge, addEvent = Highcharts.addEvent, createElement = Highcharts.createElement, discardElement = Highcharts.discardElement; // Extend CanVG renderer on demand, inherit from SVGRenderer extend(CanVGRenderer.prototype, SVGRenderer.prototype); // Add additional functionality: extend(CanVGRenderer.prototype, { create: function (chart, container, chartWidth, chartHeight) { this.setContainer(container, chartWidth, chartHeight); this.configure(chart); }, setContainer: function (container, chartWidth, chartHeight) { var containerStyle = container.style, containerParent = container.parentNode, containerLeft = containerStyle.left, containerTop = containerStyle.top, containerOffsetWidth = container.offsetWidth, containerOffsetHeight = container.offsetHeight, canvas, initialHiddenStyle = { visibility: HIDDEN, position: ABSOLUTE }; this.init.apply(this, [container, chartWidth, chartHeight]); // add the canvas above it canvas = createElement('canvas', { width: containerOffsetWidth, height: containerOffsetHeight }, { position: RELATIVE, left: containerLeft, top: containerTop }, container); this.canvas = canvas; // Create the tooltip line and div, they are placed as siblings to // the container (and as direct childs to the div specified in the html page) this.ttLine = createElement(DIV, null, initialHiddenStyle, containerParent); this.ttDiv = createElement(DIV, null, initialHiddenStyle, containerParent); this.ttTimer = UNDEFINED; // Move away the svg node to a new div inside the container's parent so we can hide it. var hiddenSvg = createElement(DIV, { width: containerOffsetWidth, height: containerOffsetHeight }, { visibility: HIDDEN, left: containerLeft, top: containerTop }, containerParent); this.hiddenSvg = hiddenSvg; hiddenSvg.appendChild(this.box); }, /** * Configures the renderer with the chart. Attach a listener to the event tooltipRefresh. **/ configure: function (chart) { var renderer = this, options = chart.options.tooltip, borderWidth = options.borderWidth, tooltipDiv = renderer.ttDiv, tooltipDivStyle = options.style, tooltipLine = renderer.ttLine, padding = parseInt(tooltipDivStyle.padding, 10); // Add border styling from options to the style tooltipDivStyle = merge(tooltipDivStyle, { padding: padding + PX, 'background-color': options.backgroundColor, 'border-style': 'solid', 'border-width': borderWidth + PX, 'border-radius': options.borderRadius + PX }); // Optionally add shadow if (options.shadow) { tooltipDivStyle = merge(tooltipDivStyle, { 'box-shadow': '1px 1px 3px gray', // w3c '-webkit-box-shadow': '1px 1px 3px gray' // webkit }); } css(tooltipDiv, tooltipDivStyle); // Set simple style on the line css(tooltipLine, { 'border-left': '1px solid darkgray' }); // This event is triggered when a new tooltip should be shown addEvent(chart, 'tooltipRefresh', function (args) { var chartContainer = chart.container, offsetLeft = chartContainer.offsetLeft, offsetTop = chartContainer.offsetTop, position; // Set the content of the tooltip tooltipDiv.innerHTML = args.text; // Compute the best position for the tooltip based on the divs size and container size. position = chart.tooltip.getPosition(tooltipDiv.offsetWidth, tooltipDiv.offsetHeight, {plotX: args.x, plotY: args.y}); css(tooltipDiv, { visibility: VISIBLE, left: position.x + PX, top: position.y + PX, 'border-color': args.borderColor }); // Position the tooltip line css(tooltipLine, { visibility: VISIBLE, left: offsetLeft + args.x + PX, top: offsetTop + chart.plotTop + PX, height: chart.plotHeight + PX }); // This timeout hides the tooltip after 3 seconds // First clear any existing timer if (renderer.ttTimer !== UNDEFINED) { clearTimeout(renderer.ttTimer); } // Start a new timer that hides tooltip and line renderer.ttTimer = setTimeout(function () { css(tooltipDiv, { visibility: HIDDEN }); css(tooltipLine, { visibility: HIDDEN }); }, 3000); }); }, /** * Extend SVGRenderer.destroy to also destroy the elements added by CanVGRenderer. */ destroy: function () { var renderer = this; // Remove the canvas discardElement(renderer.canvas); // Kill the timer if (renderer.ttTimer !== UNDEFINED) { clearTimeout(renderer.ttTimer); } // Remove the divs for tooltip and line discardElement(renderer.ttLine); discardElement(renderer.ttDiv); discardElement(renderer.hiddenSvg); // Continue with base class return SVGRenderer.prototype.destroy.apply(renderer); }, /** * Take a color and return it if it's a string, do not make it a gradient even if it is a * gradient. Currently canvg cannot render gradients (turns out black), * see: http://code.google.com/p/canvg/issues/detail?id=104 * * @param {Object} color The color or config object */ color: function (color, elem, prop) { if (color && color.linearGradient) { // Pick the end color and forward to base implementation color = color.stops[color.stops.length - 1][1]; } return SVGRenderer.prototype.color.call(this, color, elem, prop); }, /** * Draws the SVG on the canvas or adds a draw invokation to the deferred list. */ draw: function () { var renderer = this; window.canvg(renderer.canvas, renderer.hiddenSvg.innerHTML); } }); }(Highcharts));
JavaScript
/** * @license * Highcharts funnel module, Beta * * (c) 2010-2012 Torstein Hønsi * * License: www.highcharts.com/license */ /*global Highcharts */ (function (Highcharts) { 'use strict'; // create shortcuts var defaultOptions = Highcharts.getOptions(), defaultPlotOptions = defaultOptions.plotOptions, seriesTypes = Highcharts.seriesTypes, merge = Highcharts.merge, noop = function () {}, each = Highcharts.each; // set default options defaultPlotOptions.funnel = merge(defaultPlotOptions.pie, { center: ['50%', '50%'], width: '90%', neckWidth: '30%', height: '100%', neckHeight: '25%', dataLabels: { //position: 'right', connectorWidth: 1, connectorColor: '#606060' }, size: true, // to avoid adapting to data label size in Pie.drawDataLabels states: { select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } } }); seriesTypes.funnel = Highcharts.extendClass(seriesTypes.pie, { type: 'funnel', animate: noop, /** * Overrides the pie translate method */ translate: function () { var // Get positions - either an integer or a percentage string must be given getLength = function (length, relativeTo) { return (/%$/).test(length) ? relativeTo * parseInt(length, 10) / 100 : parseInt(length, 10); }, sum = 0, series = this, chart = series.chart, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, cumulative = 0, // start at top options = series.options, center = options.center, centerX = getLength(center[0], plotWidth), centerY = getLength(center[0], plotHeight), width = getLength(options.width, plotWidth), tempWidth, getWidthAt, height = getLength(options.height, plotHeight), neckWidth = getLength(options.neckWidth, plotWidth), neckHeight = getLength(options.neckHeight, plotHeight), neckY = height - neckHeight, data = series.data, path, fraction, half = options.dataLabels.position === 'left' ? 1 : 0, x1, y1, x2, x3, y3, x4, y5; // Return the width at a specific y coordinate series.getWidthAt = getWidthAt = function (y) { return y > height - neckHeight ? neckWidth : neckWidth + (width - neckWidth) * ((height - neckHeight - y) / (height - neckHeight)); }; series.getX = function (y, half) { return centerX + (half ? -1 : 1) * ((getWidthAt(y) / 2) + options.dataLabels.distance); }; // Expose series.center = [centerX, centerY, height]; series.centerX = centerX; /* * Individual point coordinate naming: * * x1,y1 _________________ x2,y1 * \ / * \ / * \ / * \ / * \ / * x3,y3 _________ x4,y3 * * Additional for the base of the neck: * * | | * | | * | | * x3,y5 _________ x4,y5 */ // get the total sum each(data, function (point) { sum += point.y; }); each(data, function (point) { // set start and end positions y5 = null; fraction = sum ? point.y / sum : 0; y1 = cumulative * height; y3 = y1 + fraction * height; //tempWidth = neckWidth + (width - neckWidth) * ((height - neckHeight - y1) / (height - neckHeight)); tempWidth = getWidthAt(y1); x1 = centerX - tempWidth / 2; x2 = x1 + tempWidth; tempWidth = getWidthAt(y3); x3 = centerX - tempWidth / 2; x4 = x3 + tempWidth; // the entire point is within the neck if (y1 > neckY) { x1 = x3 = centerX - neckWidth / 2; x2 = x4 = centerX + neckWidth / 2; // the base of the neck } else if (y3 > neckY) { y5 = y3; tempWidth = getWidthAt(neckY); x3 = centerX - tempWidth / 2; x4 = x3 + tempWidth; y3 = neckY; } // save the path path = [ 'M', x1, y1, 'L', x2, y1, x4, y3 ]; if (y5) { path.push(x4, y5, x3, y5); } path.push(x3, y3, 'Z'); // prepare for using shared dr point.shapeType = 'path'; point.shapeArgs = { d: path }; // for tooltips and data labels point.percentage = fraction * 100; point.plotX = centerX; point.plotY = (y1 + (y5 || y3)) / 2; // Placement of tooltips and data labels point.tooltipPos = [ centerX, point.plotY ]; // Slice is a noop on funnel points point.slice = noop; // Mimicking pie data label placement logic point.half = half; cumulative += fraction; }); series.setTooltipPoints(); }, /** * Draw a single point (wedge) * @param {Object} point The point object * @param {Object} color The color of the point * @param {Number} brightness The brightness relative to the color */ drawPoints: function () { var series = this, options = series.options, chart = series.chart, renderer = chart.renderer; each(series.data, function (point) { var graphic = point.graphic, shapeArgs = point.shapeArgs; if (!graphic) { // Create the shapes point.graphic = renderer.path(shapeArgs). attr({ fill: point.color, stroke: options.borderColor, 'stroke-width': options.borderWidth }). add(series.group); } else { // Update the shapes graphic.animate(shapeArgs); } }); }, /** * Extend the pie data label method */ drawDataLabels: function () { var data = this.data, labelDistance = this.options.dataLabels.distance, leftSide, sign, point, i = data.length, x, y; // In the original pie label anticollision logic, the slots are distributed // from one labelDistance above to one labelDistance below the pie. In funnels // we don't want this. this.center[2] -= 2 * labelDistance; // Set the label position array for each point. while (i--) { point = data[i]; leftSide = point.half; sign = leftSide ? 1 : -1; y = point.plotY; x = this.getX(y, leftSide); // set the anchor point for data labels point.labelPos = [ 0, // first break of connector y, // a/a x + (labelDistance - 5) * sign, // second break, right outside point shape y, // a/a x + labelDistance * sign, // landing point for connector y, // a/a leftSide ? 'right' : 'left', // alignment 0 // center angle ]; } seriesTypes.pie.prototype.drawDataLabels.call(this); } }); }(Highcharts));
JavaScript
/** * @license Data plugin for Highcharts * * (c) 2012-2013 Torstein Hønsi * Last revision 2012-11-27 * * License: www.highcharts.com/license */ /* * The Highcharts Data plugin is a utility to ease parsing of input sources like * CSV, HTML tables or grid views into basic configuration options for use * directly in the Highcharts constructor. * * Demo: http://jsfiddle.net/highcharts/SnLFj/ * * --- OPTIONS --- * * - columns : Array<Array<Mixed>> * A two-dimensional array representing the input data on tabular form. This input can * be used when the data is already parsed, for example from a grid view component. * Each cell can be a string or number. If not switchRowsAndColumns is set, the columns * are interpreted as series. See also the rows option. * * - complete : Function(chartOptions) * The callback that is evaluated when the data is finished loading, optionally from an * external source, and parsed. The first argument passed is a finished chart options * object, containing series and an xAxis with categories if applicable. Thise options * can be extended with additional options and passed directly to the chart constructor. * * - csv : String * A comma delimited string to be parsed. Related options are startRow, endRow, startColumn * and endColumn to delimit what part of the table is used. The lineDelimiter and * itemDelimiter options define the CSV delimiter formats. * * - endColumn : Integer * In tabular input data, the first row (indexed by 0) to use. Defaults to the last * column containing data. * * - endRow : Integer * In tabular input data, the last row (indexed by 0) to use. Defaults to the last row * containing data. * * - googleSpreadsheetKey : String * A Google Spreadsheet key. See https://developers.google.com/gdata/samples/spreadsheet_sample * for general information on GS. * * - googleSpreadsheetWorksheet : String * The Google Spreadsheet worksheet. The available id's can be read from * https://spreadsheets.google.com/feeds/worksheets/{key}/public/basic * * - itemDelimiter : String * Item or cell delimiter for parsing CSV. Defaults to ",". * * - lineDelimiter : String * Line delimiter for parsing CSV. Defaults to "\n". * * - parsed : Function * A callback function to access the parsed columns, the two-dimentional input data * array directly, before they are interpreted into series data and categories. * * - parseDate : Function * A callback function to parse string representations of dates into JavaScript timestamps. * Return an integer on success. * * - rows : Array<Array<Mixed>> * The same as the columns input option, but defining rows intead of columns. * * - startColumn : Integer * In tabular input data, the first column (indexed by 0) to use. * * - startRow : Integer * In tabular input data, the first row (indexed by 0) to use. * * - table : String|HTMLElement * A HTML table or the id of such to be parsed as input data. Related options ara startRow, * endRow, startColumn and endColumn to delimit what part of the table is used. */ // JSLint options: /*global jQuery */ (function (Highcharts) { // Utilities var each = Highcharts.each; // The Data constructor var Data = function (options) { this.init(options); }; // Set the prototype properties Highcharts.extend(Data.prototype, { /** * Initialize the Data object with the given options */ init: function (options) { this.options = options; this.columns = options.columns || this.rowsToColumns(options.rows) || []; // No need to parse or interpret anything if (this.columns.length) { this.dataFound(); // Parse and interpret } else { // Parse a CSV string if options.csv is given this.parseCSV(); // Parse a HTML table if options.table is given this.parseTable(); // Parse a Google Spreadsheet this.parseGoogleSpreadsheet(); } }, dataFound: function () { // Interpret the values into right types this.parseTypes(); // Use first row for series names? this.findHeaderRow(); // Handle columns if a handleColumns callback is given this.parsed(); // Complete if a complete callback is given this.complete(); }, /** * Parse a CSV input string */ parseCSV: function () { var self = this, options = this.options, csv = options.csv, columns = this.columns, startRow = options.startRow || 0, endRow = options.endRow || Number.MAX_VALUE, startColumn = options.startColumn || 0, endColumn = options.endColumn || Number.MAX_VALUE, lines, activeRowNo = 0; if (csv) { lines = csv .replace(/\r\n/g, "\n") // Unix .replace(/\r/g, "\n") // Mac .split(options.lineDelimiter || "\n"); each(lines, function (line, rowNo) { var trimmed = self.trim(line), isComment = trimmed.indexOf('#') === 0, isBlank = trimmed === '', items; if (rowNo >= startRow && rowNo <= endRow && !isComment && !isBlank) { items = line.split(options.itemDelimiter || ','); each(items, function (item, colNo) { if (colNo >= startColumn && colNo <= endColumn) { if (!columns[colNo - startColumn]) { columns[colNo - startColumn] = []; } columns[colNo - startColumn][activeRowNo] = item; } }); activeRowNo += 1; } }); this.dataFound(); } }, /** * Parse a HTML table */ parseTable: function () { var options = this.options, table = options.table, columns = this.columns, startRow = options.startRow || 0, endRow = options.endRow || Number.MAX_VALUE, startColumn = options.startColumn || 0, endColumn = options.endColumn || Number.MAX_VALUE, colNo; if (table) { if (typeof table === 'string') { table = document.getElementById(table); } each(table.getElementsByTagName('tr'), function (tr, rowNo) { colNo = 0; if (rowNo >= startRow && rowNo <= endRow) { each(tr.childNodes, function (item) { if ((item.tagName === 'TD' || item.tagName === 'TH') && colNo >= startColumn && colNo <= endColumn) { if (!columns[colNo]) { columns[colNo] = []; } columns[colNo][rowNo - startRow] = item.innerHTML; colNo += 1; } }); } }); this.dataFound(); // continue } }, /** * TODO: * - switchRowsAndColumns */ parseGoogleSpreadsheet: function () { var self = this, options = this.options, googleSpreadsheetKey = options.googleSpreadsheetKey, columns = this.columns, startRow = options.startRow || 0, endRow = options.endRow || Number.MAX_VALUE, startColumn = options.startColumn || 0, endColumn = options.endColumn || Number.MAX_VALUE, gr, // google row gc; // google column if (googleSpreadsheetKey) { jQuery.getJSON('https://spreadsheets.google.com/feeds/cells/' + googleSpreadsheetKey + '/' + (options.googleSpreadsheetWorksheet || 'od6') + '/public/values?alt=json-in-script&callback=?', function (json) { // Prepare the data from the spreadsheat var cells = json.feed.entry, cell, cellCount = cells.length, colCount = 0, rowCount = 0, i; // First, find the total number of columns and rows that // are actually filled with data for (i = 0; i < cellCount; i++) { cell = cells[i]; colCount = Math.max(colCount, cell.gs$cell.col); rowCount = Math.max(rowCount, cell.gs$cell.row); } // Set up arrays containing the column data for (i = 0; i < colCount; i++) { if (i >= startColumn && i <= endColumn) { // Create new columns with the length of either end-start or rowCount columns[i - startColumn] = []; // Setting the length to avoid jslint warning columns[i - startColumn].length = Math.min(rowCount, endRow - startRow); } } // Loop over the cells and assign the value to the right // place in the column arrays for (i = 0; i < cellCount; i++) { cell = cells[i]; gr = cell.gs$cell.row - 1; // rows start at 1 gc = cell.gs$cell.col - 1; // columns start at 1 // If both row and col falls inside start and end // set the transposed cell value in the newly created columns if (gc >= startColumn && gc <= endColumn && gr >= startRow && gr <= endRow) { columns[gc - startColumn][gr - startRow] = cell.content.$t; } } self.dataFound(); }); } }, /** * Find the header row. For now, we just check whether the first row contains * numbers or strings. Later we could loop down and find the first row with * numbers. */ findHeaderRow: function () { var headerRow = 0; each(this.columns, function (column) { if (typeof column[0] !== 'string') { headerRow = null; } }); this.headerRow = 0; }, /** * Trim a string from whitespace */ trim: function (str) { return typeof str === 'string' ? str.replace(/^\s+|\s+$/g, '') : str; }, /** * Parse numeric cells in to number types and date types in to true dates. * @param {Object} columns */ parseTypes: function () { var columns = this.columns, col = columns.length, row, val, floatVal, trimVal, dateVal; while (col--) { row = columns[col].length; while (row--) { val = columns[col][row]; floatVal = parseFloat(val); trimVal = this.trim(val); /*jslint eqeq: true*/ if (trimVal == floatVal) { // is numeric /*jslint eqeq: false*/ columns[col][row] = floatVal; // If the number is greater than milliseconds in a year, assume datetime if (floatVal > 365 * 24 * 3600 * 1000) { columns[col].isDatetime = true; } else { columns[col].isNumeric = true; } } else { // string, continue to determine if it is a date string or really a string dateVal = this.parseDate(val); if (col === 0 && typeof dateVal === 'number' && !isNaN(dateVal)) { // is date columns[col][row] = dateVal; columns[col].isDatetime = true; } else { // string columns[col][row] = trimVal === '' ? null : trimVal; } } } } }, //* dateFormats: { 'YYYY-mm-dd': { regex: '^([0-9]{4})-([0-9]{2})-([0-9]{2})$', parser: function (match) { return Date.UTC(+match[1], match[2] - 1, +match[3]); } } }, // */ /** * Parse a date and return it as a number. Overridable through options.parseDate. */ parseDate: function (val) { var parseDate = this.options.parseDate, ret, key, format, match; if (parseDate) { ret = parseDate(val); } if (typeof val === 'string') { for (key in this.dateFormats) { format = this.dateFormats[key]; match = val.match(format.regex); if (match) { ret = format.parser(match); } } } return ret; }, /** * Reorganize rows into columns */ rowsToColumns: function (rows) { var row, rowsLength, col, colsLength, columns; if (rows) { columns = []; rowsLength = rows.length; for (row = 0; row < rowsLength; row++) { colsLength = rows[row].length; for (col = 0; col < colsLength; col++) { if (!columns[col]) { columns[col] = []; } columns[col][row] = rows[row][col]; } } } return columns; }, /** * A hook for working directly on the parsed columns */ parsed: function () { if (this.options.parsed) { this.options.parsed.call(this, this.columns); } }, /** * If a complete callback function is provided in the options, interpret the * columns into a Highcharts options object. */ complete: function () { var columns = this.columns, hasXData, categories, firstCol, type, options = this.options, series, data, name, i, j; if (options.complete) { // Use first column for X data or categories? if (columns.length > 1) { firstCol = columns.shift(); if (this.headerRow === 0) { firstCol.shift(); // remove the first cell } // Use the first column for categories or X values hasXData = firstCol.isNumeric || firstCol.isDatetime; if (!hasXData) { // means type is neither datetime nor linear categories = firstCol; } if (firstCol.isDatetime) { type = 'datetime'; } } // Use the next columns for series series = []; for (i = 0; i < columns.length; i++) { if (this.headerRow === 0) { name = columns[i].shift(); } data = []; for (j = 0; j < columns[i].length; j++) { data[j] = columns[i][j] !== undefined ? (hasXData ? [firstCol[j], columns[i][j]] : columns[i][j] ) : null; } series[i] = { name: name, data: data }; } // Do the callback options.complete({ xAxis: { categories: categories, type: type }, series: series }); } } }); // Register the Data prototype and data function on Highcharts Highcharts.Data = Data; Highcharts.data = function (options) { return new Data(options); }; // Extend Chart.init so that the Chart constructor accepts a new configuration // option group, data. Highcharts.wrap(Highcharts.Chart.prototype, 'init', function (proceed, userOptions, callback) { var chart = this; if (userOptions && userOptions.data) { Highcharts.data(Highcharts.extend(userOptions.data, { complete: function (dataOptions) { // Merge series configs if (userOptions.series) { each(userOptions.series, function (series, i) { userOptions.series[i] = Highcharts.merge(series, dataOptions.series[i]); }); } // Do the merge userOptions = Highcharts.merge(dataOptions, userOptions); proceed.call(chart, userOptions, callback); } })); } else { proceed.call(chart, userOptions, callback); } }); }(Highcharts));
JavaScript
(function (Highcharts, HighchartsAdapter) { var UNDEFINED, ALIGN_FACTOR, ALLOWED_SHAPES, Chart = Highcharts.Chart, extend = Highcharts.extend, each = Highcharts.each, defaultOptions; defaultOptions = { xAxis: 0, yAxis: 0, title: { style: {}, text: "", x: 0, y: 0 }, shape: { params: { stroke: "#000000", fill: "transparent", strokeWidth: 2 } } }; ALLOWED_SHAPES = ["path", "rect", "circle"]; ALIGN_FACTOR = { top: 0, left: 0, center: 0.5, middle: 0.5, bottom: 1, right: 1 }; // Highcharts helper methods var inArray = HighchartsAdapter.inArray, merge = Highcharts.merge; function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } function isNumber(n) { return typeof n === 'number'; } function defined(obj) { return obj !== UNDEFINED && obj !== null; } // Define annotation prototype var Annotation = function () { this.init.apply(this, arguments); }; Annotation.prototype = { /* * Initialize the annotation */ init: function (chart, options) { this.chart = chart; this.options = merge({}, defaultOptions, options); }, /* * Render the annotation */ render: function (redraw) { var annotation = this, chart = this.chart, renderer = annotation.chart.renderer, group = annotation.group, title = annotation.title, shape = annotation.shape, options = annotation.options, titleOptions = options.title, shapeOptions = options.shape; if (!group) { group = annotation.group = renderer.g(); } if (!title && titleOptions) { title = annotation.title = renderer.label(titleOptions); title.add(group); } if (!shape && shapeOptions && inArray(shapeOptions.type, ALLOWED_SHAPES) !== -1) { shape = annotation.shape = renderer[options.shape.type](shapeOptions.params); shape.add(group); } group.add(chart.annotations.group); // link annotations to point or series annotation.linkObjects(); if (redraw !== false) { annotation.redraw(); } }, /* * Redraw the annotation title or shape after options update */ redraw: function () { var options = this.options, chart = this.chart, group = this.group, title = this.title, shape = this.shape, linkedTo = this.linkedObject, xAxis = chart.xAxis[options.xAxis], yAxis = chart.yAxis[options.yAxis], width = options.width, height = options.height, anchorY = ALIGN_FACTOR[options.anchorY], anchorX = ALIGN_FACTOR[options.anchorX], resetBBox = false, shapeParams, linkType, series, param, bbox, x, y; if (linkedTo) { linkType = (linkedTo instanceof Highcharts.Point) ? 'point' : (linkedTo instanceof Highcharts.Series) ? 'series' : null; if (linkType === 'point') { options.xValue = linkedTo.x; options.yValue = linkedTo.y; series = linkedTo.series; } else if (linkType === 'series') { series = linkedTo; } if (group.visibility !== series.group.visibility) { group.attr({ visibility: series.group.visibility }); } } // Based on given options find annotation pixel position x = (defined(options.xValue) ? xAxis.toPixels(options.xValue + xAxis.minPointOffset) : options.x) - xAxis.minPixelPadding; y = defined(options.yValue) ? yAxis.toPixels(options.yValue) : options.y; if (isNaN(x) || isNaN(y) || !isNumber(x) || !isNumber(y)) { return; } if (title) { title.attr(options.title); title.css(options.title.style); resetBBox = true; } if (shape) { shapeParams = extend({}, options.shape.params); if (options.units === 'values') { for (param in shapeParams) { if (inArray(param, ['width', 'x']) > -1) { shapeParams[param] = xAxis.translate(shapeParams[param]); } else if (inArray(param, ['height', 'y']) > -1) { shapeParams[param] = yAxis.translate(shapeParams[param]); } } if (shapeParams.width) { shapeParams.width -= xAxis.toPixels(0) - xAxis.left; } if (shapeParams.x) { shapeParams.x += xAxis.minPixelPadding; } } resetBBox = true; shape.attr(shapeParams); } group.bBox = null; // If annotation width or height is not defined in options use bounding box size if (!isNumber(width)) { bbox = group.getBBox(); width = bbox.width; } if (!isNumber(height)) { // get bbox only if it wasn't set before if (!bbox) { bbox = group.getBBox(); } height = bbox.height; } // Calculate anchor point if (!isNumber(anchorX)) { anchorX = ALIGN_FACTOR.center; } if (!isNumber(anchorY)) { anchorY = ALIGN_FACTOR.center; } // Translate group according to its dimension and anchor point x = x - width * anchorX; y = y - height * anchorY; if (chart.animation && defined(group.translateX) && defined(group.translateY)) { group.animate({ translateX: x, translateY: y }); } else { group.translate(x, y); } }, /* * Destroy the annotation */ destroy: function () { var annotation = this, chart = this.chart, allItems = chart.annotations.allItems, index = allItems.indexOf(annotation); if (index > -1) { allItems.splice(index, 1); } each(['title', 'shape', 'group'], function (element) { if (annotation[element]) { annotation[element].destroy(); annotation[element] = null; } }); annotation.group = annotation.title = annotation.shape = annotation.chart = annotation.options = null; }, /* * Update the annotation with a given options */ update: function (options, redraw) { extend(this.options, options); // update link to point or series this.linkObjects(); this.render(redraw); }, linkObjects: function () { var annotation = this, chart = annotation.chart, linkedTo = annotation.linkedObject, linkedId = linkedTo && (linkedTo.id || linkedTo.options.id), options = annotation.options, id = options.linkedTo; if (!defined(id)) { annotation.linkedObject = null; } else if (!defined(linkedTo) || id !== linkedId) { annotation.linkedObject = chart.get(id); } } }; // Add annotations methods to chart prototype extend(Chart.prototype, { annotations: { /* * Unified method for adding annotations to the chart */ add: function (options, redraw) { var annotations = this.allItems, chart = this.chart, item, len; if (!isArray(options)) { options = [options]; } len = options.length; while (len--) { item = new Annotation(chart, options[len]); annotations.push(item); item.render(redraw); } }, /** * Redraw all annotations, method used in chart events */ redraw: function () { each(this.allItems, function (annotation) { annotation.redraw(); }); } } }); // Initialize on chart load Chart.prototype.callbacks.push(function (chart) { var options = chart.options.annotations, group; group = chart.renderer.g("annotations"); group.attr({ zIndex: 7 }); group.add(); // initialize empty array for annotations chart.annotations.allItems = []; // link chart object to annotations chart.annotations.chart = chart; // link annotations group element to the chart chart.annotations.group = group; if (isArray(options) && options.length > 0) { chart.annotations.add(chart.options.annotations); } // update annotations after chart redraw Highcharts.addEvent(chart, 'redraw', function () { chart.annotations.redraw(); }); }); }(Highcharts, HighchartsAdapter));
JavaScript
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highcharts JS v3.0.2 (2013-06-05) * * (c) 2009-2013 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */ (function () { // encapsulated variables var UNDEFINED, doc = document, win = window, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = navigator.userAgent, isOpera = win.opera, isIE = /msie/i.test(userAgent) && !isOpera, docMode8 = doc.documentMode === 8, isWebKit = /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext, Renderer, hasTouch = doc.documentElement.ontouchstart !== UNDEFINED, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function globalAnimation, pathAnim, timeUnits, noop = function () {}, charts = [], PRODUCT = 'Highcharts', VERSION = '3.0.2', // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', /* * Empirical lowest possible opacities for TRACKER_FILL * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')', // invisible but clickable //TRACKER_FILL = 'rgba(192,192,192,0.5)', NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', MILLISECOND = 'millisecond', SECOND = 'second', MINUTE = 'minute', HOUR = 'hour', DAY = 'day', WEEK = 'week', MONTH = 'month', YEAR = 'year', // constants for attributes LINEAR_GRADIENT = 'linearGradient', STOPS = 'stops', STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used makeTime, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}; // The Highcharts namespace win.Highcharts = win.Highcharts ? error(16, true) : {}; /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ function extend(a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; } /** * Deep merge two or more objects and return a third object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ function merge() { var i, len = arguments.length, ret = {}, doCopy = function (copy, original) { var value, key; for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // For each argument, extend the return for (i = 0; i < len; i++) { ret = doCopy(ret, arguments[i]); } return ret; } /** * Take an array and turn into a hash with even number arguments as keys and odd numbers as * values. Allows creating constants for commonly used style properties, attributes etc. * Avoid it in performance critical situations like looping */ function hash() { var i = 0, args = arguments, length = args.length, obj = {}; for (; i < length; i++) { obj[args[i++]] = args[i]; } return obj; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return typeof obj === 'object'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n === 'number'; } function log2lin(num) { return math.log(num) / math.LN10; } function lin2log(num) { return math.pow(10, num); } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. Like MooTools' $.defined. * @param {Object} obj */ function defined(obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, setAttribute = 'setAttribute', ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem[setAttribute](prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem[setAttribute](key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. Like * MooTools' $.splat. */ function splat(obj) { return isArray(obj) ? obj : [obj]; } /** * Return the first value that is defined. Like MooTools' $.pick. */ function pick() { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (typeof arg !== 'undefined' && arg !== null) { return arg; } } } /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isIE) { if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, {padding: 0, border: NONE, margin: 0}); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(parent, members) { var object = function () {}; object.prototype = new parent(); extend(object.prototype, members); return object; } /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ function numberFormat(number, decimals, decPoint, thousandsSep) { var lang = defaultOptions.lang, // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/ n = number, c = decimals === -1 ? ((n || 0).toString().split('.')[1] || '').length : // preserve decimals (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals), d = decPoint === undefined ? lang.decimalPoint : decPoint, t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep, s = n < 0 ? "-" : "", i = String(pInt(n = mathAbs(+n || 0).toFixed(c))), j = i.length > 3 ? i.length % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + mathAbs(n - i).toFixed(c).slice(2) : ""); } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length) { // Create an array of the remaining length +1 and join it with 0's return new Array((length || 2) + 1 - String(number).length).join(0) + number; } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ function wrap(obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return 'Invalid date'; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, // List all format keys. Custom formats can be added from the outside. replacements = extend({ // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, Highcharts.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ function formatSingle(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; val = numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } else { val = dateFormat(format, val); } return val; } /** * Format a string according to a subset of the rules of Python's String.format method. */ function format(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while ((index = str.indexOf(splitter)) !== -1) { segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); } /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, options) { var normalized, i; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (options && options.allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { interval = multiples[i]; if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) { break; } } // multiply back to the correct magnitude interval *= magnitude; return interval; } /** * Get a normalized tick interval for dates. Returns a configuration object with * unit range (interval), count and name. Used to prepare data for getTimeTicks. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs * of segments in stock charts, the normalizing logic was extracted in order to * prevent it for running over again for each segment having the same interval. * #662, #697. */ function normalizeTimeTickInterval(tickInterval, unitsOption) { var units = unitsOption || [[ MILLISECOND, // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ SECOND, [1, 2, 5, 10, 15, 30] ], [ MINUTE, [1, 2, 5, 10, 15, 30] ], [ HOUR, [1, 2, 3, 4, 6, 8, 12] ], [ DAY, [1, 2] ], [ WEEK, [1, 2] ], [ MONTH, [1, 2, 3, 4, 6] ], [ YEAR, null ]], unit = units[units.length - 1], // default unit is years interval = timeUnits[unit[0]], multiples = unit[1], count, i; // loop through the units to find the one that best fits the tickInterval for (i = 0; i < units.length; i++) { unit = units[i]; interval = timeUnits[unit[0]]; multiples = unit[1]; if (units[i + 1]) { // lessThan is in the middle between the highest multiple and the next unit. var lessThan = (interval * multiples[multiples.length - 1] + timeUnits[units[i + 1][0]]) / 2; // break and keep the current unit if (tickInterval <= lessThan) { break; } } } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // get the count count = normalizeTickInterval(tickInterval / interval, multiples); return { unitRange: interval, count: count, unitName: unit[0] }; } /** * Set the tick positions to a time unit that makes sense, for example * on the first of each month or on every Monday. Return an array * with the time positions. Used in datetime axes as well as for grouping * data on a datetime axis. * * @param {Object} normalizedInterval The interval in axis values (ms) and the count * @param {Number} min The minimum in axis values * @param {Number} max The maximum in axis values * @param {Number} startOfWeek */ function getTimeTicks(normalizedInterval, min, max, startOfWeek) { var tickPositions = [], i, higherRanks = {}, useUTC = defaultOptions.global.useUTC, minYear, // used in months and years as a basis for Date.UTC() minDate = new Date(min), interval = normalizedInterval.unitRange, count = normalizedInterval.count; if (defined(min)) { // #1300 if (interval >= timeUnits[SECOND]) { // second minDate.setMilliseconds(0); minDate.setSeconds(interval >= timeUnits[MINUTE] ? 0 : count * mathFloor(minDate.getSeconds() / count)); } if (interval >= timeUnits[MINUTE]) { // minute minDate[setMinutes](interval >= timeUnits[HOUR] ? 0 : count * mathFloor(minDate[getMinutes]() / count)); } if (interval >= timeUnits[HOUR]) { // hour minDate[setHours](interval >= timeUnits[DAY] ? 0 : count * mathFloor(minDate[getHours]() / count)); } if (interval >= timeUnits[DAY]) { // day minDate[setDate](interval >= timeUnits[MONTH] ? 1 : count * mathFloor(minDate[getDate]() / count)); } if (interval >= timeUnits[MONTH]) { // month minDate[setMonth](interval >= timeUnits[YEAR] ? 0 : count * mathFloor(minDate[getMonth]() / count)); minYear = minDate[getFullYear](); } if (interval >= timeUnits[YEAR]) { // year minYear -= minYear % count; minDate[setFullYear](minYear); } // week is a special case that runs outside the hierarchy if (interval === timeUnits[WEEK]) { // get start of current week, independent of count minDate[setDate](minDate[getDate]() - minDate[getDay]() + pick(startOfWeek, 1)); } // get tick positions i = 1; minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), timezoneOffset = useUTC ? 0 : (24 * 3600 * 1000 + minDate.getTimezoneOffset() * 60 * 1000) % (24 * 3600 * 1000); // #950 // iterate and add tick positions at appropriate values while (time < max) { tickPositions.push(time); // if the interval is years, use Date.UTC to increase years if (interval === timeUnits[YEAR]) { time = makeTime(minYear + i * count, 0); // if the interval is months, use Date.UTC to increase months } else if (interval === timeUnits[MONTH]) { time = makeTime(minYear, minMonth + i * count); // if we're using global time, the interval is not fixed as it jumps // one hour at the DST crossover } else if (!useUTC && (interval === timeUnits[DAY] || interval === timeUnits[WEEK])) { time = makeTime(minYear, minMonth, minDateDate + i * count * (interval === timeUnits[DAY] ? 1 : 7)); // else, the interval is fixed and we use simple addition } else { time += interval * count; } i++; } // push the last time tickPositions.push(time); // mark new days if the time is dividible by day (#1649, #1760) each(grep(tickPositions, function (time) { return interval <= timeUnits[HOUR] && time % timeUnits[DAY] === timezoneOffset; }), function (time) { higherRanks[time] = DAY; }); } // record information on the chosen unit - for dynamic label formatter tickPositions.info = extend(normalizedInterval, { higherRanks: higherRanks, totalRange: interval * count }); return tickPositions; } /** * Helper class that contains variuos counters that are local to the chart. */ function ChartCounters() { this.color = 0; this.symbol = 0; } ChartCounters.prototype = { /** * Wraps the color counter if it reaches the specified length. */ wrapColor: function (length) { if (this.color >= length) { this.color = 0; } }, /** * Wraps the symbol counter if it reaches the specified length. */ wrapSymbol: function (length) { if (this.symbol >= length) { this.symbol = 0; } } }; /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].ss_i = i; // stable sort index } arr.sort(function (a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.ss_i - b.ss_i : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].ss_i; // stable sort index } } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMin(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMax(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; } /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ function destroyObjectProperties(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /** * Provide error messages for debugging, with links to online explanation */ function error(code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw msg; } else if (win.console) { console.log(msg); } } /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num) { return parseFloat( num.toPrecision(14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { globalAnimation = pick(animation, chart.animation); } /** * The time unit lookup */ /*jslint white: true*/ timeUnits = hash( MILLISECOND, 1, SECOND, 1000, MINUTE, 60000, HOUR, 3600000, DAY, 24 * 3600000, WEEK, 7 * 24 * 3600000, MONTH, 31 * 24 * 3600000, YEAR, 31556952000 ); /*jslint white: false*/ /** * Path interpolation algorithm used across adapters */ pathAnim = { /** * Prepare start and end values so that the path can be animated one to one */ init: function (elem, fromD, toD) { fromD = fromD || ''; var shift = elem.shift, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, endLength, slice, i, start = fromD.split(' '), end = [].concat(toD), // copy startBaseLine, endBaseLine, sixify = function (arr) { // in splines make move points have six parameters like bezier curves i = arr.length; while (i--) { if (arr[i] === M) { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } }; if (bezier) { sixify(start); sixify(end); } // pull out the base lines before padding if (elem.isArea) { startBaseLine = start.splice(start.length - 6, 6); endBaseLine = end.splice(end.length - 6, 6); } // if shifting points, prepend a dummy point to the end path if (shift <= end.length / numParams) { while (shift--) { end = [].concat(end).splice(0, numParams).concat(end); } } elem.shift = 0; // reset for following animations // copy and append last point until the length matches the end length if (start.length) { endLength = end.length; while (start.length < endLength) { //bezier && sixify(start); slice = [].concat(start).splice(start.length - numParams, numParams); if (bezier) { // disable first control point slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } start = start.concat(slice); } } if (startBaseLine) { // append the base lines for areas start = start.concat(startBaseLine); end = end.concat(endBaseLine); } return [start, end]; }, /** * Interpolate each value of the path and return the array */ step: function (start, end, pos, complete) { var ret = [], i = start.length, startVal; if (pos === 1) { // land on the final path without adjustment points appended in the ends ret = complete; } else if (i === end.length && pos < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : pos * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } return ret; } }; (function ($) { /** * The default HighchartsAdapter for jQuery */ win.HighchartsAdapter = win.HighchartsAdapter || ($ && { /** * Initialize the adapter by applying some extensions to jQuery */ init: function (pathAnim) { // extend the animate function to allow SVG animations var Fx = $.fx, Step = Fx.step, dSetter, Tween = $.Tween, propHooks = Tween && Tween.propHooks, opacityHook = $.cssHooks.opacity; /*jslint unparam: true*//* allow unused param x in this function */ $.extend($.easing, { easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; } }); /*jslint unparam: false*/ // extend some methods to check for elem.attr, which means it is a Highcharts SVG object $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) { var obj = Step, base, elem; // Handle different parent objects if (fn === 'cur') { obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype } else if (fn === '_default' && Tween) { // jQuery 1.8 model obj = propHooks[fn]; fn = 'set'; } // Overwrite the method base = obj[fn]; if (base) { // step.width and step.height don't exist in jQuery < 1.7 // create the extended function replacement obj[fn] = function (fx) { // Fx.prototype.cur does not use fx argument fx = i ? fx : this; // shortcut elem = fx.elem; // Fx.prototype.cur returns the current value. The other ones are setters // and returning a value has no effect. return elem.attr ? // is SVG element wrapper elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method base.apply(this, arguments); // use jQuery's built-in method }; } }); // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+ wrap(opacityHook, 'get', function (proceed, elem, computed) { return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed); }); // Define the setter function for d (path definitions) dSetter = function (fx) { var elem = fx.elem, ends; // Normally start and end should be set in state == 0, but sometimes, // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped // in these cases if (!fx.started) { ends = pathAnim.init(elem, elem.d, elem.toD); fx.start = ends[0]; fx.end = ends[1]; fx.started = true; } // interpolate each value of the path elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD)); }; // jQuery 1.8 style if (Tween) { propHooks.d = { set: dSetter }; // pre 1.8 } else { // animate paths Step.d = dSetter; } /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ this.each = Array.prototype.forEach ? function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); } : function (arr, fn) { // legacy var i = 0, len = arr.length; for (; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; /** * Register Highcharts as a plugin in the respective framework */ $.fn.highcharts = function () { var constr = 'Chart', // default constructor args = arguments, options, ret, chart; if (isString(args[0])) { constr = args[0]; args = Array.prototype.slice.call(args, 1); } options = args[0]; // Create the chart if (options !== UNDEFINED) { /*jslint unused:false*/ options.chart = options.chart || {}; options.chart.renderTo = this[0]; chart = new Highcharts[constr](options, args[1]); ret = this; /*jslint unused:true*/ } // When called without parameters or with the return argument, get a predefined chart if (options === UNDEFINED) { ret = charts[attr(this[0], 'data-highcharts-chart')]; } return ret; }; }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: $.getScript, /** * Return the index of an item in an array, or -1 if not found */ inArray: $.inArray, /** * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method. * @param {Object} elem The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (elem, method) { return $(elem)[method](); }, /** * Filter an array */ grep: $.grep, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { //return jQuery.map(arr, fn); var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }, /** * Get the position of an element relative to the top left of the page */ offset: function (el) { return $(el).offset(); }, /** * Add an event listener * @param {Object} el A HTML element or custom object * @param {String} event The event type * @param {Function} fn The event handler */ addEvent: function (el, event, fn) { $(el).bind(event, fn); }, /** * Remove event added with addEvent * @param {Object} el The object * @param {String} eventType The event type. Leave blank to remove all events. * @param {Function} handler The function to remove */ removeEvent: function (el, eventType, handler) { // workaround for jQuery issue with unbinding custom events: // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2 var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent'; if (doc[func] && el && !el[func]) { el[func] = function () {}; } $(el).unbind(eventType, handler); }, /** * Fire an event on a custom object * @param {Object} el * @param {String} type * @param {Object} eventArguments * @param {Function} defaultFunction */ fireEvent: function (el, type, eventArguments, defaultFunction) { var event = $.Event(type), detachedType = 'detached' + type, defaultPrevented; // Remove warnings in Chrome when accessing layerX and layerY. Although Highcharts // never uses these properties, Chrome includes them in the default click event and // raises the warning when they are copied over in the extend statement below. // // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid // testing if they are there (warning in chrome) the only option is to test if running IE. if (!isIE && eventArguments) { delete eventArguments.layerX; delete eventArguments.layerY; } extend(event, eventArguments); // Prevent jQuery from triggering the object method that is named the // same as the event. For example, if the event is 'select', jQuery // attempts calling el.select and it goes into a loop. if (el[type]) { el[detachedType] = el[type]; el[type] = null; } // Wrap preventDefault and stopPropagation in try/catch blocks in // order to prevent JS errors when cancelling events on non-DOM // objects. #615. /*jslint unparam: true*/ $.each(['preventDefault', 'stopPropagation'], function (i, fn) { var base = event[fn]; event[fn] = function () { try { base.call(event); } catch (e) { if (fn === 'preventDefault') { defaultPrevented = true; } } }; }); /*jslint unparam: false*/ // trigger it $(el).trigger(event); // attach the method if (el[detachedType]) { el[type] = el[detachedType]; el[detachedType] = null; } if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) { defaultFunction(event); } }, /** * Extension method needed for MooTools */ washMouseEvent: function (e) { var ret = e.originalEvent || e; // computed by jQuery, needed by IE8 if (ret.pageX === UNDEFINED) { // #1236 ret.pageX = e.pageX; ret.pageY = e.pageY; } return ret; }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var $el = $(el); if (!el.style) { el.style = {}; // #1881 } if (params.d) { el.toD = params.d; // keep the array form for paths, used in $.fx.step.d params.d = 1; // because in jQuery, animating to an array has a different meaning } $el.stop(); $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { $(el).stop(); } }); }(win.jQuery)); // check for a custom HighchartsAdapter defined prior to this file var globalAdapter = win.HighchartsAdapter, adapter = globalAdapter || {}; // Initialize the adapter if (globalAdapter) { globalAdapter.init.call(globalAdapter, pathAnim); } // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object // and all the utility functions will be null. In that case they are populated by the // default adapters below. var adapterRun = adapter.adapterRun, getScript = adapter.getScript, inArray = adapter.inArray, each = adapter.each, grep = adapter.grep, offset = adapter.offset, map = adapter.map, addEvent = adapter.addEvent, removeEvent = adapter.removeEvent, fireEvent = adapter.fireEvent, washMouseEvent = adapter.washMouseEvent, animate = adapter.animate, stop = adapter.stop; /* **************************************************************************** * Handle the options * *****************************************************************************/ var defaultLabelOptions = { enabled: true, // rotation: 0, align: 'center', x: 0, y: 15, /*formatter: function () { return this.value; },*/ style: { color: '#666', cursor: 'default', fontSize: '11px', lineHeight: '14px' } }; defaultOptions = { colors: ['#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce', '#492970', '#f28f43', '#77a1e5', '#c42525', '#a6c96a'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ',' }, global: { useUTC: true, canvasToolsURL: 'http://code.highcharts.com/3.0.2/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/3.0.2/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 5, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacingTop: 10, spacingRight: 10, spacingBottom: 15, spacingLeft: 10, style: { fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' } }, title: { text: 'Chart title', align: 'center', // floating: false, // margin: 15, // x: 0, // verticalAlign: 'top', y: 15, style: { color: '#274b6d',//#3E576F', fontSize: '16px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', y: 30, style: { color: '#4d759e' } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, lineWidth: 2, //shadow: false, // stacking: null, marker: { enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true //radius: base + 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: merge(defaultLabelOptions, { enabled: false, formatter: function () { return numberFormat(this.y, -1); }, verticalAlign: 'bottom', // above singular point y: 0 // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, // padding: 3, // shadow: false }), cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, showInLegend: true, states: { // states for the entire series hover: { //enabled: false, //lineWidth: base + 1, marker: { // lineWidth: base + 1, // radius: base + 1 } }, select: { marker: {} } }, stickyTracking: true //tooltip: { //pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} // turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, borderWidth: 1, borderColor: '#909090', borderRadius: 5, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 10, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { cursor: 'pointer', color: '#274b6d', fontSize: '12px' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null, style: { fontWeight: 'bold' } } }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '1em' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(255, 255, 255, .85)', borderWidth: 1, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>', shadow: true, //shared: false, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', cursor: 'default', fontSize: '12px', padding: '8px', whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '9px' } } }; // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; // set the default time methods setTimeMethods(); /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var useUTC = defaultOptions.global.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) { return new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Pull out axis options and apply them to the respective default axis options /*defaultXAxisOptions = merge(defaultXAxisOptions, options.xAxis); defaultYAxisOptions = merge(defaultYAxisOptions, options.yAxis); options.xAxis = options.yAxis = UNDEFINED;*/ // Merge in the default options defaultOptions = merge(defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Merely exposing defaultOptions for outside modules * isn't enough because the setOptions method creates a new object. */ function getOptions() { return defaultOptions; } /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ var Color = function (input) { // declare variables var rgba = [], result, stops; /** * Parse the input color to rgba array * @param {String} input */ function init(input) { // Gradients if (input && input.stops) { stops = map(input.stops, function (stop) { return Color(stop[1]); }); // Solid colors } else { // rgba result = /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(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } else { // hex result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(input); if (result) { rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } else { // rgb result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1]; } } } } } /** * Return the color a specified format * @param {String} format */ function get(format) { var ret; if (stops) { ret = merge(input); ret.stops = [].concat(ret.stops); each(stops, function (stop, i) { ret.stops[i] = [ret.stops[i][0], stop.get(format)]; }); // it's NaN if gradient colors on a column chart } else if (rgba && !isNaN(rgba[0])) { if (format === 'rgb') { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; } /** * Brighten the color * @param {Number} alpha */ function brighten(alpha) { if (stops) { each(stops, function (stop) { stop.brighten(alpha); }); } else if (isNumber(alpha) && alpha !== 0) { var i; for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; } /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ function setOpacity(alpha) { rgba[3] = alpha; return this; } // initialize: parse the input init(input); // public methods return { get: get, brighten: brighten, rgba: rgba, setOpacity: setOpacity }; }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; /** * A collection of attribute setters. These methods, if defined, are called right before a certain * attribute is set on an element wrapper. Returning false prevents the default attribute * setter to run. Returning a value causes the default setter to set that value. Used in * Renderer.label. */ wrapper.attrSetters = {}; }, /** * Default base for animation */ opacity: 1, /** * Animate a given attribute * @param {Object} params * @param {Number} options The same options as in jQuery animation * @param {Function} complete Function to perform at the end of animation */ animate: function (params, options, complete) { var animOptions = pick(options, globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { animOptions = merge(animOptions); if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params); if (complete) { complete(); } } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val) { var wrapper = this, key, value, result, i, child, element = wrapper.element, nodeName = element.nodeName.toLowerCase(), // Android2 requires lower for "text" renderer = wrapper.renderer, skipAttr, titleNode, attrSetters = wrapper.attrSetters, shadows = wrapper.shadows, hasSetSymbolSize, doTransform, ret = wrapper; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (isString(hash)) { key = hash; if (nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } else if (key === 'strokeWidth') { key = 'stroke-width'; } ret = attr(element, key) || wrapper[key] || 0; if (key !== 'd' && key !== 'visibility') { // 'd' is string in animation step ret = parseFloat(ret); } // setter } else { for (key in hash) { skipAttr = false; // reset value = hash[key]; // check for a specific attribute setter result = attrSetters[key] && attrSetters[key].call(wrapper, value, key); if (result !== false) { if (result !== UNDEFINED) { value = result; // the attribute setter has returned a new value to set } // paths if (key === 'd') { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } //wrapper.d = value; // shortcut for animations // update child tspans x values } else if (key === 'x' && nodeName === 'text') { for (i = 0; i < element.childNodes.length; i++) { child = element.childNodes[i]; // if the x values are equal, the tspan represents a linebreak if (attr(child, 'x') === attr(element, 'x')) { //child.setAttribute('x', value); attr(child, 'x', value); } } } else if (wrapper.rotation && (key === 'x' || key === 'y')) { doTransform = true; // apply gradients } else if (key === 'fill') { value = renderer.color(value, element, key); // circle x and y } else if (nodeName === 'circle' && (key === 'x' || key === 'y')) { key = { x: 'cx', y: 'cy' }[key] || key; // rectangle border radius } else if (nodeName === 'rect' && key === 'r') { attr(element, { rx: value, ry: value }); skipAttr = true; // translation and text rotation } else if (key === 'translateX' || key === 'translateY' || key === 'rotation' || key === 'verticalAlign' || key === 'scaleX' || key === 'scaleY') { doTransform = true; skipAttr = true; // apply opacity as subnode (required by legacy WebKit and Batik) } else if (key === 'stroke') { value = renderer.color(value, element, key); // emulate VML's dashstyle implementation } else if (key === 'dashstyle') { key = 'stroke-dasharray'; value = value && value.toLowerCase(); if (value === 'solid') { value = NONE; } else if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * hash['stroke-width']; } value = value.join(','); } // IE9/MooTools combo: MooTools returns objects instead of numbers and IE9 Beta 2 // is unable to cast them. Test again with final IE9. } else if (key === 'width') { value = pInt(value); // Text alignment } else if (key === 'align') { key = 'text-anchor'; value = { left: 'start', center: 'middle', right: 'end' }[value]; // Title requires a subnode, #431 } else if (key === 'title') { titleNode = element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); element.appendChild(titleNode); } titleNode.textContent = value; } // jQuery animate changes case if (key === 'strokeWidth') { key = 'stroke-width'; } // In Chrome/Win < 6 as well as Batik, the stroke attribute can't be set when the stroke- // width is 0. #1369 if (key === 'stroke-width' || key === 'stroke') { wrapper[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (wrapper.stroke && wrapper['stroke-width']) { attr(element, 'stroke', wrapper.stroke); attr(element, 'stroke-width', wrapper['stroke-width']); wrapper.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && wrapper.hasStroke) { element.removeAttribute('stroke'); wrapper.hasStroke = false; } skipAttr = true; } // symbols if (wrapper.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { wrapper.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } // let the shadow follow the main element if (shadows && /^(width|height|visibility|x|y|d|transform)$/.test(key)) { i = shadows.length; while (i--) { attr( shadows[i], key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : value ); } } // validate heights if ((key === 'width' || key === 'height') && nodeName === 'rect' && value < 0) { value = 0; } // Record for animation and quick access without polling the DOM wrapper[key] = value; if (key === 'text') { // Delete bBox memo when the text changes if (value !== wrapper.textStr) { delete wrapper.bBox; } wrapper.textStr = value; if (wrapper.added) { renderer.buildText(wrapper); } } else if (!skipAttr) { attr(element, key, value); } } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (doTransform) { wrapper.updateTransform(); } } return ret; }, /** * Add a class name to an element */ addClass: function (className) { attr(this.element, 'class', attr(this.element, 'class') + ' ' + className); return this; }, /* hasClass and removeClass are not (yet) needed hasClass: function (className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function (className) { attr(this.element, 'class', attr(this.element, 'class').replace(className, '')); return this; }, */ /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (strokeWidth, x, y, width, height) { var wrapper = this, key, attribs = {}, values = {}, normalizer; strokeWidth = strokeWidth || wrapper.strokeWidth || (wrapper.attr && wrapper.attr('stroke-width')) || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges values.x = mathFloor(x || wrapper.x || 0) + normalizer; values.y = mathFloor(y || wrapper.y || 0) + normalizer; values.width = mathFloor((width || wrapper.width || 0) - 2 * normalizer); values.height = mathFloor((height || wrapper.height || 0) - 2 * normalizer); values.strokeWidth = strokeWidth; for (key in values) { if (wrapper[key] !== values[key]) { // only set attribute if changed wrapper[key] = attribs[key] = values[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { /*jslint unparam: true*//* allow unused param a in the regexp function below */ var elemWrapper = this, elem = elemWrapper.element, textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text', n, serializedCss = '', hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Merge the new styles with the old ones styles = extend( elemWrapper.styles, styles ); // store object elemWrapper.styles = styles; // Don't handle line wrap on canvas if (useCanVG && textWidth) { delete styles.width; } // serialize and set style attribute if (isIE && !hasSVG) { // legacy IE doesn't support setting style attribute if (textWidth) { delete styles.width; } css(elemWrapper.element, styles); } else { for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } attr(elem, 'style', serializedCss); // #1881 } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // touch if (hasTouch && eventType === 'click') { this.element.ontouchstart = function (e) { e.preventDefault(); handler(); }; } // simplest possible event model for internal use this.element['on' + eventType] = handler; return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { this.element.radialReference = coordinates; return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element, bBox = wrapper.bBox; // faking getBBox in exported SVG in legacy IE if (!bBox) { // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } bBox = wrapper.bBox = { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; } return bBox; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], nonLeft = align && align !== 'left', shadows = wrapper.shadows; // apply translate css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var width, height, rotation = wrapper.rotation, baseline, radians = 0, costheta = 1, sintheta = 0, quad, textWidth = pInt(wrapper.textWidth), xCorr = wrapper.xCorr || 0, yCorr = wrapper.yCorr || 0, currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','), rotationStyle = {}, cssTransformKey; if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed if (defined(rotation)) { if (renderer.isSVG) { // #916 cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; } else { radians = rotation * deg2rad; // deg to rad costheta = mathCos(radians); sintheta = mathSin(radians); // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://highcharts.com/tests/?file=text-rotation rotationStyle.filter = rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE; } css(elem, rotationStyle); } width = pick(wrapper.elemWidth, elem.offsetWidth); height = pick(wrapper.elemHeight, elem.offsetHeight); // update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: 'normal' }); width = textWidth; } // correct x and y baseline = renderer.fontMetrics(elem.style.fontSize).b; xCorr = costheta < 0 && -width; yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(elem, { textAlign: align }); } // record correction wrapper.xCorr = xCorr; wrapper.yCorr = yCorr; } // apply position with correction css(elem, { left: (x + xCorr) + PX, top: (y + yCorr) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { height = elem.offsetHeight; // assigned to height for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, transform; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // Apply translate. Nearly all transformed elements have translation, so instead // of checking for translate = 0, do it always (#1767, #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (wrapper.x || 0) + ' ' + (wrapper.y || 0) + ')'); } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { attr(wrapper.element, 'transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // Vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function () { var wrapper = this, bBox = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation = wrapper.rotation, element = wrapper.element, styles = wrapper.styles, rad = rotation * deg2rad; if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669) if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '22.7') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } wrapper.bBox = bBox; } return bBox; }, /** * Show the element */ show: function () { return this.attr({ visibility: VISIBLE }); }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { elemWrapper.hide(); } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, parentWrapper = parent || renderer, parentNode = parentWrapper.element || renderer.box, childNodes = parentNode.childNodes, element = this.element, zIndex = attr(element, 'zIndex'), otherElement, otherZIndex, i, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // mark the container as having z indexed children if (zIndex) { parentWrapper.handleZ = true; zIndex = pInt(zIndex); } // insert according to this and other elements' zIndex if (parentWrapper.handleZ) { // this element or any of its siblings has a z index for (i = 0; i < childNodes.length; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // insert before the first element with a higher zIndex pInt(otherZIndex) > zIndex || // if no zIndex given, insert before the first element with a zIndex (!defined(zIndex) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; break; } } } // default: append at the end if (!inserted) { parentNode.appendChild(element); } // mark as added this.added = true; // fire an event for internal hooks fireEvent(this, 'add'); return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; } }; /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, forExport) { var renderer = this, loc = location, boxWrapper, desc; boxWrapper = renderer.createElement('svg') .attr({ xmlns: SVG_NS, version: '1.1' }); container.appendChild(boxWrapper.element); // object properties renderer.isSVG = true; renderer.box = boxWrapper.element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? loc.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION)); renderer.defs = this.createElement('defs').add(); renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, lines = pick(wrapper.textStr, '').toString() .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g), childNodes = textNode.childNodes, styleRegex = /style="([^"]+)"/, hrefRegex = /href="([^"]+)"/, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = textStyles && textStyles.width && pInt(textStyles.width), textLineHeight = textStyles && textStyles.lineHeight, i = childNodes.length; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } if (width && !wrapper.added) { this.box.appendChild(textNode); // attach it to the DOM to read offset width } // remove empty line at end if (lines[lines.length - 1] === '') { lines.pop(); } // build the lines each(lines, function (line, lineNo) { var spans, spanNo = 0; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = (span.replace(/<(.|\n)*?>/g, '') || ' ') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>'); // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left attributes.x = parentX; } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', textLineHeight || renderer.fontMetrics( /px$/.test(tspan.style.fontSize) ? tspan.style.fontSize : textStyles.fontSize ).h, // Safari 6.0.2 - too optimized for its own good (#1539) // TODO: revisit this with future versions of Safari isWebKit && tspan.offsetHeight ); } // Append it textNode.appendChild(tspan); spanNo++; // check width and apply soft breaks if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 tooLong, actualWidth, rest = []; while (words.length || rest.length) { delete wrapper.bBox; // delete cache actualWidth = wrapper.getBBox().width; tooLong = actualWidth > width; if (!tooLong || words.length === 1) { // new line needed words = rest; rest = []; if (words.length) { tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: textLineHeight || 16, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } } } }); }); }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState) { var label = this.label(text, x, y, null, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, STYLE = 'style', verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // Normal state - prepare the attributes normalState = merge({ 'stroke-width': 1, stroke: '#CCCCCC', fill: { linearGradient: verticalGradient, stops: [ [0, '#FEFEFE'], [1, '#F6F6F6'] ] }, r: 2, padding: 5, style: { color: 'black' } }, normalState); normalStyle = normalState[STYLE]; delete normalState[STYLE]; // Hover state hoverState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#FFF'], [1, '#ACF'] ] } }, hoverState); hoverStyle = hoverState[STYLE]; delete hoverState[STYLE]; // Pressed state pressedState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#9BD'], [1, '#CDF'] ] } }, pressedState); pressedStyle = pressedState[STYLE]; delete pressedState[STYLE]; // add the events addEvent(label.element, 'mouseenter', function () { label.attr(hoverState) .css(hoverStyle); }); addEvent(label.element, 'mouseleave', function () { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); }); label.setState = function (state) { curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } }; return label .on('click', function () { callback.call(label); }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }; return this.createElement('circle').attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { // arcs are defined as symbols for the ability to set // attributes in attr and animate if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } return this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect').attr({ rx: r, ry: r, fill: NONE }); return wrapper.attr( isObject(x) ? x : // do not crispify when an object is passed in (as in column charts) wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0)) ); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( mathRound(x), mathRound(y), width, height, options ), imageElement, imageRegex = /^url\((.*?)\)$/, imageSrc, imageSize, centerImage; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { // On image load, set the size and position centerImage = function (img, size) { if (img.element) { // it may be destroyed in the meantime (#1390) img.attr({ width: size[0], height: size[1] }); if (!img.alignByTranslate) { // #185 img.translate( mathRound((width - size[0]) / 2), // #1378 mathRound((height - size[1]) / 2) ); } } }; imageSrc = symbol.match(imageRegex)[1]; imageSize = symbolSizes[imageSrc]; // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); obj.isImg = true; if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. // obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). imageElement = createElement('img', { onload: function () { centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); }, src: imageSrc }); } } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function (x, y, w, h) { var cpw = 0.166 * w; return [ M, x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561) innerRadius = options.innerR, open = options.open, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? M : L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; return wrapper; }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object. Prior to Highstock, an array was used to define * a linear gradient with pixel positions relative to the SVG. In newer versions * we change the coordinates to apply relative to the shape, using coordinates * 0-1 within the shape. To preserve backwards compatibility, linearGradient * in this definition is an object of x1, y1, x2 and y2. * * @param {Object} color The color or config object */ color: function (color, elem, prop) { var renderer = this, colorObject, regexRgba = /^rgba/, gradName, gradAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color && color.linearGradient) { gradName = 'linearGradient'; } else if (color && color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { gradAttr = merge(gradAttr, { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2], gradientUnits: 'userSpaceOnUse' }); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].id; } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Return the reference to the gradient object return 'url(' + renderer.url + '#' + id + ')'; // Webkit and Batik can't show rgba. } else if (regexRgba.test(color)) { colorObject = Color(color); attr(elem, prop + '-opacity', colorObject.get('a')); return colorObject.get('rgb'); } else { // Remove the opacity attribute added above. Does not throw if the attribute is not there. elem.removeAttribute(prop + '-opacity'); return color; } }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, defaultChartStyle = defaultOptions.chart.style, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper; if (useHTML && !renderer.forExport) { return renderer.html(str, x, y); } x = mathRound(pick(x, 0)); y = mathRound(pick(y, 0)); wrapper = renderer.createElement('text') .attr({ x: x, y: y, text: str }) .css({ fontFamily: defaultChartStyle.fontFamily, fontSize: defaultChartStyle.fontSize }); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } wrapper.x = x; wrapper.y = y; return wrapper; }, /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var defaultChartStyle = defaultOptions.chart.style, wrapper = this.createElement('span'), attrSetters = wrapper.attrSetters, element = wrapper.element, renderer = wrapper.renderer; // Text setter attrSetters.text = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = value; return false; }; // Various setters which rely on update transform attrSetters.x = attrSetters.y = attrSetters.align = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); return false; }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, whiteSpace: 'nowrap', fontFamily: defaultChartStyle.fontFamily, fontSize: defaultChartStyle.fontSize }); // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (renderer.isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle; // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, { className: attr(parentGroup.element, 'class') }, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup.attrSetters, { translateX: function (value) { htmlGroupStyle.left = value + PX; }, translateY: function (value) { htmlGroupStyle.top = value + PX; }, visibility: function (value, key) { htmlGroupStyle[key] = value; } }); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize) { fontSize = pInt(fontSize || 11); // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2), baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, attrSetters = wrapper.attrSetters, needsBox; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ function updateBoxSize() { var boxX, boxY, style = text.element.style; bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && text.getBBox(); wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize).b; if (needsBox) { // create the border box if it is not already present if (!box) { boxX = mathRound(-alignFactor * padding); boxY = baseline ? -baselineOffset : 0; wrapper.box = box = shape ? renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); box.add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(merge({ width: wrapper.width, height: wrapper.height }, deferredAttr)); } deferredAttr = null; } } /** * This function runs after setting text or padding, but only if padding is changed */ function updateTextPadding() { var styles = wrapper.styles, textAlign = styles && styles.textAlign, x = paddingLeft + padding * (1 - alignFactor), y; // determin y based on the baseline y = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr({ x: x, y: y }); } // record current values text.x = x; text.y = y; } /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ function boxAttr(key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } } function getSizeAfterAdd() { text.add(wrapper); wrapper.attr({ text: str, // alignment is available now x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ addEvent(wrapper, 'add', getSizeAfterAdd); /* * Add specific attribute setters. */ // only change local variables attrSetters.width = function (value) { width = value; return false; }; attrSetters.height = function (value) { height = value; return false; }; attrSetters.padding = function (value) { if (defined(value) && value !== padding) { padding = value; updateTextPadding(); } return false; }; attrSetters.paddingLeft = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } return false; }; // change local variable and set attribue as well attrSetters.align = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; return false; // prevent setting text-anchor on the group }; // apply these to the box and the text alike attrSetters.text = function (value, key) { text.attr(key, value); updateBoxSize(); updateTextPadding(); return false; }; // apply these to the box but not to the text attrSetters[STROKE_WIDTH] = function (value, key) { needsBox = true; crispAdjust = value % 2 / 2; boxAttr(key, value); return false; }; attrSetters.stroke = attrSetters.fill = attrSetters.r = function (value, key) { if (key === 'fill') { needsBox = true; } boxAttr(key, value); return false; }; attrSetters.anchorX = function (value, key) { anchorX = value; boxAttr(key, value + crispAdjust - wrapperX); return false; }; attrSetters.anchorY = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); return false; }; // rename attributes attrSetters.x = function (value) { wrapper.x = value; // for animation getter value -= alignFactor * ((width || bBox.width) + padding); wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); return false; }; attrSetters.y = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); return false; }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration'], function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { removeEvent(wrapper, 'add', getSizeAfterAdd); // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = getSizeAfterAdd = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer, VMLElement; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ Highcharts.VMLElement = VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';'], isDiv = nodeName === DIV; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? HIDDEN : VISIBLE); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; wrapper.attrSetters = {}; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks fireEvent(wrapper, 'add'); return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Get or set attributes */ attr: function (hash, val) { var wrapper = this, key, value, i, result, element = wrapper.element || {}, elemStyle = element.style, nodeName = element.nodeName, renderer = wrapper.renderer, symbolName = wrapper.symbolName, hasSetSymbolSize, shadows = wrapper.shadows, skipAttr, attrSetters = wrapper.attrSetters, ret = wrapper; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter, val is undefined if (isString(hash)) { key = hash; if (key === 'strokeWidth' || key === 'stroke-width') { ret = wrapper.strokeweight; } else { ret = wrapper[key]; } // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; // check for a specific attribute setter result = attrSetters[key] && attrSetters[key].call(wrapper, value, key); if (result !== false && value !== null) { // #620 if (result !== UNDEFINED) { value = result; // the attribute setter has returned a new value to set } // prepare paths // symbols if (symbolName && /^(x|y|r|start|end|width|height|innerR|anchorX|anchorY)/.test(key)) { // if one of the symbol size affecting parameters are changed, // check all the others only once for each call to an element's // .attr() method if (!hasSetSymbolSize) { wrapper.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } else if (key === 'd') { value = value || []; wrapper.d = value.join(' '); // used in getter for animation // convert paths i = value.length; var convertedPath = [], clockwise; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { convertedPath[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path convertedPath[i] = 'x'; } else { convertedPath[i] = value[i]; // When the start X and end X coordinates of an arc are too close, // they are rounded to the same value above. In this case, substract 1 from the end X // position. #760, #1371. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { clockwise = value[i] === 'wa' ? 1 : -1; // #1642 if (convertedPath[i + 5] === convertedPath[i + 7]) { convertedPath[i + 7] -= clockwise; } // Start and end Y (#1410) if (convertedPath[i + 6] === convertedPath[i + 8]) { convertedPath[i + 8] -= clockwise; } } } } value = convertedPath.join(' ') || 'x'; element.path = value; // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } skipAttr = true; // handle visibility } else if (key === 'visibility') { // let the shadow follow the main element if (shadows) { i = shadows.length; while (i--) { shadows[i].style[key] = value; } } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when tucked away // outside the viewport. So the visibility is actually opposite of // the expected value. This applies to the tooltip only. if (!docMode8) { elemStyle[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } elemStyle[key] = value; skipAttr = true; // directly mapped to css } else if (key === 'zIndex') { if (value) { elemStyle[key] = value; } skipAttr = true; // x, y, width, height } else if (inArray(key, ['x', 'y', 'width', 'height']) !== -1) { wrapper[key] = value; // used in getter if (key === 'x' || key === 'y') { key = { x: 'left', y: 'top' }[key]; } else { value = mathMax(0, value); // don't set width or height below zero (#311) } // clipping rectangle special if (wrapper.updateClipping) { wrapper[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' wrapper.updateClipping(); } else { // normal elemStyle[key] = value; } skipAttr = true; // class name } else if (key === 'class' && nodeName === 'DIV') { // IE8 Standards mode has problems retrieving the className element.className = value; // stroke } else if (key === 'stroke') { value = renderer.color(value, element, key); key = 'strokecolor'; // stroke width } else if (key === 'stroke-width' || key === 'strokeWidth') { element.stroked = value ? true : false; key = 'strokeweight'; wrapper[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } // dashStyle } else if (key === 'dashstyle') { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; wrapper.dashstyle = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ skipAttr = true; // fill } else if (key === 'fill') { if (nodeName === 'SPAN') { // text color elemStyle.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE ? true : false; value = renderer.color(value, element, key, wrapper); key = 'fillcolor'; } // opacity: don't bother - animation is too slow and filters introduce artifacts } else if (key === 'opacity') { /*css(element, { opacity: value });*/ skipAttr = true; // rotation on VML elements } else if (nodeName === 'shape' && key === 'rotation') { wrapper[key] = value; // Correction for the 1x1 size of the shape container. Used in gauge needles. element.style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; element.style.top = mathRound(mathCos(value * deg2rad)) + PX; // translation for animation } else if (key === 'translateX' || key === 'translateY' || key === 'rotation') { wrapper[key] = value; wrapper.updateTransform(); skipAttr = true; // text for rotated and non-rotated elements } else if (key === 'text') { this.bBox = null; element.innerHTML = value; skipAttr = true; } if (!skipAttr) { if (docMode8) { // IE8 setAttribute bug element[key] = value; } else { attr(element, key, value); } } } } } return ret; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; } }; VMLElement = extendClass(SVGElement, VMLElement); /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height) { var renderer = this, boxWrapper, box; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV); box = boxWrapper.element; box.style.position = RELATIVE; // for freeform drawing using renderer directly container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // setup default css doc.createStyleSheet().cssText = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], left: isObj ? x.x : x, top: isObj ? x.y : y, width: isObj ? x.width : width, height: isObj ? x.height : height, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && nodeName === 'DIV') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { member.css(clipRect.getCSS(member)); }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right addEvent(wrapper, 'add', applyRadialGradient); } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // if the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>']; createElement(this.prepVML(markup), null, null, elem); ret = colorObject.get('rgb'); } else { var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node if (propNodes.length) { propNodes[0].opacity = 1; propNodes[0].type = 'solid'; } ret = color; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: SVGRenderer.prototype.html, /** * Create and return a path element * @param {Array} path */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function (x, y, r) { var circle = this.symbol('circle'); if (isObject(x)) { r = x.r; y = x.y; x = x.x; } circle.isCircle = true; // Causes x and y to mean center (#1682) return circle.attr({ x: x, y: y, width: 2 * r, height: 2 * r }); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * VML uses a shape for rect to overcome bugs and rotation problems */ rect: function (x, y, width, height, r, strokeWidth) { if (isObject(x)) { y = x.y; width = x.width; height = x.height; strokeWidth = x.strokeWidth; x = x.x; } var wrapper = this.symbol('rect'); wrapper.r = r; return wrapper.attr(wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var parentStyle = parentNode.style; css(element, { flip: 'x', left: pInt(parentStyle.width) - 1, top: pInt(parentStyle.height) - 1, rotation: -90 }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x,// - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h, wrapper) { // Center correction, #1682 if (wrapper && wrapper.isCircle) { x -= w / 2; y -= h / 2; } // Return the path return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape * * @param {Number} left Left position * @param {Number} top Top position * @param {Number} r Border radius * @param {Object} options Width and height */ rect: function (left, top, width, height, options) { var right = left + width, bottom = top + height, ret, r; // No radius, return the more lightweight square if (!defined(options) || !options.r) { ret = SVGRenderer.prototype.symbols.square.apply(0, arguments); // Has radius add arcs for the corners } else { r = mathMin(options.r, width, height); ret = [ M, left + r, top, L, right - r, top, 'wa', right - 2 * r, top, right, top + 2 * r, right - r, top, right, top + r, L, right, bottom - r, 'wa', right - 2 * r, bottom - 2 * r, right, bottom, right, bottom - r, right - r, bottom, L, left + r, bottom, 'wa', left, bottom - 2 * r, left + 2 * r, bottom, left + r, bottom, left, bottom - r, L, left, top + r, 'wa', left, top, left + 2 * r, top + 2 * r, left, top + r, left + r, top, 'x', 'e' ]; } return ret; } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ Highcharts.CanVGRenderer = CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); Renderer = CanVGRenderer; } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * The Tick class */ function Tick(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, horiz = axis.horiz, categories = axis.categories, names = axis.series[0] && axis.series[0].names, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, width = (horiz && categories && !labelOptions.step && !labelOptions.staggerLines && !labelOptions.rotation && chart.plotWidth / tickPositions.length) || (!horiz && (chart.optionsMarginLeft || chart.plotWidth / 2)), // #1580 isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], css, attr, value = categories ? pick(categories[pos], names && names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(lin2log(value)) : value }); // prepare CSS css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; css = extend(css, labelOptions.style); // first call if (!defined(label)) { attr = { align: labelOptions.align }; if (isNumber(labelOptions.rotation)) { attr.rotation = labelOptions.rotation; } tick.label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) .attr(attr) // without position absolute, IE export sometimes is wrong .css(css) .add(axis.labelGroup) : null; // update } else if (label) { label.attr({ text: str }) .css(css); } }, /** * Get the offset height or width of the label */ getLabelSize: function () { var label = this.label, axis = this.axis; return label ? ((this.labelBBox = label.getBBox()))[axis.horiz ? 'height' : 'width'] : 0; }, /** * Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision * detection with overflow logic. */ getLabelSides: function () { var bBox = this.labelBBox, // assume getLabelSize has run at this point axis = this.axis, options = axis.options, labelOptions = options.labels, width = bBox.width, leftSide = width * { left: 0, center: 0.5, right: 1 }[labelOptions.align] - labelOptions.x; return [-leftSide, width - leftSide]; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (index, xy) { var show = true, axis = this.axis, chart = axis.chart, isFirst = this.isFirst, isLast = this.isLast, x = xy.x, reversed = axis.reversed, tickPositions = axis.tickPositions; if (isFirst || isLast) { var sides = this.getLabelSides(), leftSide = sides[0], rightSide = sides[1], plotLeft = chart.plotLeft, plotRight = plotLeft + axis.len, neighbour = axis.ticks[tickPositions[index + (isFirst ? 1 : -1)]], neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1]; if ((isFirst && !reversed) || (isLast && reversed)) { // Is the label spilling out to the left of the plot area? if (x + leftSide < plotLeft) { // Align it to plot left x = plotLeft - leftSide; // Hide it if it now overlaps the neighbour label if (neighbour && x + rightSide > neighbourEdge) { show = false; } } } else { // Is the label spilling out to the right of the plot area? if (x + rightSide > plotRight) { // Align it to plot right x = plotRight - rightSide; // Hide it if it now overlaps the neighbour label if (neighbour && x + leftSide < neighbourEdge) { show = false; } } } // Set the modified x position of the label xy.x = x; } return show; }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines; x = x + labelOptions.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + labelOptions.y - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Vertically centered if (!defined(labelOptions.y)) { y += pInt(label.styles.lineHeight) * 0.9 - label.getBBox().height / 2; } // Correct for staggered labels if (staggerLines) { y += (index / (step || 1) % staggerLines) * 16; } return { x: x, y: y }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickLength = options[tickPrefix + 'Length'], tickWidth = options[tickPrefix + 'Width'] || 0, tickColor = options[tickPrefix + 'Color'], tickPosition = options[tickPrefix + 'Position'], gridLinePath, mark = tick.mark, markPath, step = labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos) || (!horiz && y === axis.pos + axis.len)) ? -1 : 1, // #1480 staggerLines = axis.staggerLines; this.isActive = true; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickWidth && tickLength) { // negate the length if (tickPosition === 'inside') { tickLength = -tickLength; } if (axis.opposite) { tickLength = -tickLength; } markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath, opacity: opacity }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth, opacity: opacity }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && !isNaN(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // apply show first and show last if ((tick.isFirst && !pick(options.showFirstLabel, 1)) || (tick.isLast && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (!staggerLines && horiz && labelOptions.overflow === 'justify' && !tick.handleOverflow(index, xy)) { show = false; } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && !isNaN(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); tick.isNew = false; } else { label.attr('y', -9999); // #1338 } } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * The object wrapper for plot lines and plot bands * @param {Object} options */ function PlotLineOrBand(axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } } PlotLineOrBand.prototype = { /** * Render the plot line or plot band. If it is already existing, * move it. */ render: function () { var plotLine = this, axis = plotLine.axis, horiz = axis.horiz, halfPointRange = (axis.pointRange || 0) / 2, options = plotLine.options, optionsLabel = options.label, label = plotLine.label, width = options.width, to = options.to, from = options.from, isBand = defined(from) && defined(to), value = options.value, dashStyle = options.dashStyle, svgElem = plotLine.svgElem, path = [], addEvent, eventType, xs, ys, x, y, color = options.color, zIndex = options.zIndex, events = options.events, attribs, renderer = axis.chart.renderer; // logarithmic conversion if (axis.isLog) { from = log2lin(from); to = log2lin(to); value = log2lin(value); } // plot line if (width) { path = axis.getPlotLinePath(value, width); attribs = { stroke: color, 'stroke-width': width }; if (dashStyle) { attribs.dashstyle = dashStyle; } } else if (isBand) { // plot band // keep within plot area from = mathMax(from, axis.min - halfPointRange); to = mathMin(to, axis.max + halfPointRange); path = axis.getPlotBandPath(from, to, options); attribs = { fill: color }; if (options.borderWidth) { attribs.stroke = options.borderColor; attribs['stroke-width'] = options.borderWidth; } } else { return; } // zIndex if (defined(zIndex)) { attribs.zIndex = zIndex; } // common for lines and bands if (svgElem) { if (path) { svgElem.animate({ d: path }, null, svgElem.onGetPath); } else { svgElem.hide(); svgElem.onGetPath = function () { svgElem.show(); }; } } else if (path && path.length) { plotLine.svgElem = svgElem = renderer.path(path) .attr(attribs).add(); // events if (events) { addEvent = function (eventType) { svgElem.on(eventType, function (e) { events[eventType].apply(plotLine, [e]); }); }; for (eventType in events) { addEvent(eventType); } } } // the plot band/line label if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) { // apply defaults optionsLabel = merge({ align: horiz && isBand && 'center', x: horiz ? !isBand && 4 : 10, verticalAlign : !horiz && isBand && 'middle', y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4, rotation: horiz && !isBand && 90 }, optionsLabel); // add the SVG element if (!label) { plotLine.label = label = renderer.text( optionsLabel.text, 0, 0 ) .attr({ align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation, zIndex: zIndex }) .css(optionsLabel.style) .add(); } // get the bounding box and align the label xs = [path[1], path[4], pick(path[6], path[1])]; ys = [path[2], path[5], pick(path[7], path[2])]; x = arrayMin(xs); y = arrayMin(ys); label.align(optionsLabel, false, { x: x, y: y, width: arrayMax(xs) - x, height: arrayMax(ys) - y }); label.show(); } else if (label) { // move out of sight label.hide(); } // chainable return plotLine; }, /** * Remove the plot line or band */ destroy: function () { var plotLine = this, axis = plotLine.axis; // remove it from the lookup erase(axis.plotLinesAndBands, plotLine); destroyObjectProperties(plotLine, this.axis); } }; /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption, stacking) { var inverted = axis.chart.inverted; this.axis = axis; // Tells if the stack is negative this.isNegative = isNegative; // Save the options to be able to style the label this.options = options; // Save the x value to be able to position the label later this.x = x; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; this.percent = stacking === 'percent'; // The align options and text align varies on whether the stack is negative and // if the chart is inverted or not. // First test the user supplied value, then use the dynamic. this.alignOptions = { align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'), verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')), y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)), x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0) }; this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center'); } StackItem.prototype = { destroy: function () { destroyObjectProperties(this, this.axis); }, /** * Sets the total of this stack. Should be called when a serie is hidden or shown * since that will affect the total of other stacks. */ setTotal: function (total) { this.total = total; this.cum = total; }, /** * Renders the stack total label and adds it to the stack label group. */ render: function (group) { var options = this.options, formatOption = options.format, // docs: added stackLabel.format option str = formatOption ? format(formatOption, this) : options.formatter.call(this); // format the text in the label // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden if (this.label) { this.label.attr({text: str, visibility: HIDDEN}); // Create new label } else { this.label = this.axis.chart.renderer.text(str, 0, 0, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries .css(options.style) // apply style .attr({ align: this.textAlign, // fix the text-anchor rotation: options.rotation, // rotation visibility: HIDDEN // hidden until setOffset is called }) .add(group); // add to the labels-group } }, /** * Sets the offset that the stack has from the x value and repositions the label. */ setOffset: function (xOffset, xWidth) { var stackItem = this, axis = stackItem.axis, chart = axis.chart, inverted = chart.inverted, neg = this.isNegative, // special treatment is needed for negative stacks y = axis.translate(this.percent ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates yZero = axis.translate(0), // stack origin h = mathAbs(y - yZero), // stack height x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position plotHeight = chart.plotHeight, stackBox = { // this is the box for the complete stack x: inverted ? (neg ? y : y - h) : x, y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y), width: inverted ? h : xWidth, height: inverted ? xWidth : h }, label = this.label, alignAttr; if (label) { label.align(this.alignOptions, null, stackBox); // align the label to the box // Set visibility (#678) alignAttr = label.alignAttr; label.attr({ visibility: this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN }); } } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ function Axis() { this.init.apply(this, arguments); } Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#C0C0C0', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: defaultLabelOptions, // { step: null }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 5, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#4d759e', //font: defaultFont.replace('normal', 'bold') fontWeight: 'bold' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { align: 'right', x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, tickWidth: 0, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return numberFormat(this.total, -1); }, style: defaultLabelOptions.style } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { align: 'right', x: -8, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { align: 'left', x: 8, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { align: 'center', x: 0, y: 14 // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for left axes */ defaultTopAxisOptions: { labels: { align: 'center', x: 0, y: -5 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.xOrY = isXAxis ? 'x' : 'y'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.staggerLines = axis.horiz && options.labels.staggerLines; axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series //axis.ignoreMaxPadding = UNDEFINED; axis.chart = chart; axis.reversed = options.reversed; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.categories = options.categories || type === 'category'; // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Flag if percentage mode //axis.usePercentage = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between') ? 0.5 : 0; // Major ticks axis.ticks = {}; // Minor ticks axis.minorTicks = {}; //axis.tickAmount = UNDEFINED; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis._stacksTouched = 0; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() chart.axes.push(axis); chart[isXAxis ? 'xAxis' : 'yAxis'].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = log2lin; axis.lin2val = lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.isXAxis ? {} : this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.isXAxis ? 'xAxis' : 'yAxis'], // if set in setOptions (#1053) userOptions ) ); }, /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.xOrY + 'Axis'][this.options.index] = merge(this.userOptions, newOptions); this.destroy(); this._addedPlotLB = false; // #1611 this.init(chart, newOptions); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.xOrY + 'Axis'; // xAxis or yAxis // Remove associated series each(this.series, function (series) { series.remove(false); }); // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); each(chart[key], function (axis, i) { // Re-index, #1706 axis.options.index = i; }); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && numericSymbols[i] !== null) { ret = numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (value >= 1000) { // add thousands separators ret = numberFormat(value, 0); } else { // small numbers ret = numberFormat(value, -1); } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart, stacks = axis.stacks, posStack = [], negStack = [], stacksTouched = axis._stacksTouched = axis._stacksTouched + 1, type, i; axis.hasVisibleSeries = false; // reset dataMin and dataMax in case we're redrawing axis.dataMin = axis.dataMax = null; // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, stacking, posPointStack, negPointStack, stackKey, stackOption, negKey, xData, yData, x, y, threshold = seriesOptions.threshold, yDataLength, activeYData = [], seriesDataMin, seriesDataMax, activeCounter = 0; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = seriesOptions.threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData)); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { var isNegative, pointStack, key, cropped = series.cropped, xExtremes = series.xAxis.getExtremes(), //findPointRange, //pointRange, j, hasModifyValue = !!series.modifyValue; // Handle stacking stacking = seriesOptions.stacking; axis.usePercentage = stacking === 'percent'; // create a stack for this particular series type if (stacking) { stackOption = seriesOptions.stack; stackKey = series.type + pick(stackOption, ''); negKey = '-' + stackKey; series.stackKey = stackKey; // used in translate posPointStack = posStack[stackKey] || []; // contains the total values for each x posStack[stackKey] = posPointStack; negPointStack = negStack[negKey] || []; negStack[negKey] = negPointStack; } if (axis.usePercentage) { axis.dataMin = 0; axis.dataMax = 99; } // processData can alter series.pointRange, so this goes after //findPointRange = series.pointRange === null; xData = series.processedXData; yData = series.processedYData; yDataLength = yData.length; // loop over the non-null y values and read them into a local array for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // Read stacked values into a stack based on the x value, // the sign of y and the stack key. Stacking is also handled for null values (#739) if (stacking) { isNegative = y < threshold; pointStack = isNegative ? negPointStack : posPointStack; key = isNegative ? negKey : stackKey; // Set the stack value and y for extremes if (defined(pointStack[x])) { // we're adding to the stack pointStack[x] = correctFloat(pointStack[x] + y); y = [y, pointStack[x]]; // consider both the actual value and the stack (#1376) } else { // it's the first point in the stack pointStack[x] = y; } // add the series if (!stacks[key]) { stacks[key] = {}; } // If the StackItem is there, just update the values, // if not, create one first if (!stacks[key][x]) { stacks[key][x] = new StackItem(axis, axis.options.stackLabels, isNegative, x, stackOption, stacking); } stacks[key][x].setTotal(pointStack[x]); stacks[key][x].touched = stacksTouched; } // Handle non null values if (y !== null && y !== UNDEFINED && (!axis.isLog || (y.length || y > 0))) { // general hook, used for Highstock compare values feature if (hasModifyValue) { y = series.modifyValue(y); } // For points within the visible range, including the first point outside the // visible range, consider y extremes if (series.getExtremesFromAll || cropped || ((xData[i + 1] || x) >= xExtremes.min && (xData[i - 1] || x) <= xExtremes.max)) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } } // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If the length of activeYData is 0, continue with null values. if (!axis.usePercentage && activeYData.length) { series.dataMin = seriesDataMin = arrayMin(activeYData); series.dataMax = seriesDataMax = arrayMax(activeYData); axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { if (axis.dataMin >= threshold) { axis.dataMin = threshold; axis.ignoreMinPadding = true; } else if (axis.dataMax < threshold) { axis.dataMax = threshold; axis.ignoreMaxPadding = true; } } } } }); // Destroy unused stacks (#1044) for (type in stacks) { for (i in stacks[type]) { if (stacks[type][i].touched < stacksTouched) { stacks[type][i].destroy(); delete stacks[type][i]; } } } }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacementBetween) { var axis = this, axisLength = axis.len, sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axisLength; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * axisLength; } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (postTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (postTranslate) { // log and ordinal axes val = axis.val2lin(val); } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (pointPlacementBetween ? localA * axis.pointRange / 2 : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function (value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function (pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old, force) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, translatedValue = axis.translate(value, null, null, old), cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB; x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; if (x1 < axisLeft || x1 > axisLeft + axis.width) { skip = true; } } else { x1 = axisLeft; x2 = cWidth - axis.right; if (y1 < axisTop || y1 > axisTop + axis.height) { skip = true; } } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 0); }, /** * Create the path for a plot band */ getPlotBandPath: function (from, to) { var toPath = this.getPlotLinePath(to), path = this.getPlotLinePath(from); if (path && toPath) { path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Set the tick positions of a logarithmic axis */ getLogTickPositions: function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max)) { // #1670 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, math.pow(10, mathFloor(math.log(interval) / math.LN10)) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, len; if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( getTimeTicks( normalizeTimeTickInterval(minorTickInterval), axis.min, axis.max, options.startOfWeek ) ); if (minorTickPositions[0] < axis.min) { minorTickPositions.shift(); } } else { for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) { minorTickPositions.push(pos); } } return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { var minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Update translation information */ setAxisTranslation: function (saveOld) { var axis = this, range = axis.max - axis.min, pointRange = 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, transA = axis.transA; // adjust translation for padding if (axis.isXAxis) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = series.pointRange, pointPlacement = series.options.pointPlacement, seriesClosestPointRange = series.closestPointRange; if (seriesPointRange > range) { // #1446 seriesPointRange = 0; } pointRange = mathMax(pointRange, seriesPointRange); // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, pointPlacement ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); // Set the closestPointRange if (!series.noSharedTooltip && defined(seriesClosestPointRange)) { closestPointRange = defined(closestPointRange) ? mathMin(closestPointRange, seriesClosestPointRange) : seriesClosestPointRange; } }); } // Record minPointOffset and pointRangePadding ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853 axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection; axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = mathMin(pointRange, range); // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value axis.closestPointRange = closestPointRange; } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickPositions: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, tickPositioner = axis.options.tickPositioner, magnitude, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickIntervalOption = options.minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, tickPositions, categories = axis.categories; // linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[isXAxis ? 'xAxis' : 'yAxis'][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } } else { // initial min and max from the extreme data values axis.min = pick(axis.userMin, options.min, axis.dataMin); axis.max = pick(axis.userMax, options.max, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934 axis.max = correctFloat(log2lin(axis.max)); } // handle zoomed range if (axis.range) { axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618 axis.userMax = axis.max; if (secondPass) { axis.range = null; // don't use it when running setExtremes } } // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) { axis.min -= length * minPadding; } if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) { axis.max += length * maxPadding; } } } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : (axis.max - axis.min) * tickPixelIntervalOption / (axis.len || 1) ); } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) { axis.tickInterval = minTickIntervalOption; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog) { // linear magnitude = math.pow(10, mathFloor(math.log(axis.tickInterval) / math.LN10)); if (!tickIntervalOption) { axis.tickInterval = normalizeTickInterval(axis.tickInterval, null, magnitude, options); } } // get minorTickInterval axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ? axis.tickInterval / 5 : options.minorTickInterval; // find the tick positions axis.tickPositions = tickPositions = options.tickPositions ? [].concat(options.tickPositions) : // Work on a copy (#1565) (tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max])); if (!tickPositions) { if (isDatetimeAxis) { tickPositions = (axis.getNonLinearTimeTicks || getTimeTicks)( normalizeTimeTickInterval(axis.tickInterval, options.units), axis.min, axis.max, options.startOfWeek, axis.ordinalPositions, axis.closestPointRange, true ); } else if (isLog) { tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max); } else { tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max); } axis.tickPositions = tickPositions; } if (!isLinked) { // reset min/max or remove extremes based on start/end on tick var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = axis.minPointOffset || 0, singlePad; if (options.startOnTick) { axis.min = roundedMin; } else if (axis.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (options.endOnTick) { axis.max = roundedMax; } else if (axis.max + minPointOffset < roundedMax) { tickPositions.pop(); } // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (tickPositions.length === 1) { singlePad = 0.001; // The lowest possible number to avoid extra padding on columns axis.min -= singlePad; axis.max += singlePad; } } }, /** * Set the max ticks of either the x and y axis collection */ setMaxTicks: function () { var chart = this.chart, maxTicks = chart.maxTicks || {}, tickPositions = this.tickPositions, key = this._maxTicksKey = [this.xOrY, this.pos, this.len].join('-'); if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) { maxTicks[key] = tickPositions.length; } chart.maxTicks = maxTicks; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var axis = this, chart = axis.chart, key = axis._maxTicksKey, tickPositions = axis.tickPositions, maxTicks = chart.maxTicks; if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false) { // only apply to linear scale var oldTickAmount = axis.tickAmount, calculatedTickAmount = tickPositions.length, tickAmount; // set the axis-level tickAmount to use below axis.tickAmount = tickAmount = maxTicks[key]; if (calculatedTickAmount < tickAmount) { while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + axis.tickInterval )); } axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1); axis.max = tickPositions[tickPositions.length - 1]; } if (defined(oldTickAmount) && tickAmount !== oldTickAmount) { axis.isDirty = true; } } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, stacks = axis.stacks, type, i, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) { axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickPositions(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } // reset stacks if (!axis.isXAxis) { for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } // Set the maximum tick amount axis.setMaxTicks(); }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; // Mark for running afterSetExtremes axis.isDirtyExtremes = true; // redraw if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { // Prevent pinch zooming out of range if (!this.allowZoomOutside) { if (newMin <= this.dataMin) { newMin = UNDEFINED; } if (newMax >= this.dataMax) { newMax = UNDEFINED; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED; // Do it this.setExtremes( newMin, newMax, false, UNDEFINED, { trigger: 'zoom' } ); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width, height, top, left; // Expose basic values to use in Series object and navigator this.left = left = pick(options.left, chart.plotLeft + offsetLeft); this.top = top = pick(options.top, chart.plotTop); this.width = width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight); this.height = height = pick(options.height, chart.plotHeight); this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog; var realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; if (realMin > threshold || threshold === null) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, addPlotBand: function (options) { this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function (options) { this.addPlotBandOrLine(options, 'plotLines'); }, /** * Add a plot band or plot line after render time * * @param options {Object} The plotBand or plotLine configuration object */ addPlotBandOrLine: function (options, coll) { var obj = new PlotLineOrBand(this, options).render(), userOptions = this.userOptions; // Add it to the user options for exporting and Axis.update if (coll) { userOptions[coll] = userOptions[coll] || []; userOptions[coll].push(options); } this.plotLinesAndBands.push(obj); return obj; }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, directionFactor = [-1, 1, 1, -1][side], n; // For reuse in Axis.render axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions)); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .add(); } if (hasData || axis.isLinked) { each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); each(tickPositions, function (pos) { // left side must be align: right and right side must have align: left for labels if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === labelOptions.align) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); } }); if (axis.staggerLines) { labelOffset += (axis.staggerLines - 1) * 16; } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) { if (!axis.axisTitle) { axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: axisTitleOptions.textAlign || { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align] }) .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10); titleOffsetOption = axisTitleOptions.offset; } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); axis.axisTitleMargin = pick(titleOffsetOption, labelOffset + titleMargin + (side !== 2 && labelOffset && directionFactor * options.labels[horiz ? 'y' : 'x']) ); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset ); clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], options.lineWidth); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; this.lineTop = lineTop; // used by flag series if (!opposite) { lineWidth *= -1; // crispify the other way - #1480 } return chart.renderer.crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis : offAxis + (opposite ? this.width : 0) + offset + (axisTitleOptions.x || 0), // x y: horiz ? offAxis - (opposite ? this.height : 0) + offset : alongAxis + (axisTitleOptions.y || 0) // y }; }, /** * Render the axis */ render: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, axisTitle = axis.axisTitle, stacks = axis.stacks, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin), hasData = axis.hasData, showAxis = axis.showAxis, from, to; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (hasData || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 each(tickPositions.slice(1).concat([tickPositions[0]]), function (pos, i) { // Reorganize the indices i = (i === tickPositions.length - 1) ? 0 : i + 1; // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true); } ticks[pos].render(i, false, 1); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && axis.min === 0) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { if (i % 2 === 0 && pos < axis.max) { if (!alternateBands[pos]) { alternateBands[pos] = new PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max; alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos, i, forDestruction = [], delay = globalAnimation ? globalAnimation.duration || 500 : 0, destroyInactiveItems = function () { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them if (coll === alternateBands || !chart.hasRendered || !delay) { destroyInactiveItems(); } else if (delay) { setTimeout(destroyInactiveItems, delay); } }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { linePath = axis.getLinePath(lineWidth); if (!axis.axisLine) { axis.axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLine.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[showAxis ? 'show' : 'hide'](); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { var stackKey, oneStack, stackCategory, stackTotalGroup = axis.stackTotalGroup; // Create a separate group for the stack total labels if (!stackTotalGroup) { axis.stackTotalGroup = stackTotalGroup = renderer.g('stack-labels') .attr({ visibility: VISIBLE, zIndex: 6 }) .add(); } // plotLeft/Top will change when y axis gets wider so we need to translate the // stackTotalGroup at every render call. See bug #506 and #516 stackTotalGroup.translate(chart.plotLeft, chart.plotTop); // Render each stack total for (stackKey in stacks) { oneStack = stacks[stackKey]; for (stackCategory in oneStack) { oneStack[stackCategory].render(stackTotalGroup); } } } // End stacked totals axis.isDirty = false; }, /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ removePlotBandOrLine: function (id) { var plotLinesAndBands = this.plotLinesAndBands, i = plotLinesAndBands.length; while (i--) { if (plotLinesAndBands[i].id === id) { plotLinesAndBands[i].destroy(); } } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { var axis = this, chart = axis.chart, pointer = chart.pointer; // hide tooltip and hover states if (pointer.reset) { pointer.reset(true); } // render the axis axis.render(); // move plot lines and bands each(axis.plotLinesAndBands, function (plotLine) { plotLine.render(); }); // mark associated series as dirty and ready for redraw each(axis.series, function (series) { series.isDirty = true; }); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); }, /** * Destroys an Axis instance. */ destroy: function () { var axis = this, stacks = axis.stacks, stackKey; // Remove the events removeEvent(axis); // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands, axis.plotLinesAndBands], function (coll) { destroyObjectProperties(coll); }); // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisGroup', 'gridGroup', 'labelGroup', 'axisTitle'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); } }; // end Axis /** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ function Tooltip() { this.init.apply(this, arguments); } Tooltip.prototype = { init: function (chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape, null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .hide() .add(); // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; }, /** * Destroy the tooltip and its elements. */ destroy: function () { each(this.crosshairs, function (crosshair) { if (crosshair) { crosshair.destroy(); } }); // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } clearTimeout(this.hideTimer); clearTimeout(this.tooltipTimeout); }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden; // get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: animate ? (now.anchorY + anchorY) / 2 : anchorY }); // move to the intermediate value tooltip.label.attr(now); // run on next tick of the mouse tracker if (animate && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) { // never allow two timeouts clearTimeout(this.tooltipTimeout); // set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function () { var tooltip = this, hoverPoints; clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766) if (!this.isHidden) { hoverPoints = this.chart.hoverPoints; this.hideTimer = setTimeout(function () { tooltip.label.fadeOut(); tooltip.isHidden = true; }, pick(this.options.hideDelay, 500)); // hide previous hoverPoints and set new if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } this.chart.hoverPoints = null; } }, /** * Hide the crosshairs */ hideCrosshairs: function () { each(this.crosshairs, function (crosshair) { if (crosshair) { crosshair.hide(); } }); }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotX = 0, plotY = 0, yAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === UNDEFINED) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; plotX += point.plotX; plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { // Set up the variables var chart = this.chart, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, distance = pick(this.options.distance, 12), pointX = point.plotX, pointY = point.plotY, x = pointX + plotLeft + (chart.inverted ? distance : -boxWidth - distance), y = pointY - boxHeight + plotTop + 15, // 15 means the point is 15 pixels up from the bottom of the tooltip alignedRight; // It is too far to the left, adjust it if (x < 7) { x = plotLeft + mathMax(pointX, 0) + distance; } // Test to see if the tooltip is too far to the right, // if it is, move it back to be inside and then up to not cover the point. if ((x + boxWidth) > (plotLeft + plotWidth)) { x -= (x + boxWidth) - (plotLeft + plotWidth); y = pointY - boxHeight + plotTop - distance; alignedRight = true; } // If it is now above the plot area, align it to the top of the plot area if (y < plotTop + 5) { y = plotTop + 5; // If the tooltip is still covering the point, move it below instead if (alignedRight && pointY >= y && pointY <= (y + boxHeight)) { y = pointY + plotTop + distance; // below } } // Now if the tooltip is below the chart, move it up. It's better to cover the // point than to disappear outside the chart. #834. if (y + boxHeight > plotTop + plotHeight) { y = mathMax(plotTop, plotTop + plotHeight - boxHeight - distance); // below } return {x: x, y: y}; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), series = items[0].series, s; // build the header s = [series.tooltipHeaderFormatter(items[0])]; // build the values each(items, function (item) { series = item.series; s.push((series.tooltipFormatter && series.tooltipFormatter(item)) || item.point.tooltipFormatter(series.tooltipOptions.pointFormat)); }); // footer s.push(tooltip.options.footerFormat || ''); return s.join(''); }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options, x, y, show, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, crosshairsOptions = options.crosshairs, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; // For line type series, hide tooltip if the point falls outside the plot show = shared || !currentSeries.isCartesian || currentSeries.tooltipOutsidePlot || chart.isInsidePlot(x, y); // update the inner HTML if (text === false || !show) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr('opacity', 1).show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); tooltip.updatePosition({ plotX: x, plotY: y }); this.isHidden = false; } // crosshairs if (crosshairsOptions) { crosshairsOptions = splat(crosshairsOptions); // [x, y] var path, i = crosshairsOptions.length, attribs, axis, val; while (i--) { axis = point.series[i ? 'yAxis' : 'xAxis']; if (crosshairsOptions[i] && axis) { val = i ? pick(point.stackY, point.y) : point.x; // #814 if (axis.isLog) { // #1671 val = log2lin(val); } path = axis.getPlotLinePath( val, 1 ); if (tooltip.crosshairs[i]) { tooltip.crosshairs[i].attr({ d: path, visibility: VISIBLE }); } else { attribs = { 'stroke-width': crosshairsOptions[i].width || 1, stroke: crosshairsOptions[i].color || '#C0C0C0', zIndex: crosshairsOptions[i].zIndex || 2 }; if (crosshairsOptions[i].dashStyle) { attribs.dashstyle = crosshairsOptions[i].dashStyle; } tooltip.crosshairs[i] = chart.renderer.path(path) .attr(attribs) .add(); } } } } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); }, /** * Find the new position and perform the move */ updatePosition: function (point) { var chart = this.chart, label = this.label, pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( mathRound(pos.x), mathRound(pos.y), point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); } }; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ function Pointer(chart, options) { this.init(chart, options); } Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var zoomType = useCanVG ? '' : options.chart.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); this.pinchDown = []; this.lastValidTouch = {}; if (options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e) { var chartPosition, chartX, chartY, ePos; // common IE normalizing e = e || win.event; if (!e.target) { e.target = e.srcElement; } // Framework specific normalizing (#1165) e = washMouseEvent(e); // iOS ePos = e.touches ? e.touches.item(0) : e; // get mouse position this.chartPosition = chartPosition = offset(this.chart.container); // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = e.x; chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * Return the index in the tooltipPoints array, corresponding to pixel position in * the plot area. */ getIndex: function (e) { var chart = this.chart; return chart.inverted ? chart.plotHeight + chart.plotTop - e.chartY : e.chartX - chart.plotLeft; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, point, points, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, j, distance = chart.chartWidth, index = pointer.getIndex(e), anchor; // shared tooltip if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) { points = []; // loop over all series and find the ones with points closest to the mouse i = series.length; for (j = 0; j < i; j++) { if (series[j].visible && series[j].options.enableMouseTracking !== false && !series[j].noSharedTooltip && series[j].tooltipPoints.length) { point = series[j].tooltipPoints[index]; if (point.series) { // not a dummy point, #1544 point._dist = mathAbs(index - point.clientX); distance = mathMin(distance, point._dist); points.push(point); } } } // remove furthest points i = points.length; while (i--) { if (points[i]._dist > distance) { points.splice(i, 1); } } // refresh the tooltip if necessary if (points.length && (points[0].clientX !== pointer.hoverX)) { tooltip.refresh(points, e); pointer.hoverX = points[0].clientX; } } // separate tooltip and general mouse events if (hoverSeries && hoverSeries.tracker) { // only use for line-type series with common tracker // get the point point = hoverSeries.tooltipPoints[index]; // a new point is hovered, refresh the tooltip if (point && point !== hoverPoint) { // trigger the events point.onMouseOver(e); } } else if (tooltip && tooltip.followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area, #1003 if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) { allowMove = false; } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(); tooltip.hideCrosshairs(); } pointer.hoverX = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart; // Scale each series each(chart.series, function (series) { if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(attribs); if (series.markerGroup) { series.markerGroup.attr(attribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(attribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { // TODO: implement clipping for inverted charts clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function (e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, followTouchMove = chart.tooltip && chart.tooltip.options.followTouchMove, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, zoomHor = self.zoomHor || self.pinchHor, zoomVert = self.zoomVert || self.pinchVert, hasZoom = zoomHor || zoomVert, selectionMarker = self.selectionMarker, transform = {}, clip = {}; // On touch devices, only proceed to trigger click if a handler is defined if (e.type === 'touchstart') { if (followTouchMove || hasZoom) { e.preventDefault(); } } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(axis.dataMin), max = axis.toPixels(axis.dataMax), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop }, chart.plotBox); } if (zoomHor) { self.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (zoomVert) { self.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } } }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY; // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside) { if (!this.selectionMarker) { this.selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (this.selectionMarker && zoomHor) { size = chartX - mouseDownX; this.selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (this.selectionMarker && zoomVert) { size = chartY - mouseDownY; this.selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !this.selectionMarker && chartOptions.panning) { chart.pan(chartX); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { xAxis: [], yAxis: [], originalEvent: e.originalEvent || e }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.x, selectionTop = selectionBox.y, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled) { var horiz = axis.horiz, selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop)), selectionMax = axis.toValue((horiz ? selectionLeft + selectionBox.width : selectionTop + selectionBox.height)); if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859 selectionData[axis.xOrY + 'Axis'].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes, max: mathMax(selectionMin, selectionMax) }); runZoom = true; } } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups({ translateX: chart.plotLeft, translateY: chart.plotTop, scaleX: 1, scaleY: 1 }); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { this.drop(e); }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition, hoverSeries = chart.hoverSeries; // Get e.pageX and e.pageY back in MooTools e = washMouseEvent(e); // If we're outside, hide the tooltip if (chartPosition && hoverSeries && hoverSeries.isCartesian && !chart.isInsidePlot(e.pageX - chartPosition.left - chart.plotLeft, e.pageY - chartPosition.top - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function () { this.reset(); this.chartPosition = null; // also reset the chart position, used in #149 fix }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; // normalize e = this.normalize(e); // #295 e.returnValue = false; if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries; if (series && !series.options.stickyTracking && !this.inClass(e.toElement || e.relatedTarget, PREFIX + 'tooltip')) { series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop, inverted = chart.inverted, chartPosition, plotX, plotY; e = this.normalize(e); e.cancelBubble = true; // IE specific if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { chartPosition = this.chartPosition; plotX = hoverPoint.plotX; plotY = hoverPoint.plotY; // add page position info extend(hoverPoint, { pageX: chartPosition.left + plotLeft + (inverted ? chart.plotWidth - plotY : plotX), pageY: chartPosition.top + plotTop + (inverted ? chart.plotHeight - plotX : plotY) }); // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, onContainerTouchStart: function (e) { var chart = this.chart; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { // Prevent the click pseudo event from firing unless it is set in the options /*if (!chart.runChartClick) { e.preventDefault(); }*/ // Run mouse events and display tooltip etc this.runPointActions(e); this.pinch(e); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchMove: function (e) { if (e.touches.length === 1 || e.touches.length === 2) { this.pinch(e); } }, onDocumentTouchEnd: function (e) { this.drop(e); }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container, events; this._events = events = [ [container, 'onmousedown', 'onContainerMouseDown'], [container, 'onmousemove', 'onContainerMouseMove'], [container, 'onclick', 'onContainerClick'], [container, 'mouseleave', 'onContainerMouseLeave'], [doc, 'mousemove', 'onDocumentMouseMove'], [doc, 'mouseup', 'onDocumentMouseUp'] ]; if (hasTouch) { events.push( [container, 'ontouchstart', 'onContainerTouchStart'], [container, 'ontouchmove', 'onContainerTouchMove'], [doc, 'touchend', 'onDocumentTouchEnd'] ); } each(events, function (eventConfig) { // First, create the callback function that in turn calls the method on Pointer pointer['_' + eventConfig[2]] = function (e) { pointer[eventConfig[2]](e); }; // Now attach the function, either as a direct property or through addEvent if (eventConfig[1].indexOf('on') === 0) { eventConfig[0][eventConfig[1]] = pointer['_' + eventConfig[2]]; } else { addEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]); } }); }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var pointer = this; // Release all DOM events each(pointer._events, function (eventConfig) { if (eventConfig[1].indexOf('on') === 0) { eventConfig[0][eventConfig[1]] = null; // delete breaks oldIE } else { removeEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]); } }); delete pointer._events; // memory and CPU leak clearInterval(pointer.tooltipTimeout); } }; /** * The overview of the chart's series */ function Legend(chart, options) { this.init(chart, options); } Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding = pick(options.padding, 8), itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.baseline = pInt(itemStyle.fontSize) + 3 + itemMarginTop; // used in Series prototype legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding; legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; legend.itemHeight = 0; legend.lastLineHeight = 0; // Render it legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? item.color : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { stroke: symbolColor, fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions) { markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox; if (item.legendGroup) { item.legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = (translateY + checkbox.y + (scrollOffset || 0) + 3); css(checkbox, { left: (alignAttr.translateX + item.legendItemWidth + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .css(titleOptions.style) .add(this.group); } titleHeight = this.title.getBBox().height; this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = options.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series || item, itemOptions = series.options, showCheckbox = itemOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item), ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? li : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); li.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { li.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { item.setVisible(); }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (itemOptions && showCheckbox) { item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, options.itemCheckboxStyle, chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item, 'checkboxClick', { checked: target.checked }, function () { item.select(); } ); }); } } // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.legendItemWidth = options.itemWidth || symbolWidth + symbolPadding + bBox.width + padding + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = bBox.height; // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( horizontal ? legend.itemX - initialItemX : itemWidth, legend.offsetWidth ); }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = []; each(chart.series, function (serie) { var seriesOptions = serie.options; if (!seriesOptions.showInLegend || defined(seriesOptions.linkedTo)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( serie.legendItems || (seriesOptions.legendType === 'point' ? serie.data : serie) ); }); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items each(allItems, function (item) { legend.renderItem(item); }); // Draw the border legendWidth = options.width || legend.offsetWidth; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); if (legendBorderWidth || legendBackgroundColor) { legendWidth += padding; legendHeight += padding; if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp(null, null, null, legendWidth, legendHeight) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, pageCount, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle if (legendHeight > spaceHeight && !options.useHTML) { this.clipHeight = clipHeight = spaceHeight - 20 - this.titleHeight; this.pageCount = pageCount = mathCeil(legendHeight / clipHeight); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, 0, 9999, 0); legend.contentGroup.clip(clipRect); } clipRect.attr({ height: clipHeight }); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipRect.attr({ height: chart.chartHeight }); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pageCount = this.pageCount, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + this.pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -mathMin(clipHeight * (currentPage - 1), this.fullHeight - clipHeight + padding) + 1; this.scrollGroup.animate({ translateY: scrollOffset }); pager.attr({ text: currentPage + '/' + pageCount }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ function Chart() { this.init.apply(this, arguments); } Chart.prototype = { /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data var optionsChart = options.chart, optionsMargin = optionsChart.margin, margin = isObject(optionsMargin) ? optionsMargin : [optionsMargin, optionsMargin, optionsMargin, optionsMargin]; this.optionsMarginTop = pick(optionsChart.marginTop, margin[0]); this.optionsMarginRight = pick(optionsChart.marginRight, margin[1]); this.optionsMarginBottom = pick(optionsChart.marginBottom, margin[2]); this.optionsMarginLeft = pick(optionsChart.marginLeft, margin[3]); var chartEvents = optionsChart.events; this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', function () { chart.initReflow(); }); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = 0; chart.counters = new ChartCounters(); chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, constr = seriesTypes[type]; // No such series type if (!constr) { error(17, true); } series = new constr(); series.init(this, options); return series; }, /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function (options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options, axis; /*jslint unused: false*/ axis = new Axis(this, merge(options, { index: this[key].length })); /*jslint unused: true*/ // Push the new axis options to the chart options chartOptions[key] = splat(chartOptions[key] || {}); chartOptions[key].push(options); if (pick(redraw, true)) { this.redraw(animation); } }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Adjust all axes tick amounts */ adjustTickAmounts: function () { if (this.options.chart.alignTicks !== false) { each(this.axes, function (axis) { axis.adjustTickAmount(); }); } this.maxTicks = null; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed? seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // link stacked series while (i--) { serie = series[i]; if (serie.isDirty && serie.options.stacking) { hasStackedSeries = true; break; } } if (hasStackedSeries) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // handle updated data in the series each(series, function (serie) { if (serie.isDirty) { // prepare the data so axis can read it if (serie.options.legendType === 'point') { redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } if (chart.hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } chart.adjustTickAmounts(); chart.getMargins(); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set if (axis.isDirtyExtremes) { // #821 axis.isDirtyExtremes = false; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', axis.getExtremes()); // #747, #751 }); } if (axis.isDirty || isDirtyBox || hasStackedSeries) { axis.redraw(); isDirtyBox = true; // #792 } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (pointer && pointer.reset) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function (callback) { callback.call(); }); }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv; var loadingOptions = options.loading; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '', left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function (id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function () { var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray, axis; // make sure the options are arrays and add some members each(xAxisOptions, function (axis, i) { axis.index = i; axis.isX = true; }); each(yAxisOptions, function (axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function (axisOptions) { axis = new Axis(chart, axisOptions); }); chart.adjustTickAmounts(); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points || [], function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .add() .align(btnOptions.position, false, alignTo); }, /** * Zoom out to 1:1 */ zoomOut: function () { var chart = this; fireEvent(chart, 'selection', { resetSelection: true }, function () { chart.zoom(); }); }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function (axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function (axisData) { var axis = axisData.axis, isXAxis = axis.isXAxis; // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function (chartX) { var chart = this, xAxis = chart.xAxis[0], mouseDownX = chart.mouseDownX, halfPointRange = xAxis.pointRange / 2, extremes = xAxis.getExtremes(), newMin = xAxis.translate(mouseDownX - chartX, true) + halfPointRange, newMax = xAxis.translate(mouseDownX + chart.plotWidth - chartX, true) - halfPointRange, hoverPoints = chart.hoverPoints; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } if (xAxis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) { xAxis.setExtremes(newMin, newMax, true, false, { trigger: 'pan' }); } chart.mouseDownX = chartX; // set new reference for next run css(chart.container, { cursor: 'move' }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add() .align(chartTitleOptions, false, 'spacingBox'); } }); }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) chart.containerWidth = adapterRun(renderTo, 'width'); chart.containerHeight = adapterRun(renderTo, 'height'); chart.chartWidth = mathMax(0, optionsChart.width || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(optionsChart.height, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { this.renderTo.appendChild(container); discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, optionsChart = chart.options.chart, chartWidth, chartHeight, renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, containerId; chart.renderTo = renderTo = optionsChart.renderTo; containerId = PREFIX + idCounter++; if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex]) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly if (!renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0, // #1072 '-webkit-tap-highlight-color': 'rgba(0,0,0,0)' }, optionsChart.style), chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; chart.renderer = optionsChart.forExport ? // force SVG, used for SVG export new SVGRenderer(container, chartWidth, chartHeight, true) : new Renderer(container, chartWidth, chartHeight); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function () { var chart = this, optionsChart = chart.options.chart, spacingTop = optionsChart.spacingTop, spacingRight = optionsChart.spacingRight, spacingBottom = optionsChart.spacingBottom, spacingLeft = optionsChart.spacingLeft, axisOffset, legend = chart.legend, optionsMarginTop = chart.optionsMarginTop, optionsMarginLeft = chart.optionsMarginLeft, optionsMarginRight = chart.optionsMarginRight, optionsMarginBottom = chart.optionsMarginBottom, chartTitleOptions = chart.options.title, chartSubtitleOptions = chart.options.subtitle, legendOptions = chart.options.legend, legendMargin = pick(legendOptions.margin, 10), legendX = legendOptions.x, legendY = legendOptions.y, align = legendOptions.align, verticalAlign = legendOptions.verticalAlign, titleOffset; chart.resetMargins(); axisOffset = chart.axisOffset; // adjust for title and subtitle if ((chart.title || chart.subtitle) && !defined(chart.optionsMarginTop)) { titleOffset = mathMax( (chart.title && !chartTitleOptions.floating && !chartTitleOptions.verticalAlign && chartTitleOptions.y) || 0, (chart.subtitle && !chartSubtitleOptions.floating && !chartSubtitleOptions.verticalAlign && chartSubtitleOptions.y) || 0 ); if (titleOffset) { chart.plotTop = mathMax(chart.plotTop, titleOffset + pick(chartTitleOptions.margin, 15) + spacingTop); } } // adjust for legend if (legend.display && !legendOptions.floating) { if (align === 'right') { // horizontal alignment handled first if (!defined(optionsMarginRight)) { chart.marginRight = mathMax( chart.marginRight, legend.legendWidth - legendX + legendMargin + spacingRight ); } } else if (align === 'left') { if (!defined(optionsMarginLeft)) { chart.plotLeft = mathMax( chart.plotLeft, legend.legendWidth + legendX + legendMargin + spacingLeft ); } } else if (verticalAlign === 'top') { if (!defined(optionsMarginTop)) { chart.plotTop = mathMax( chart.plotTop, legend.legendHeight + legendY + legendMargin + spacingTop ); } } else if (verticalAlign === 'bottom') { if (!defined(optionsMarginBottom)) { chart.marginBottom = mathMax( chart.marginBottom, legend.legendHeight - legendY + legendMargin + spacingBottom ); } } } // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { axis.getOffset(); }); } if (!defined(optionsMarginLeft)) { chart.plotLeft += axisOffset[3]; } if (!defined(optionsMarginTop)) { chart.plotTop += axisOffset[0]; } if (!defined(optionsMarginBottom)) { chart.marginBottom += axisOffset[2]; } if (!defined(optionsMarginRight)) { chart.marginRight += axisOffset[1]; } chart.setChartSize(); }, /** * Add the event handlers necessary for auto resizing * */ initReflow: function () { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, reflowTimeout; function reflow(e) { var width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win; // #805 - MooTools doesn't supply e // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!chart.hasUserSize && width && height && (target === win || target === doc)) { if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(reflowTimeout); chart.reflowTimeout = reflowTimeout = setTimeout(function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }, 100); } chart.containerWidth = width; chart.containerHeight = height; } } addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, chartWidth, chartHeight, fireEndResize; // Handle the isResizing counter chart.isResizing += 1; fireEndResize = function () { if (chart) { fireEvent(chart, 'endResize', null, function () { chart.isResizing -= 1; }); } }; // set the animation for the current process setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (defined(width)) { chart.chartWidth = chartWidth = mathMax(0, mathRound(width)); chart.hasUserSize = !!chartWidth; } if (defined(height)) { chart.chartHeight = chartHeight = mathMax(0, mathRound(height)); } css(chart.container, { width: chartWidth + PX, height: chartHeight + PX }); chart.setChartSize(true); chart.renderer.setSize(chartWidth, chartHeight, animation); // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.getMargins(); chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // fire endResize and set isResizing back // If animation is disabled, fire without delay if (globalAnimation === false) { fireEndResize(); } else { // else set a timeout with the animation duration setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500); } }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function (skipAxes) { var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacingTop = optionsChart.spacingTop, spacingRight = optionsChart.spacingRight, spacingBottom = optionsChart.spacingBottom, spacingLeft = optionsChart.spacingLeft, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = mathRound(chart.plotLeft); chart.plotTop = plotTop = mathRound(chart.plotTop); chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacingLeft, y: spacingTop, width: chartWidth - spacingLeft - spacingRight, height: chartHeight - spacingTop - spacingBottom }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2); clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2); chart.clipBox = { x: clipX, y: clipY, width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX), height: mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY) }; if (!skipAxes) { each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this, optionsChart = chart.options.chart, spacingTop = optionsChart.spacingTop, spacingRight = optionsChart.spacingRight, spacingBottom = optionsChart.spacingBottom, spacingLeft = optionsChart.spacingLeft; chart.plotTop = pick(chart.optionsMarginTop, spacingTop); chart.marginRight = pick(chart.optionsMarginRight, spacingRight); chart.marginBottom = pick(chart.optionsMarginBottom, spacingBottom); chart.plotLeft = pick(chart.optionsMarginLeft, spacingLeft); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp(null, null, null, chartWidth - mgn, chartHeight - mgn) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp(null, plotLeft, plotTop, plotWidth, plotHeight) ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options; var labels = options.labels, credits = options.credits, creditsHref; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); // Get margins by pre-rendering axes // set axes scales each(axes, function (axis) { axis.setScale(); }); chart.getMargins(); chart.maxTicks = null; // reset for second pass each(axes, function (axis) { axis.setTickPositions(true); // update to reflect the new margins axis.setMaxTicks(); }); chart.adjustTickAmounts(); chart.getMargins(); // second pass to check for new labels // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { axis.render(); }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } each(chart.series, function (serie) { serie.translate(); serie.setTooltipPoints(); serie.render(); }); // Labels if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } // Credits if (credits.enabled && !chart.credits) { creditsHref = credits.href; chart.credits = renderer.text( credits.text, 0, 0 ) .on('click', function () { if (creditsHref) { location.href = creditsHref; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } // Set flag chart.hasRendered = true; }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: in spite of JSLint's complaints, win == win.top is required /*jslint eqeq: true*/ if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { /*jslint eqeq: false*/ if (useCanVG) { // Delay rendering until canvg library is downloaded and ready CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL); } else { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); } return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function () { var chart = this, options = chart.options, callback = chart.callback; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function (serieOptions) { chart.initSeries(serieOptions); }); // Run an event after axes and series are initialized, but before render. At this stage, // the series data is indexed and cached in the xData and yData arrays, so we can access // those before rendering. Used in Highstock. fireEvent(chart, 'beforeRender'); // depends on inverted and on margins being set chart.pointer = new Pointer(chart, options); chart.render(); // add canvas chart.renderer.draw(); // run callbacks if (callback) { callback.apply(chart, [chart]); } each(chart.callbacks, function (fn) { fn.apply(chart, [chart]); }); // If the chart was rendered outside the top container, put it back in chart.cloneRenderTo(true); fireEvent(chart, 'load'); } }; // end Chart // Hook for exporting module Chart.prototype.callbacks = []; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, colors; point.series = series; point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { colors = series.options.colors || series.chart.options.colors; point.color = point.color || colors[series.colorCounter++]; // loop back to zero if (series.colorCounter === colors.length) { series.colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointValKey = series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if (point.x === UNDEFINED && series) { point.x = x === UNDEFINED ? series.autoIncrement() : x; } return point; }, /** * Transform number or array configs into objects */ optionsToObject: function (options) { var ret, series = this.series, pointArrayMap = series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (typeof options === 'number' || options === null) { ret = { y: options }; } else if (isArray(options)) { ret = {}; // with leading x value if (options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { ret[pointArrayMap[j++]] = options[i++]; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { var point = this; return { x: point.category, y: point.y, key: point.name || point.category, series: point.series, point: point, percentage: point.percentage, total: point.total || point.stackTotal }; }, /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the defalut handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { point.selected = point.options.selected = selected; series.options.data[inArray(point, series.data)] = point.options; point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; series.options.data[inArray(loopPoint, series.data)] = loopPoint.options; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }); }, /** * Runs on mouse over the point */ onMouseOver: function (e) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point, e); } // hover this point.setState(HOVER_STATE); chart.hoverPoint = point; }, /** * Runs on mouse out from the point */ onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887 this.firePointEvent('mouseOut'); this.setState(); chart.hoverPoint = null; } }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function (key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation) { var point = this, series = point.series, graphic = point.graphic, i, data = series.data, chart = series.chart; redraw = pick(redraw, true); // fire the event with a default handler of doing the update point.firePointEvent('update', { options: options }, function () { point.applyOptions(options); // update visuals if (isObject(options)) { series.getAttribs(); if (graphic) { graphic.attr(point.pointAttr[series.state]); } } // record changes in the parallel arrays i = inArray(point, data); series.xData[i] = point.x; series.yData[i] = series.toYData ? series.toYData(point) : point.y; series.zData[i] = point.z; series.options.data[i] = point.options; // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(animation); } }); }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var point = this, series = point.series, chart = series.chart, i, data = series.data; setAnimation(animation, chart); redraw = pick(redraw, true); // fire the event with a default handler of removing the point point.firePointEvent('remove', null, function () { // splice all the parallel arrays i = inArray(point, data); data.splice(i, 1); series.options.data.splice(i, 1); series.xData.splice(i, 1); series.yData.splice(i, 1); series.zData.splice(i, 1); point.destroy(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }); }, /** * Fire an event on the Point object. Must not be renamed to fireEvent, as this * causes a name clash in MooTools * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function (eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); }; } fireEvent(this, eventType, eventArgs, defaultFunction); }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state) { var point = this, plotX = point.plotX, plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, radius, newSymbol, pointAttr = point.pointAttr; state = state || NORMAL_STATE; // empty string if ( // already has this state state === point.state || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // point marker's state options is disabled (state && (stateDisabled || (normalDisabled && !markerStateOptions.enabled))) ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr[state].r; point.graphic.attr(merge( pointAttr[state], radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr[state]) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; // Move the existing graphic } else { stateMarkerGraphic.attr({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY) ? 'show' : 'hide'](); } } point.state = state; } }; /** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, colorCounter: 0, init: function (chart, options) { var series = this, eventType, events, linkedTo, chartSeries = chart.series; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // set the data series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123) stableSort(chartSeries, function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, a._i); }); each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); // Linked series linkedTo = options.linkedTo; series.linkedSeries = []; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chartSeries[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo) { linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; } } }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; if (series.isCartesian) { each(['xAxis', 'yAxis'], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS]) { error(18, true); } }); } }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var series = this, options = series.options, xIncrement = series.xIncrement; xIncrement = pick(xIncrement, options.pointStart, 0); series.pointInterval = pick(series.pointInterval, options.pointInterval, 1); series.xIncrement = xIncrement + series.pointInterval; return xIncrement; }, /** * Divide the series data into segments divided by null values. */ getSegments: function () { var series = this, lastNull = -1, segments = [], i, points = series.points, pointsLength = points.length; if (pointsLength) { // no action required for [] // if connect nulls, just remove null points if (series.options.connectNulls) { i = pointsLength; while (i--) { if (points[i].y === null) { points.splice(i, 1); } } if (points.length) { segments = [points]; } // else, split on null points } else { each(points, function (point, i) { if (point.y === null) { if (i > lastNull + 1) { segments.push(points.slice(lastNull + 1, i)); } lastNull = i; } else if (i === pointsLength - 1) { // last value segments.push(points.slice(lastNull + 1, i + 1)); } }); } } // register it series.segments = segments; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function (itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, typeOptions = plotOptions[this.type], options; this.userOptions = itemOptions; options = merge( typeOptions, plotOptions.series, itemOptions ); // the tooltip options are merged between global and series specific options this.tooltipOptions = merge(chartOptions.tooltip, options.tooltip); // Delte marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } return options; }, /** * Get the series' color */ getColor: function () { var options = this.options, userOptions = this.userOptions, defaultColors = this.chart.options.colors, counters = this.chart.counters, color, colorIndex; color = options.color || defaultPlotOptions[this.type].color; if (!color && !options.colorByPoint) { if (defined(userOptions._colorIndex)) { // after Series.update() colorIndex = userOptions._colorIndex; } else { userOptions._colorIndex = counters.color; colorIndex = counters.color++; } color = defaultColors[colorIndex]; } this.color = color; counters.wrapColor(defaultColors.length); }, /** * Get the series' symbol */ getSymbol: function () { var series = this, userOptions = series.userOptions, seriesMarkerOption = series.options.marker, chart = series.chart, defaultSymbols = chart.options.symbols, counters = chart.counters, symbolIndex; series.symbol = seriesMarkerOption.symbol; if (!series.symbol) { if (defined(userOptions._symbolIndex)) { // after Series.update() symbolIndex = userOptions._symbolIndex; } else { userOptions._symbolIndex = counters.symbol; symbolIndex = counters.symbol++; } series.symbol = defaultSymbols[symbolIndex]; } // don't substract radius in image symbols (#604) if (/^url/.test(series.symbol)) { seriesMarkerOption.radius = 0; } counters.wrapSymbol(defaultSymbols.length); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLegendSymbol: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendOptions = legend.options, legendSymbol, symbolWidth = legendOptions.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, baseline = legend.baseline, attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, baseline - 4, L, symbolWidth, baseline - 4 ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, baseline - 4 - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); } }, /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, graph = series.graph, area = series.area, chart = series.chart, xData = series.xData, yData = series.yData, zData = series.zData, names = series.names, currentShift = (graph && graph.shift) || 0, dataOptions = seriesOptions.data, point; setAnimation(animation, chart); // Make graph animate sideways if (graph && shift) { graph.shift = currentShift + 1; } if (area) { if (shift) { // #780 area.shift = currentShift + 1; } area.isArea = true; // needed in animation, both with and without shift } // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); xData.push(point.x); yData.push(series.toYData ? series.toYData(point) : point.y); zData.push(point.z); if (names) { names[point.x] = point.name; } dataOptions.push(options); // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays // todo: consider series.removePoint(i) method if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); xData.shift(); yData.shift(); zData.shift(); dataOptions.shift(); } } series.getAttribs(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw) { var series = this, oldData = series.points, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, names = xAxis && xAxis.categories && !xAxis.categories.length ? [] : null, i; // reset properties series.xIncrement = null; series.pointRange = xAxis && xAxis.categories ? 1 : options.pointRange; series.colorCounter = 0; // for series with colorByPoint (#1547) // parallel arrays var xData = [], yData = [], zData = [], dataLength = data ? data.length : [], turboThreshold = options.turboThreshold || 1000, pt, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length, hasToYData = !!series.toYData; // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers var x = pick(options.pointStart, 0), pointInterval = pick(options.pointInterval, 1); for (i = 0; i < dataLength; i++) { xData[i] = x; yData[i] = data[i]; x += pointInterval; } series.xIncrement = x; } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } /* else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode }*/ } else { for (i = 0; i < dataLength; i++) { if (data[i] !== UNDEFINED) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); xData[i] = pt.x; yData[i] = hasToYData ? series.toYData(pt) : pt.y; zData[i] = pt.z; if (names && pt.name) { names[i] = pt.name; } } } } // Unsorted data is not supported by the line tooltip as well as data grouping and // navigation in Stock charts (#725) if (series.requireSorting && xData.length > 1 && xData[1] < xData[0]) { error(15); } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = data; series.xData = xData; series.yData = yData; series.zData = zData; series.names = names; // destroy old points i = (oldData && oldData.length) || 0; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(false); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var series = this, chart = series.chart; redraw = pick(redraw, true); if (!series.isRemoving) { /* prevent triggering native event in jQuery (calling the remove function from the remove event) */ series.isRemoving = true; // fire the event with a default handler of removing the point fireEvent(series, 'remove', null, function () { // destroy elements series.destroy(); // redraw chart.isDirtyLegend = chart.isDirtyBox = true; if (redraw) { chart.redraw(animation); } }); } series.isRemoving = false; }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, cropStart = 0, cropEnd = dataLength, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, isCartesian = series.isCartesian; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { var extremes = xAxis.getExtremes(), min = extremes.min, max = extremes.max; // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (processedXData[i] >= min) { cropStart = mathMax(0, i - 1); break; } } // proceed to find slice end for (; i < dataLength; i++) { if (processedXData[i] > max) { cropEnd = i + 1; break; } } processedXData = processedXData.slice(cropStart, cropEnd); processedYData = processedYData.slice(cropStart, cropEnd); cropped = true; } } // Find the closest distance between processed points for (i = processedXData.length - 1; i > 0; i--) { distance = processedXData[i] - processedXData[i - 1]; if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) { closestPointRange = distance; } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = closestPointRange || 1; } series.closestPointRange = closestPointRange; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function () { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, pointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== UNDEFINED) { // #970 data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); } } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, isBottomSeries, allStackSeries, i, placeBetween = options.pointPlacement === 'between', threshold = options.threshold; //nextSeriesDown; // Is it the last visible series? (#809, #1722). // TODO: After merging in the 'stacking' branch, this logic should probably be moved to Chart.getStacks allStackSeries = yAxis.series.sort(function (a, b) { return a.index - b.index; }); i = allStackSeries.length; while (i--) { if (allStackSeries[i].visible) { if (allStackSeries[i] === series) { // #809 isBottomSeries = true; } break; } } // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = yAxis.stacks[(yValue < threshold ? '-' : '') + series.stackKey], pointStack, pointStackTotal; // Discard disallowed y values for log axes if (yAxis.isLog && yValue <= 0) { point.y = yValue = null; } // Get the plotX translation point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, placeBetween); // Math.round fixes #591 // Calculate the bottom y value for stacked series if (stacking && series.visible && stack && stack[xValue]) { pointStack = stack[xValue]; pointStackTotal = pointStack.total; pointStack.cum = yBottom = pointStack.cum - yValue; // start from top yValue = yBottom + yValue; if (isBottomSeries) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } if (stacking === 'percent') { yBottom = pointStackTotal ? yBottom * 100 / pointStackTotal : 0; yValue = pointStackTotal ? yValue * 100 / pointStackTotal : 0; } point.percentage = pointStackTotal ? point.y * 100 / pointStackTotal : 0; point.total = point.stackTotal = pointStackTotal; point.stackY = yValue; } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = (typeof yValue === 'number' && yValue !== Infinity) ? mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591 UNDEFINED; // Set client related positions for mouse tracking point.clientX = placeBetween ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; } // now that we have the cropped data, build the segments series.getSegments(); }, /** * Memoize tooltip texts and positions */ setTooltipPoints: function (renew) { var series = this, points = [], pointsLength, low, high, xAxis = series.xAxis, axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar point, i, tooltipPoints = []; // a lookup array for each pixel in the x dimension // don't waste resources if tracker is disabled if (series.options.enableMouseTracking === false) { return; } // renew if (renew) { series.tooltipPoints = null; } // concat segments to overcome null values each(series.segments || series.points, function (segment) { points = points.concat(segment); }); // Reverse the points in case the X axis is reversed if (xAxis && xAxis.reversed) { points = points.reverse(); } // Assign each pixel position to the nearest point pointsLength = points.length; for (i = 0; i < pointsLength; i++) { point = points[i]; // Set this range's low to the last range's high plus one low = points[i - 1] ? high + 1 : 0; // Now find the new high high = points[i + 1] ? mathMax(0, mathFloor((point.clientX + (points[i + 1] ? points[i + 1].clientX : axisLength)) / 2)) : axisLength; while (low >= 0 && low <= high) { tooltipPoints[low++] = point; } } series.tooltipPoints = tooltipPoints; }, /** * Format the header of the tooltip */ tooltipHeaderFormatter: function (point) { var series = this, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, dateTimeLabelFormats = tooltipOptions.dateTimeLabelFormats, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime', headerFormat = tooltipOptions.headerFormat, closestPointRange = xAxis && xAxis.closestPointRange, n; // Guess the best date format based on the closest point distance (#568) if (isDateTime && !xDateFormat) { if (closestPointRange) { for (n in timeUnits) { if (timeUnits[n] >= closestPointRange) { xDateFormat = dateTimeLabelFormats[n]; break; } } } else { xDateFormat = dateTimeLabelFormats.day; } } // Insert the header date format if any if (isDateTime && xDateFormat && isNumber(point.key)) { headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(headerFormat, { point: point, series: series }); }, /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); chart.hoverSeries = null; }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, renderer = chart.renderer, clipRect, markerClipRect, animation = series.options.animation, clipBox = chart.clipBox, inverted = chart.inverted, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } sharedClipKey = '_sharedClip' + animation.duration + animation.easing; // Initialize the animation. Set up the clipping rectangle. if (init) { // If a clipping rectangle with the same properties is currently present in the chart, use that. clipRect = chart[sharedClipKey]; markerClipRect = chart[sharedClipKey + 'm']; if (!clipRect) { chart[sharedClipKey] = clipRect = renderer.clipRect( extend(clipBox, { width: 0 }) ); chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } series.group.clip(clipRect); series.markerGroup.clip(markerClipRect); series.sharedClipKey = sharedClipKey; // Run the animation } else { clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animation.duration); } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { var chart = this.chart, sharedClipKey = this.sharedClipKey, group = this.group; if (group && this.options.clip !== false) { group.clip(chart.clipRect); this.markerGroup.clip(); // no clip } // Remove the shared clipping rectancgle when all series are shown setTimeout(function () { if (sharedClipKey && chart[sharedClipKey]) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } }, 100); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, pointMarkerOptions, enabled, isInside, markerGroup = series.markerGroup; if (seriesMarkerOptions.enabled || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = point.plotX; plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; enabled = (seriesMarkerOptions.enabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = chart.isInsidePlot(mathRound(plotX), plotY, chart.inverted); // #1858 // only draw the point if y is defined if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic .attr({ // Since the marker group isn't clipped, each individual marker must be toggled visibility: isInside ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN }) .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, seriesOptions = series.options, normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions, negativeColor = seriesOptions.negativeColor, key; // series type specific modifications if (seriesOptions.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + 2; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } if (point.negative && negativeColor) { point.color = point.fillColor = negativeColor; } hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!seriesOptions.marker) { // column, bar, point // if no hover color is given, brighten the normal color pointStateOptionsHover.color = Color(pointStateOptionsHover.color || point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness).get(); } // normal point state inherits series wide normal state pointAttr[NORMAL_STATE] = series.convertAttribs(extend({ color: point.color // #868 }, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // Force the fill to negativeColor on markers if (point.negative && seriesOptions.marker && negativeColor) { pointAttr[NORMAL_STATE].fill = pointAttr[HOVER_STATE].fill = pointAttr[SELECT_STATE].fill = series.convertAttribs({ fillColor: negativeColor }).fill; } // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type; // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, newOptions); // Destroy the series and reinsert methods from the type prototype this.remove(false); extend(this, seriesTypes[newOptions.type || oldType].prototype); this.init(chart, newOptions); if (pick(redraw, true)) { chart.redraw(false); } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(['xAxis', 'yAxis'], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // destroy all SVGElements associated to the series each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker', 'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) { if (series[prop]) { // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } }); // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Draw the data labels */ drawDataLabels: function () { var series = this, seriesOptions = series.options, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, str, dataLabelsGroup; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', series.visible ? VISIBLE : HIDDEN, options.zIndex || 6 ); // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true; // Determine if each data label is enabled pointOptions = point.options && point.options.dataLabels; enabled = generalOptions.enabled || (pointOptions && pointOptions.enabled); // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { rotation = options.rotation; // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color options.style.color = pick(options.color, options.style.color, series.color, 'black'); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -999, null, null, null, options.useHTML ) .attr(attr) .css(options.style) .add(dataLabelsGroup) .shadow(options.shadow); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }, /** * Align each individual data label */ alignDataLabel: function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -999), plotY = pick(point.plotY, -999), bBox = dataLabel.getBBox(), alignAttr; // the final position; // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: mathRound(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (options.rotation) { // Fancy box alignment isn't supported for rotated text alignAttr = { align: options.align, x: alignTo.x + options.x + alignTo.width / 2, y: alignTo.y + options.y + alignTo.height / 2 }; dataLabel[isNew ? 'attr' : 'animate'](alignAttr); } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; } // Show or hide based on the final aligned position dataLabel.attr({ visibility: options.crop === false || /*chart.isInsidePlot(alignAttr.x, alignAttr.y) || */chart.isInsidePlot(plotX, plotY, inverted) ? (chart.renderer.isSVG ? 'inherit' : VISIBLE) : HIDDEN }); }, /** * Return the graph path of a segment */ getSegmentPath: function (segment) { var series = this, segmentPath = [], step = series.options.step; // build the segment line each(segment, function (point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint; if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i)); } else { // moveTo or lineTo segmentPath.push(i ? L : M); // step line? if (step && i) { lastPoint = segment[i - 1]; if (step === 'right') { segmentPath.push( lastPoint.plotX, plotY ); } else if (step === 'center') { segmentPath.push( (lastPoint.plotX + plotX) / 2, lastPoint.plotY, (lastPoint.plotX + plotX) / 2, plotY ); } else { segmentPath.push( plotX, lastPoint.plotY ); } } // normal line to next point segmentPath.push( point.plotX, point.plotY ); } }); return segmentPath; }, /** * Get the graph path */ getGraphPath: function () { var series = this, graphPath = [], segmentPath, singlePoints = []; // used in drawTracker // Divide into segments and build graph and area paths each(series.segments, function (segment) { segmentPath = series.getSegmentPath(segment); // add the segment to the graph, or a single point for tracking if (segment.length > 1) { graphPath = graphPath.concat(segmentPath); } else { singlePoints.push(segment[0]); } }); // Record it for use in drawGraph and drawTracker, and return graphPath series.singlePoints = singlePoints; series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function () { var series = this, options = this.options, props = [['graph', options.lineColor || this.color]], lineWidth = options.lineWidth, dashStyle = options.dashStyle, graphPath = this.getGraphPath(), negativeColor = options.negativeColor; if (negativeColor) { props.push(['graphNeg', negativeColor]); } // draw the graph each(props, function (prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { stop(graph); // cancel running animations, #459 graph.animate({ d: graphPath }); } else if (lineWidth && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, zIndex: 1 // #1069 }; if (dashStyle) { attribs.dashstyle = dashStyle; } series[graphKey] = series.chart.renderer.path(graphPath) .attr(attribs) .add(series.group) .shadow(!i && options.shadow); } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ clipNeg: function () { var options = this.options, chart = this.chart, renderer = chart.renderer, negativeColor = options.negativeColor, translatedThreshold, posAttr, negAttr, graph = this.graph, area = this.area, posClip = this.posClip, negClip = this.negClip, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartSizeMax = mathMax(chartWidth, chartHeight), above, below; if (negativeColor && (graph || area)) { translatedThreshold = mathCeil(this.yAxis.len - this.yAxis.translate(options.threshold || 0)); above = { x: 0, y: 0, width: chartSizeMax, height: translatedThreshold }; below = { x: 0, y: translatedThreshold, width: chartSizeMax, height: chartSizeMax - translatedThreshold }; if (chart.inverted && renderer.isVML) { above = { x: chart.plotWidth - translatedThreshold - chart.plotLeft, y: 0, width: chartWidth, height: chartHeight }; below = { x: translatedThreshold + chart.plotLeft - chartWidth, y: 0, width: chart.plotLeft + translatedThreshold, height: chartWidth }; } if (this.yAxis.reversed) { posAttr = below; negAttr = above; } else { posAttr = above; negAttr = below; } if (posClip) { // update posClip.animate(posAttr); negClip.animate(negAttr); } else { this.posClip = posClip = renderer.clipRect(posAttr); this.negClip = negClip = renderer.clipRect(negAttr); if (graph) { graph.clip(posClip); this.graphNeg.clip(negClip); } if (area) { area.clip(posClip); this.areaNeg.clip(negClip); } } } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function () { var series = this, chart = series.chart; // Pie, go away (#1736) if (!series.xAxis) { return; } // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group, chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Generate it on first call if (isNew) { this[prop] = group = chart.renderer.g(name) .attr({ visibility: visibility, zIndex: zIndex || 0.1 // IE8 needs this }) .add(parent); } // Place it on first and subsequent (redraw) calls group[isNew ? 'attr' : 'animate']({ translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }); return group; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, doAnimation = animation && !!series.animate && chart.renderer.isSVG, // this animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE visibility = series.visible ? VISIBLE : HIDDEN, zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (doAnimation) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089, #1795) group.inverted = series.isCartesian ? chart.inverted : false; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.clipNeg(); } // draw the data labels (inn pies they go before the points) series.drawDataLabels(); // draw the points series.drawPoints(); // draw the mouse tracking area if (series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (doAnimation) { series.animate(); } else if (!hasRendered) { series.afterAnimate(); } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function () { var series = this, chart = series.chart, wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); series.setTooltipPoints(true); series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, graphNeg = series.graphNeg, stateOptions = options.states, lineWidth = options.lineWidth, attribs; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + 1; } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML attribs = { 'stroke-width': lineWidth }; // use attr because animate will cause any other animation on the graph to stop graph.attr(attribs); if (graphNeg) { graphNeg.attr(attribs); } } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTracker: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, singlePoint, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = tracker = renderer.path(trackerPath) .attr({ 'class': PREFIX + 'tracker', 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css) .add(series.markerGroup); if (hasTouch) { tracker.on('touchstart', onMouseOver); } } } }; // end Series prototype /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for area */ defaultPlotOptions.area = merge(defaultSeriesOptions, { threshold: 0 // trackByArea: false, // lineColor: null, // overrides color, but lets fillColor be unaltered // fillOpacity: 0.75, // fillColor: null }); /** * AreaSeries object */ var AreaSeries = extendClass(Series, { type: 'area', /** * For stacks, don't split segments on null values. Instead, draw null values with * no marker. Also insert dummy points for any X position that exists in other series * in the stack. */ getSegments: function () { var segments = [], segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, plotX, plotY, points = this.points, i, x; if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue // Create a map where we can quickly look up the points by their X value. for (i = 0; i < points.length; i++) { pointMap[points[i].x] = points[i]; } // Sort the keys (#1651) for (x in stack) { keys.push(+x); } keys.sort(function (a, b) { return a - b; }); each(keys, function (x) { // The point exists, push it to the segment if (pointMap[x]) { segment.push(pointMap[x]); // There is no point for this X value in this series, so we // insert a dummy point in order for the areas to be drawn // correctly. } else { plotX = xAxis.translate(x); plotY = yAxis.toPixels(stack[x].cum, true); segment.push({ y: null, plotX: plotX, clientX: plotX, plotY: plotY, yBottom: plotY, onMouseOver: noop }); } }); if (segment.length) { segments.push(segment); } } else { Series.prototype.getSegments.call(this); segments = this.segments; } this.segments = segments; }, /** * Extend the base Series getSegmentPath method by adding the path for the area. * This path is pushed to the series.areaPath property. */ getSegmentPath: function (segment) { var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path i, options = this.options, segLength = segmentPath.length; if (segLength === 3) { // for animation from 1 to two points areaSegmentPath.push(L, segmentPath[1], segmentPath[2]); } if (options.stacking && !this.closedStacks) { // Follow stack back. Todo: implement areaspline. A general solution could be to // reverse the entire graphPath of the previous series, though may be hard with // splines and with series with different extremes for (i = segment.length - 1; i >= 0; i--) { // step line? if (i < segment.length - 1 && options.step) { areaSegmentPath.push(segment[i + 1].plotX, segment[i].yBottom); } areaSegmentPath.push(segment[i].plotX, segment[i].yBottom); } } else { // follow zero line back this.closeSegment(areaSegmentPath, segment); } this.areaPath = this.areaPath.concat(areaSegmentPath); return segmentPath; }, /** * Extendable method to close the segment path of an area. This is overridden in polar * charts. */ closeSegment: function (path, segment) { var translatedThreshold = this.yAxis.getThreshold(this.options.threshold); path.push( L, segment[segment.length - 1].plotX, translatedThreshold, L, segment[0].plotX, translatedThreshold ); }, /** * Draw the graph and the underlying area. This method calls the Series base * function and adds the area. The areaPath is calculated in the getSegmentPath * method called from Series.prototype.drawGraph. */ drawGraph: function () { // Define or reset areaPath this.areaPath = []; // Call the base method Series.prototype.drawGraph.apply(this); // Define local variables var series = this, areaPath = this.areaPath, options = this.options, negativeColor = options.negativeColor, props = [['area', this.color, options.fillColor]]; // area name, main color, fill color if (negativeColor) { props.push(['areaNeg', options.negativeColor, options.negativeFillColor]); } each(props, function (prop) { var areaKey = prop[0], area = series[areaKey]; // Create or update the area if (area) { // update area.animate({ d: areaPath }); } else { // create series[areaKey] = series.chart.renderer.path(areaPath) .attr({ fill: pick( prop[2], Color(prop[1]).setOpacity(options.fillOpacity || 0.75).get() ), zIndex: 0 // #1069 }).add(series.group); } }); }, /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawLegendSymbol: function (legend, item) { item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 11, legend.options.symbolWidth, 12, 2 ).attr({ zIndex: 3 }).add(item.legendGroup); } }); seriesTypes.area = AreaSeries;/** * Set the default options for spline */ defaultPlotOptions.spline = merge(defaultSeriesOptions); /** * SplineSeries object */ var SplineSeries = extendClass(Series, { type: 'spline', /** * Get the spline segment from a given point's previous neighbour to the given point */ getPointSpline: function (segment, point, i) { var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = segment[i - 1], nextPoint = segment[i + 1], leftContX, leftContY, rightContX, rightContY, ret; // find control points if (lastPoint && nextPoint) { var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; // have the two control points make a straight line through main point correction = ((rightContY - leftContY) * (rightContX - plotX)) / (rightContX - leftContX) + plotY - rightContY; leftContY += correction; rightContY += correction; // to prevent false extremes, check that control points are between // neighbouring points' y values if (leftContY > lastY && leftContY > plotY) { leftContY = mathMax(lastY, plotY); rightContY = 2 * plotY - leftContY; // mirror of left control point } else if (leftContY < lastY && leftContY < plotY) { leftContY = mathMin(lastY, plotY); rightContY = 2 * plotY - leftContY; } if (rightContY > nextY && rightContY > plotY) { rightContY = mathMax(nextY, plotY); leftContY = 2 * plotY - rightContY; } else if (rightContY < nextY && rightContY < plotY) { rightContY = mathMin(nextY, plotY); leftContY = 2 * plotY - rightContY; } // record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // Visualize control points for debugging /* if (leftContX) { this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2) .attr({ stroke: 'red', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'red', 'stroke-width': 1 }) .add(); this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2) .attr({ stroke: 'green', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'green', 'stroke-width': 1 }) .add(); } */ // moveTo or lineTo if (!i) { ret = [M, plotX, plotY]; } else { // curve from last point to this ret = [ 'C', lastPoint.rightContX || lastPoint.plotX, lastPoint.rightContY || lastPoint.plotY, leftContX || plotX, leftContY || plotY, plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later } return ret; } }); seriesTypes.spline = SplineSeries; /** * Set the default options for areaspline */ defaultPlotOptions.areaspline = merge(defaultPlotOptions.area); /** * AreaSplineSeries object */ var areaProto = AreaSeries.prototype, AreaSplineSeries = extendClass(SplineSeries, { type: 'areaspline', closedStacks: true, // instead of following the previous graph back, follow the threshold back // Mix in methods from the area series getSegmentPath: areaProto.getSegmentPath, closeSegment: areaProto.closeSegment, drawGraph: areaProto.drawGraph }); seriesTypes.areaspline = AreaSplineSeries; /** * Set the default options for column */ defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { brightness: 0.1, shadow: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, stickyTracking: false, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', tooltipOutsidePlot: true, requireSorting: false, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color', r: 'borderRadius' }, trackerGroups: ['group', 'dataLabelsGroup'], /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function () { var series = this, chart = series.chart, options = series.options, xAxis = this.xAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, columnIndex, columnCount = 0; // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(chart.series, function (otherSeries) { var otherOptions = otherSeries.options; if (otherSeries.type === series.type && otherSeries.visible && series.options.group === otherOptions.group) { // used in Stock charts navigator series if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } var categoryWidth = mathMin( mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || 1), xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, optionPointWidth = options.pointWidth, pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 : pointOffsetWidth * options.pointPadding, pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts colIndex = (reversedXAxis ? columnCount - (series.columnIndex || 0) : // #1251 series.columnIndex) || 0, pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1); // Save it for reading in linked series (Error bars particularly) return (series.columnMetrics = { width: pointWidth, offset: pointXOffset }); }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, stacking = options.stacking, borderWidth = options.borderWidth, yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width pointXOffset = metrics.offset; Series.prototype.translate.apply(series); // record the new values each(series.points, function (point) { var plotY = mathMin(mathMax(-999, point.plotY), yAxis.len + 999), // Don't draw too far outside plot area (#1303) yBottom = pick(point.yBottom, translatedThreshold), barX = point.plotX + pointXOffset, barY = mathCeil(mathMin(plotY, yBottom)), barH = mathCeil(mathMax(plotY, yBottom) - barY), stack = yAxis.stacks[(point.y < 0 ? '-' : '') + series.stackKey], shapeArgs; // Record the offset'ed position and width of the bar to be able to align the stacking total correctly if (stacking && series.visible && stack && stack[point.x]) { stack[point.x].setOffset(pointXOffset, barW); } // handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; barY = mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0); // use exact yAxis.translation (#1485) } } point.barX = barX; point.pointWidth = pointWidth; // create shape type and shape args that are reused in drawPoints and drawTracker point.shapeType = 'rect'; point.shapeArgs = shapeArgs = chart.renderer.Element.prototype.crisp.call(0, borderWidth, barX, barY, barW, barH); if (borderWidth % 2) { // correct for shorting in crisp method, visible in stacked columns with 1px border shapeArgs.y -= 1; shapeArgs.height += 1; } }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, options = series.options, renderer = series.chart.renderer, shapeArgs; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; if (graphic) { // update stop(graphic); graphic.animate(merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]) .add(series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ drawTracker: function () { var series = this, pointer = series.chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; series.onMouseOver(); while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); } else { series._hasTracking = true; } }, /** * Override the basic data label alignment by adjusting for the position of the column */ alignDataLabel: function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)), inside = pick(options.inside, !!this.options.stacking); // draw it inside the box? // Align to the column itself, or the top of it if (dlBox) { // Area range uses this method but not alignTo alignTo = merge(dlBox); if (inverted) { alignTo = { x: chart.plotWidth - alignTo.y - alignTo.height, y: chart.plotHeight - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (hasSVG) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr.scaleY = 1; attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, series.options.animation); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for bar */ defaultPlotOptions.bar = merge(defaultPlotOptions.column); /** * The Bar series class */ var BarSeries = extendClass(ColumnSeries, { type: 'bar', inverted: true }); seriesTypes.bar = BarSeries; /** * Set the default options for scatter */ defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, tooltip: { headerFormat: '<span style="font-size: 10px; color:{series.color}">{series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>', followPointer: true }, stickyTracking: false }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['markerGroup'], drawTracker: ColumnSeries.prototype.drawTracker, setTooltipPoints: noop }); seriesTypes.scatter = ScatterSeries; /** * Set the default options for pie */ defaultPlotOptions.pie = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, center: [null, null], clip: false, colorByPoint: true, // always true for pies dataLabels: { // align: null, // connectorWidth: 1, // connectorColor: point.color, // connectorPadding: 5, distance: 30, enabled: true, formatter: function () { return this.point.name; } // softConnector: true, //y: 0 }, ignoreHiddenPoint: true, //innerSize: 0, legendType: 'point', marker: null, // point options are specified in the base options size: null, showInLegend: false, slicedOffset: 10, states: { hover: { brightness: 0.1, shadow: false } }, stickyTracking: false, tooltip: { followPointer: true } }); /** * Extended point object for pies */ var PiePoint = extendClass(Point, { /** * Initiate the pie slice */ init: function () { Point.prototype.init.apply(this, arguments); var point = this, toggleSlice; // Disallow negative values (#1530) if (point.y < 0) { point.y = null; } //visible: options.visible !== false, extend(point, { visible: point.visible !== false, name: pick(point.name, 'Slice') }); // add event listener for select toggleSlice = function () { point.slice(); }; addEvent(point, 'select', toggleSlice); addEvent(point, 'unselect', toggleSlice); return point; }, /** * Toggle the visibility of the pie slice * @param {Boolean} vis Whether to show the slice or not. If undefined, the * visibility is toggled */ setVisible: function (vis) { var point = this, series = point.series, chart = series.chart, method; // if called without an argument, toggle visibility point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data method = vis ? 'show' : 'hide'; // Show and hide associated elements each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) { if (point[key]) { point[key][method](); } }); if (point.legendItem) { chart.legend.colorizeItem(point, vis); } // Handle ignore hidden slices if (!series.isDirty && series.options.ignoreHiddenPoint) { series.isDirty = true; chart.redraw(); } }, /** * Set or toggle whether the slice is cut out from the pie * @param {Boolean} sliced When undefined, the slice state is toggled * @param {Boolean} redraw Whether to redraw the chart. True by default. */ slice: function (sliced, redraw, animation) { var point = this, series = point.series, chart = series.chart, translation; setAnimation(animation, chart); // redraw is true by default redraw = pick(redraw, true); // if called without an argument, toggle point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data translation = sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; point.graphic.animate(translation); if (point.shadowGroup) { point.shadowGroup.animate(translation); } } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'dataLabelsGroup'], pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, /** * Pies have one color each point */ getColor: noop, /** * Animate the pies in */ animate: function (init) { var series = this, points = series.points, startAngleRad = series.startAngleRad; if (!init) { each(points, function (point) { var graphic = point.graphic, args = point.shapeArgs; if (graphic) { // start values graphic.attr({ r: series.center[3] / 2, // animate from inner radius (#779) start: startAngleRad, end: startAngleRad }); // animate graphic.animate({ r: args.r, start: args.start, end: args.end }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; } }, /** * Extend the basic setData method by running processData and generatePoints immediately, * in order to access the points from the legend. */ setData: function (data, redraw) { Series.prototype.setData.call(this, data, false); this.processData(); this.generatePoints(); if (pick(redraw, true)) { this.chart.redraw(); } }, /** * Get the center of the pie based on the size and center options relative to the * plot area. Borrowed by the polar and gauge series types. */ getCenter: function () { var options = this.options, chart = this.chart, slicingRoom = 2 * (options.slicedOffset || 0), handleSlicingRoom, plotWidth = chart.plotWidth - 2 * slicingRoom, plotHeight = chart.plotHeight - 2 * slicingRoom, centerOption = options.center, positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0], smallestSize = mathMin(plotWidth, plotHeight), isPercent; return map(positions, function (length, i) { isPercent = /%$/.test(length); handleSlicingRoom = i < 2 || (i === 2 && isPercent); return (isPercent ? // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize // i == 4: innerSize, relative to smallestSize [plotWidth, plotHeight, smallestSize, smallestSize][i] * pInt(length) / 100 : length) + (handleSlicingRoom ? slicingRoom : 0); }); }, /** * Do translation for pie slices */ translate: function (positions) { this.generatePoints(); var total = 0, series = this, cumulative = 0, precision = 1000, // issue #172 options = series.options, slicedOffset = options.slicedOffset, connectorOffset = slicedOffset + options.borderWidth, start, end, angle, startAngleRad = series.startAngleRad = mathPI / 180 * ((options.startAngle || 0) % 360 - 90), points = series.points, circ = 2 * mathPI, fraction, radiusX, // the x component of the radius vector for a given point radiusY, labelDistance = options.dataLabels.distance, ignoreHiddenPoint = options.ignoreHiddenPoint, i, len = points.length, point; // Get positions - either an integer or a percentage string must be given. // If positions are passed as a parameter, we're in a recursive loop for adjusting // space for data labels. if (!positions) { series.center = positions = series.getCenter(); } // utility for getting the x value from a given y, used for anticollision logic in data labels series.getX = function (y, left) { angle = math.asin((y - positions[1]) / (positions[2] / 2 + labelDistance)); return positions[0] + (left ? -1 : 1) * (mathCos(angle) * (positions[2] / 2 + labelDistance)); }; // get the total sum for (i = 0; i < len; i++) { point = points[i]; total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y; } // Calculate the geometry for each point for (i = 0; i < len; i++) { point = points[i]; // set start and end angle fraction = total ? point.y / total : 0; start = mathRound((startAngleRad + (cumulative * circ)) * precision) / precision; if (!ignoreHiddenPoint || point.visible) { cumulative += fraction; } end = mathRound((startAngleRad + (cumulative * circ)) * precision) / precision; // set the shape point.shapeType = 'arc'; point.shapeArgs = { x: positions[0], y: positions[1], r: positions[2] / 2, innerR: positions[3] / 2, start: start, end: end }; // center for the sliced out slice angle = (end + start) / 2; if (angle > 0.75 * circ) { angle -= 2 * mathPI; } point.slicedTranslation = { translateX: mathRound(mathCos(angle) * slicedOffset), translateY: mathRound(mathSin(angle) * slicedOffset) }; // set the anchor point for tooltips radiusX = mathCos(angle) * positions[2] / 2; radiusY = mathSin(angle) * positions[2] / 2; point.tooltipPos = [ positions[0] + radiusX * 0.7, positions[1] + radiusY * 0.7 ]; point.half = angle < circ / 4 ? 0 : 1; point.angle = angle; // set the anchor point for data labels connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678 point.labelPos = [ positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a positions[0] + radiusX, // landing point for connector positions[1] + radiusY, // a/a labelDistance < 0 ? // alignment 'center' : point.half ? 'right' : 'left', // alignment angle // center angle ]; // API properties point.percentage = fraction * 100; point.total = total; } this.setTooltipPoints(); }, drawGraph: null, /** * Draw the data points */ drawPoints: function () { var series = this, chart = series.chart, renderer = chart.renderer, groupTranslation, //center, graphic, //group, shadow = series.options.shadow, shadowGroup, shapeArgs; if (shadow && !series.shadowGroup) { series.shadowGroup = renderer.g('shadow') .add(series.group); } // draw the slices each(series.points, function (point) { graphic = point.graphic; shapeArgs = point.shapeArgs; shadowGroup = point.shadowGroup; // put the shadow behind all points if (shadow && !shadowGroup) { shadowGroup = point.shadowGroup = renderer.g('shadow') .add(series.shadowGroup); } // if the point is sliced, use special translation, else use plot area traslation groupTranslation = point.sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; //group.translate(groupTranslation[0], groupTranslation[1]); if (shadowGroup) { shadowGroup.attr(groupTranslation); } // draw the slice if (graphic) { graphic.animate(extend(shapeArgs, groupTranslation)); } else { point.graphic = graphic = renderer.arc(shapeArgs) .setRadialReference(series.center) .attr( point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] ) .attr({ 'stroke-linejoin': 'round' }) .attr(groupTranslation) .add(series.group) .shadow(shadow, shadowGroup); } // detect point specific visibility if (point.visible === false) { point.setVisible(false); } }); }, /** * Override the base drawDataLabels method by pie specific functionality */ drawDataLabels: function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i, j, overflow = [0, 0, 0, 0], // top, right, bottom, left sort = function (a, b) { return b.y - a.y; }, sortByAngle = function (points, sign) { points.sort(function (a, b) { return a.angle !== undefined && (b.angle - a.angle) * sign; }); }; // get out if not enabled if (!options.enabled && !series._hasPointLabels) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); // arrange points for detection collision each(data, function (point) { if (point.dataLabel) { // it may have been cancelled in the base method (#407) halves[point.half].push(point); } }); // assume equal label heights i = 0; while (!labelHeight && data[i]) { // #1569 labelHeight = data[i] && data[i].dataLabel && (data[i].dataLabel.getBBox().height || 21); // 21 is for #968 i++; } /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ i = 2; while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, length = points.length, slotIndex; // Sort by angle sortByAngle(points, i - 0.5); // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // build the slots for (pos = centerY - radius - distanceOption; pos <= centerY + radius + distanceOption; pos += labelHeight) { slots.push(pos); // visualize the slot /* var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver' }) .add(); chart.renderer.text('Slot '+ (slots.length - 1), slotX, slotY + 4) .attr({ fill: 'silver' }).add(); } */ } slotsLength = slots.length; // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : VISIBLE; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = naturalY; } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(slotIndex === 0 || slotIndex === slots.length - 1 ? naturalY : y, i); // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; dataLabel.connX = x; dataLabel.connY = y; // Detect overflowing data labels if (this.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point } // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function (point) { connector = point.connector; labelPos = point.labelPos; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos) { visibility = dataLabel._attr.visibility; x = dataLabel.connX; y = dataLabel.connY; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility }) .add(series.group); } } else if (connector) { point.connector = connector.destroy(); } }); } } }, /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ verifyDataLabelOverflow: function (overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = mathMax( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = mathMax( mathMin( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; this.translate(center); each(this.points, function (point) { if (point.dataLabel) { point.dataLabel._pos = null; // reset } }); this.drawDataLabels(); // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }, /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ placeDataLabels: function () { each(this.points, function (point) { var dataLabel = point.dataLabel, _pos; if (dataLabel) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -999 }); } } }); }, alignDataLabel: noop, /** * Draw point specific tracker objects. Inherit directly from column series. */ drawTracker: ColumnSeries.prototype.drawTracker, /** * Use a simple symbol from column prototype */ drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol, /** * Pies don't have point marker symbols */ getSymbol: noop }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; // global variables extend(Highcharts, { // Constructors Axis: Axis, Chart: Chart, Color: Color, Legend: Legend, Pointer: Pointer, Point: Point, Tick: Tick, Tooltip: Tooltip, Renderer: Renderer, Series: Series, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, numberFormat: numberFormat, seriesTypes: seriesTypes, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, extend: extend, map: map, merge: merge, pick: pick, splat: splat, extendClass: extendClass, pInt: pInt, wrap: wrap, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); }());
JavaScript
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highcharts JS v3.0.2 (2013-06-05) * * (c) 2009-2013 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, HighchartsAdapter, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console */ (function (Highcharts, UNDEFINED) { var arrayMin = Highcharts.arrayMin, arrayMax = Highcharts.arrayMax, each = Highcharts.each, extend = Highcharts.extend, merge = Highcharts.merge, map = Highcharts.map, pick = Highcharts.pick, pInt = Highcharts.pInt, defaultPlotOptions = Highcharts.getOptions().plotOptions, seriesTypes = Highcharts.seriesTypes, extendClass = Highcharts.extendClass, splat = Highcharts.splat, wrap = Highcharts.wrap, Axis = Highcharts.Axis, Tick = Highcharts.Tick, Series = Highcharts.Series, colProto = seriesTypes.column.prototype, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMin = math.min, mathMax = math.max, noop = function () {};/** * The Pane object allows options that are common to a set of X and Y axes. * * In the future, this can be extended to basic Highcharts and Highstock. */ function Pane(options, chart, firstAxis) { this.init.call(this, options, chart, firstAxis); } // Extend the Pane prototype extend(Pane.prototype, { /** * Initiate the Pane object */ init: function (options, chart, firstAxis) { var pane = this, backgroundOption, defaultOptions = pane.defaultOptions; pane.chart = chart; // Set options if (chart.angular) { // gauges defaultOptions.background = {}; // gets extended by this.defaultBackgroundOptions } pane.options = options = merge(defaultOptions, options); backgroundOption = options.background; // To avoid having weighty logic to place, update and remove the backgrounds, // push them to the first axis' plot bands and borrow the existing logic there. if (backgroundOption) { each([].concat(splat(backgroundOption)).reverse(), function (config) { var backgroundColor = config.backgroundColor; // if defined, replace the old one (specific for gradients) config = merge(pane.defaultBackgroundOptions, config); if (backgroundColor) { config.backgroundColor = backgroundColor; } config.color = config.backgroundColor; // due to naming in plotBands firstAxis.options.plotBands.unshift(config); }); } }, /** * The default options object */ defaultOptions: { // background: {conditional}, center: ['50%', '50%'], size: '85%', startAngle: 0 //endAngle: startAngle + 360 }, /** * The default background options */ defaultBackgroundOptions: { shape: 'circle', borderWidth: 1, borderColor: 'silver', backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, '#FFF'], [1, '#DDD'] ] }, from: Number.MIN_VALUE, // corrected to axis min innerRadius: 0, to: Number.MAX_VALUE, // corrected to axis max outerRadius: '105%' } }); var axisProto = Axis.prototype, tickProto = Tick.prototype; /** * Augmented methods for the x axis in order to hide it completely, used for the X axis in gauges */ var hiddenAxisMixin = { getOffset: noop, redraw: function () { this.isDirty = false; // prevent setting Y axis dirty }, render: function () { this.isDirty = false; // prevent setting Y axis dirty }, setScale: noop, setCategories: noop, setTitle: noop }; /** * Augmented methods for the value axis */ /*jslint unparam: true*/ var radialAxisMixin = { isRadial: true, /** * The default options extend defaultYAxisOptions */ defaultRadialGaugeOptions: { labels: { align: 'center', x: 0, y: null // auto }, minorGridLineWidth: 0, minorTickInterval: 'auto', minorTickLength: 10, minorTickPosition: 'inside', minorTickWidth: 1, plotBands: [], tickLength: 10, tickPosition: 'inside', tickWidth: 2, title: { rotation: 0 }, zIndex: 2 // behind dials, points in the series group }, // Circular axis around the perimeter of a polar chart defaultRadialXOptions: { gridLineWidth: 1, // spokes labels: { align: null, // auto distance: 15, x: 0, y: null // auto }, maxPadding: 0, minPadding: 0, plotBands: [], showLastLabel: false, tickLength: 0 }, // Radial axis, like a spoke in a polar chart defaultRadialYOptions: { gridLineInterpolation: 'circle', labels: { align: 'right', x: -3, y: -2 }, plotBands: [], showLastLabel: false, title: { x: 4, text: null, rotation: 90 } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.defaultRadialOptions, userOptions ); }, /** * Wrap the getOffset method to return zero offset for title or labels in a radial * axis */ getOffset: function () { // Call the Axis prototype method (the method we're in now is on the instance) axisProto.getOffset.call(this); // Title or label offsets are not counted this.chart.axisOffset[this.side] = 0; // Set the center array this.center = this.pane.center = seriesTypes.pie.prototype.getCenter.call(this.pane); }, /** * Get the path for the axis line. This method is also referenced in the getPlotLinePath * method. */ getLinePath: function (lineWidth, radius) { var center = this.center; radius = pick(radius, center[2] / 2 - this.offset); return this.chart.renderer.symbols.arc( this.left + center[0], this.top + center[1], radius, radius, { start: this.startAngleRad, end: this.endAngleRad, open: true, innerR: 0 } ); }, /** * Override setAxisTranslation by setting the translation to the difference * in rotation. This allows the translate method to return angle for * any given value. */ setAxisTranslation: function () { // Call uber method axisProto.setAxisTranslation.call(this); // Set transA and minPixelPadding if (this.center) { // it's not defined the first time if (this.isCircular) { this.transA = (this.endAngleRad - this.startAngleRad) / ((this.max - this.min) || 1); } else { this.transA = (this.center[2] / 2) / ((this.max - this.min) || 1); } if (this.isXAxis) { this.minPixelPadding = this.transA * this.minPointOffset + (this.reversed ? (this.endAngleRad - this.startAngleRad) / 4 : 0); // ??? } } }, /** * In case of auto connect, add one closestPointRange to the max value right before * tickPositions are computed, so that ticks will extend passed the real max. */ beforeSetTickPositions: function () { if (this.autoConnect) { this.max += (this.categories && 1) || this.pointRange || this.closestPointRange; // #1197 } }, /** * Override the setAxisSize method to use the arc's circumference as length. This * allows tickPixelInterval to apply to pixel lengths along the perimeter */ setAxisSize: function () { axisProto.setAxisSize.call(this); if (this.center) { // it's not defined the first time this.len = this.width = this.height = this.isCircular ? this.center[2] * (this.endAngleRad - this.startAngleRad) / 2 : this.center[2] / 2; } }, /** * Returns the x, y coordinate of a point given by a value and a pixel distance * from center */ getPosition: function (value, length) { if (!this.isCircular) { length = this.translate(value); value = this.min; } return this.postTranslate( this.translate(value), pick(length, this.center[2] / 2) - this.offset ); }, /** * Translate from intermediate plotX (angle), plotY (axis.len - radius) to final chart coordinates. */ postTranslate: function (angle, radius) { var chart = this.chart, center = this.center; angle = this.startAngleRad + angle; return { x: chart.plotLeft + center[0] + Math.cos(angle) * radius, y: chart.plotTop + center[1] + Math.sin(angle) * radius }; }, /** * Find the path for plot bands along the radial axis */ getPlotBandPath: function (from, to, options) { var center = this.center, startAngleRad = this.startAngleRad, fullRadius = center[2] / 2, radii = [ pick(options.outerRadius, '100%'), options.innerRadius, pick(options.thickness, 10) ], percentRegex = /%$/, start, end, open, isCircular = this.isCircular, // X axis in a polar chart ret; // Polygonal plot bands if (this.options.gridLineInterpolation === 'polygon') { ret = this.getPlotLinePath(from).concat(this.getPlotLinePath(to, true)); // Circular grid bands } else { // Plot bands on Y axis (radial axis) - inner and outer radius depend on to and from if (!isCircular) { radii[0] = this.translate(from); radii[1] = this.translate(to); } // Convert percentages to pixel values radii = map(radii, function (radius) { if (percentRegex.test(radius)) { radius = (pInt(radius, 10) * fullRadius) / 100; } return radius; }); // Handle full circle if (options.shape === 'circle' || !isCircular) { start = -Math.PI / 2; end = Math.PI * 1.5; open = true; } else { start = startAngleRad + this.translate(from); end = startAngleRad + this.translate(to); } ret = this.chart.renderer.symbols.arc( this.left + center[0], this.top + center[1], radii[0], radii[0], { start: start, end: end, innerR: pick(radii[1], radii[0] - radii[2]), open: open } ); } return ret; }, /** * Find the path for plot lines perpendicular to the radial axis. */ getPlotLinePath: function (value, reverse) { var axis = this, center = axis.center, chart = axis.chart, end = axis.getPosition(value), xAxis, xy, tickPositions, ret; // Spokes if (axis.isCircular) { ret = ['M', center[0] + chart.plotLeft, center[1] + chart.plotTop, 'L', end.x, end.y]; // Concentric circles } else if (axis.options.gridLineInterpolation === 'circle') { value = axis.translate(value); if (value) { // a value of 0 is in the center ret = axis.getLinePath(0, value); } // Concentric polygons } else { xAxis = chart.xAxis[0]; ret = []; value = axis.translate(value); tickPositions = xAxis.tickPositions; if (xAxis.autoConnect) { tickPositions = tickPositions.concat([tickPositions[0]]); } // Reverse the positions for concatenation of polygonal plot bands if (reverse) { tickPositions = [].concat(tickPositions).reverse(); } each(tickPositions, function (pos, i) { xy = xAxis.getPosition(pos, value); ret.push(i ? 'L' : 'M', xy.x, xy.y); }); } return ret; }, /** * Find the position for the axis title, by default inside the gauge */ getTitlePosition: function () { var center = this.center, chart = this.chart, titleOptions = this.options.title; return { x: chart.plotLeft + center[0] + (titleOptions.x || 0), y: chart.plotTop + center[1] - ({ high: 0.5, middle: 0.25, low: 0 }[titleOptions.align] * center[2]) + (titleOptions.y || 0) }; } }; /*jslint unparam: false*/ /** * Override axisProto.init to mix in special axis instance functions and function overrides */ wrap(axisProto, 'init', function (proceed, chart, userOptions) { var axis = this, angular = chart.angular, polar = chart.polar, isX = userOptions.isX, isHidden = angular && isX, isCircular, startAngleRad, endAngleRad, options, chartOptions = chart.options, paneIndex = userOptions.pane || 0, pane, paneOptions; // Before prototype.init if (angular) { extend(this, isHidden ? hiddenAxisMixin : radialAxisMixin); isCircular = !isX; if (isCircular) { this.defaultRadialOptions = this.defaultRadialGaugeOptions; } } else if (polar) { //extend(this, userOptions.isX ? radialAxisMixin : radialAxisMixin); extend(this, radialAxisMixin); isCircular = isX; this.defaultRadialOptions = isX ? this.defaultRadialXOptions : merge(this.defaultYAxisOptions, this.defaultRadialYOptions); } // Run prototype.init proceed.call(this, chart, userOptions); if (!isHidden && (angular || polar)) { options = this.options; // Create the pane and set the pane options. if (!chart.panes) { chart.panes = []; } this.pane = pane = chart.panes[paneIndex] = chart.panes[paneIndex] || new Pane( splat(chartOptions.pane)[paneIndex], chart, axis ); paneOptions = pane.options; // Disable certain features on angular and polar axes chart.inverted = false; chartOptions.chart.zoomType = null; // Start and end angle options are // given in degrees relative to top, while internal computations are // in radians relative to right (like SVG). this.startAngleRad = startAngleRad = (paneOptions.startAngle - 90) * Math.PI / 180; this.endAngleRad = endAngleRad = (pick(paneOptions.endAngle, paneOptions.startAngle + 360) - 90) * Math.PI / 180; this.offset = options.offset || 0; this.isCircular = isCircular; // Automatically connect grid lines? if (isCircular && userOptions.max === UNDEFINED && endAngleRad - startAngleRad === 2 * Math.PI) { this.autoConnect = true; } } }); /** * Add special cases within the Tick class' methods for radial axes. */ wrap(tickProto, 'getPosition', function (proceed, horiz, pos, tickmarkOffset, old) { var axis = this.axis; return axis.getPosition ? axis.getPosition(pos) : proceed.call(this, horiz, pos, tickmarkOffset, old); }); /** * Wrap the getLabelPosition function to find the center position of the label * based on the distance option */ wrap(tickProto, 'getLabelPosition', function (proceed, x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, optionsY = labelOptions.y, ret, align = labelOptions.align, angle = (axis.translate(this.pos) + axis.startAngleRad + Math.PI / 2) / Math.PI * 180; if (axis.isRadial) { ret = axis.getPosition(this.pos, (axis.center[2] / 2) + pick(labelOptions.distance, -25)); // Automatically rotated if (labelOptions.rotation === 'auto') { label.attr({ rotation: angle }); // Vertically centered } else if (optionsY === null) { optionsY = pInt(label.styles.lineHeight) * 0.9 - label.getBBox().height / 2; } // Automatic alignment if (align === null) { if (axis.isCircular) { if (angle > 20 && angle < 160) { align = 'left'; // right hemisphere } else if (angle > 200 && angle < 340) { align = 'right'; // left hemisphere } else { align = 'center'; // top or bottom } } else { align = 'center'; } label.attr({ align: align }); } ret.x += labelOptions.x; ret.y += optionsY; } else { ret = proceed.call(this, x, y, label, horiz, labelOptions, tickmarkOffset, index, step); } return ret; }); /** * Wrap the getMarkPath function to return the path of the radial marker */ wrap(tickProto, 'getMarkPath', function (proceed, x, y, tickLength, tickWidth, horiz, renderer) { var axis = this.axis, endPoint, ret; if (axis.isRadial) { endPoint = axis.getPosition(this.pos, axis.center[2] / 2 + tickLength); ret = [ 'M', x, y, 'L', endPoint.x, endPoint.y ]; } else { ret = proceed.call(this, x, y, tickLength, tickWidth, horiz, renderer); } return ret; });/* * The AreaRangeSeries class * */ /** * Extend the default options with map options */ defaultPlotOptions.arearange = merge(defaultPlotOptions.area, { lineWidth: 1, marker: null, threshold: null, tooltip: { pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.low}</b> - <b>{point.high}</b><br/>' }, trackByArea: true, dataLabels: { verticalAlign: null, xLow: 0, xHigh: 0, yLow: 0, yHigh: 0 } }); /** * Add the series type */ seriesTypes.arearange = Highcharts.extendClass(seriesTypes.area, { type: 'arearange', pointArrayMap: ['low', 'high'], toYData: function (point) { return [point.low, point.high]; }, pointValKey: 'low', /** * Extend getSegments to force null points if the higher value is null. #1703. */ getSegments: function () { var series = this; each(series.points, function (point) { if (!series.options.connectNulls && (point.low === null || point.high === null)) { point.y = null; } else if (point.low === null && point.high !== null) { point.y = point.high; } }); Series.prototype.getSegments.call(this); }, /** * Translate data points from raw values x and y to plotX and plotY */ translate: function () { var series = this, yAxis = series.yAxis; seriesTypes.area.prototype.translate.apply(series); // Set plotLow and plotHigh each(series.points, function (point) { var low = point.low, high = point.high, plotY = point.plotY; if (high === null && low === null) { point.y = null; } else if (low === null) { point.plotLow = point.plotY = null; point.plotHigh = yAxis.toPixels(high, true); } else if (high === null) { point.plotLow = plotY; point.plotHigh = null; } else { point.plotLow = plotY; point.plotHigh = yAxis.toPixels(high, true); } }); }, /** * Extend the line series' getSegmentPath method by applying the segment * path to both lower and higher values of the range */ getSegmentPath: function (segment) { var lowSegment, highSegment = [], i = segment.length, baseGetSegmentPath = Series.prototype.getSegmentPath, point, linePath, lowerPath, options = this.options, step = options.step, higherPath; // Remove nulls from low segment lowSegment = HighchartsAdapter.grep(segment, function (point) { return point.plotLow !== null; }); // Make a segment with plotX and plotY for the top values while (i--) { point = segment[i]; if (point.plotHigh !== null) { highSegment.push({ plotX: point.plotX, plotY: point.plotHigh }); } } // Get the paths lowerPath = baseGetSegmentPath.call(this, lowSegment); if (step) { if (step === true) { step = 'left'; } options.step = { left: 'right', center: 'center', right: 'left' }[step]; // swap for reading in getSegmentPath } higherPath = baseGetSegmentPath.call(this, highSegment); options.step = step; // Create a line on both top and bottom of the range linePath = [].concat(lowerPath, higherPath); // For the area path, we need to change the 'move' statement into 'lineTo' or 'curveTo' higherPath[0] = 'L'; // this probably doesn't work for spline this.areaPath = this.areaPath.concat(lowerPath, higherPath); return linePath; }, /** * Extend the basic drawDataLabels method by running it for both lower and higher * values. */ drawDataLabels: function () { var data = this.data, length = data.length, i, originalDataLabels = [], seriesProto = Series.prototype, dataLabelOptions = this.options.dataLabels, point, inverted = this.chart.inverted; if (dataLabelOptions.enabled || this._hasPointLabels) { // Step 1: set preliminary values for plotY and dataLabel and draw the upper labels i = length; while (i--) { point = data[i]; // Set preliminary values point.y = point.high; point.plotY = point.plotHigh; // Store original data labels and set preliminary label objects to be picked up // in the uber method originalDataLabels[i] = point.dataLabel; point.dataLabel = point.dataLabelUpper; // Set the default offset point.below = false; if (inverted) { dataLabelOptions.align = 'left'; dataLabelOptions.x = dataLabelOptions.xHigh; } else { dataLabelOptions.y = dataLabelOptions.yHigh; } } seriesProto.drawDataLabels.apply(this, arguments); // #1209 // Step 2: reorganize and handle data labels for the lower values i = length; while (i--) { point = data[i]; // Move the generated labels from step 1, and reassign the original data labels point.dataLabelUpper = point.dataLabel; point.dataLabel = originalDataLabels[i]; // Reset values point.y = point.low; point.plotY = point.plotLow; // Set the default offset point.below = true; if (inverted) { dataLabelOptions.align = 'right'; dataLabelOptions.x = dataLabelOptions.xLow; } else { dataLabelOptions.y = dataLabelOptions.yLow; } } seriesProto.drawDataLabels.apply(this, arguments); } }, alignDataLabel: seriesTypes.column.prototype.alignDataLabel, getSymbol: seriesTypes.column.prototype.getSymbol, drawPoints: noop });/** * The AreaSplineRangeSeries class */ defaultPlotOptions.areasplinerange = merge(defaultPlotOptions.arearange); /** * AreaSplineRangeSeries object */ seriesTypes.areasplinerange = extendClass(seriesTypes.arearange, { type: 'areasplinerange', getPointSpline: seriesTypes.spline.prototype.getPointSpline });/** * The ColumnRangeSeries class */ defaultPlotOptions.columnrange = merge(defaultPlotOptions.column, defaultPlotOptions.arearange, { lineWidth: 1, pointRange: null }); /** * ColumnRangeSeries object */ seriesTypes.columnrange = extendClass(seriesTypes.arearange, { type: 'columnrange', /** * Translate data points from raw values x and y to plotX and plotY */ translate: function () { var series = this, yAxis = series.yAxis, plotHigh; colProto.translate.apply(series); // Set plotLow and plotHigh each(series.points, function (point) { var shapeArgs = point.shapeArgs; point.plotHigh = plotHigh = yAxis.translate(point.high, 0, 1, 0, 1); point.plotLow = point.plotY; // adjust shape shapeArgs.y = plotHigh; shapeArgs.height = point.plotY - plotHigh; }); }, trackerGroups: ['group', 'dataLabels'], drawGraph: noop, pointAttrToOptions: colProto.pointAttrToOptions, drawPoints: colProto.drawPoints, drawTracker: colProto.drawTracker, animate: colProto.animate, getColumnMetrics: colProto.getColumnMetrics });/* * The GaugeSeries class */ /** * Extend the default options */ defaultPlotOptions.gauge = merge(defaultPlotOptions.line, { dataLabels: { enabled: true, y: 15, borderWidth: 1, borderColor: 'silver', borderRadius: 3, style: { fontWeight: 'bold' }, verticalAlign: 'top', zIndex: 2 }, dial: { // radius: '80%', // backgroundColor: 'black', // borderColor: 'silver', // borderWidth: 0, // baseWidth: 3, // topWidth: 1, // baseLength: '70%' // of radius // rearLength: '10%' }, pivot: { //radius: 5, //borderWidth: 0 //borderColor: 'silver', //backgroundColor: 'black' }, tooltip: { headerFormat: '' }, showInLegend: false }); /** * Extend the point object */ var GaugePoint = Highcharts.extendClass(Highcharts.Point, { /** * Don't do any hover colors or anything */ setState: function (state) { this.state = state; } }); /** * Add the series type */ var GaugeSeries = { type: 'gauge', pointClass: GaugePoint, // chart.angular will be set to true when a gauge series is present, and this will // be used on the axes angular: true, drawGraph: noop, trackerGroups: ['group', 'dataLabels'], /** * Calculate paths etc */ translate: function () { var series = this, yAxis = series.yAxis, options = series.options, center = yAxis.center; series.generatePoints(); each(series.points, function (point) { var dialOptions = merge(options.dial, point.dial), radius = (pInt(pick(dialOptions.radius, 80)) * center[2]) / 200, baseLength = (pInt(pick(dialOptions.baseLength, 70)) * radius) / 100, rearLength = (pInt(pick(dialOptions.rearLength, 10)) * radius) / 100, baseWidth = dialOptions.baseWidth || 3, topWidth = dialOptions.topWidth || 1, rotation = yAxis.startAngleRad + yAxis.translate(point.y, null, null, null, true); // Handle the wrap option if (options.wrap === false) { rotation = Math.max(yAxis.startAngleRad, Math.min(yAxis.endAngleRad, rotation)); } rotation = rotation * 180 / Math.PI; point.shapeType = 'path'; point.shapeArgs = { d: dialOptions.path || [ 'M', -rearLength, -baseWidth / 2, 'L', baseLength, -baseWidth / 2, radius, -topWidth / 2, radius, topWidth / 2, baseLength, baseWidth / 2, -rearLength, baseWidth / 2, 'z' ], translateX: center[0], translateY: center[1], rotation: rotation }; // Positions for data label point.plotX = center[0]; point.plotY = center[1]; }); }, /** * Draw the points where each point is one needle */ drawPoints: function () { var series = this, center = series.yAxis.center, pivot = series.pivot, options = series.options, pivotOptions = options.pivot, renderer = series.chart.renderer; each(series.points, function (point) { var graphic = point.graphic, shapeArgs = point.shapeArgs, d = shapeArgs.d, dialOptions = merge(options.dial, point.dial); // #1233 if (graphic) { graphic.animate(shapeArgs); shapeArgs.d = d; // animate alters it } else { point.graphic = renderer[point.shapeType](shapeArgs) .attr({ stroke: dialOptions.borderColor || 'none', 'stroke-width': dialOptions.borderWidth || 0, fill: dialOptions.backgroundColor || 'black', rotation: shapeArgs.rotation // required by VML when animation is false }) .add(series.group); } }); // Add or move the pivot if (pivot) { pivot.animate({ // #1235 translateX: center[0], translateY: center[1] }); } else { series.pivot = renderer.circle(0, 0, pick(pivotOptions.radius, 5)) .attr({ 'stroke-width': pivotOptions.borderWidth || 0, stroke: pivotOptions.borderColor || 'silver', fill: pivotOptions.backgroundColor || 'black' }) .translate(center[0], center[1]) .add(series.group); } }, /** * Animate the arrow up from startAngle */ animate: function (init) { var series = this; if (!init) { each(series.points, function (point) { var graphic = point.graphic; if (graphic) { // start value graphic.attr({ rotation: series.yAxis.startAngleRad * 180 / Math.PI }); // animate graphic.animate({ rotation: point.shapeArgs.rotation }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; } }, render: function () { this.group = this.plotGroup( 'group', 'series', this.visible ? 'visible' : 'hidden', this.options.zIndex, this.chart.seriesGroup ); seriesTypes.pie.prototype.render.call(this); this.group.clip(this.chart.clipRect); }, setData: seriesTypes.pie.prototype.setData, drawTracker: seriesTypes.column.prototype.drawTracker }; seriesTypes.gauge = Highcharts.extendClass(seriesTypes.line, GaugeSeries);/* **************************************************************************** * Start Box plot series code * *****************************************************************************/ // Set default options defaultPlotOptions.boxplot = merge(defaultPlotOptions.column, { fillColor: '#FFFFFF', lineWidth: 1, //medianColor: null, medianWidth: 2, states: { hover: { brightness: -0.3 } }, //stemColor: null, //stemDashStyle: 'solid' //stemWidth: null, threshold: null, tooltip: { pointFormat: '<span style="color:{series.color};font-weight:bold">{series.name}</span><br/>' + 'Minimum: {point.low}<br/>' + 'Lower quartile: {point.q1}<br/>' + 'Median: {point.median}<br/>' + 'Higher quartile: {point.q3}<br/>' + 'Maximum: {point.high}<br/>' }, //whiskerColor: null, whiskerLength: '50%', whiskerWidth: 2 }); // Create the series object seriesTypes.boxplot = extendClass(seriesTypes.column, { type: 'boxplot', pointArrayMap: ['low', 'q1', 'median', 'q3', 'high'], // array point configs are mapped to this toYData: function (point) { // return a plain array for speedy calculation return [point.low, point.q1, point.median, point.q3, point.high]; }, pointValKey: 'high', // defines the top of the tracker /** * One-to-one mapping from options to SVG attributes */ pointAttrToOptions: { // mapping between SVG attributes and the corresponding options fill: 'fillColor', stroke: 'color', 'stroke-width': 'lineWidth' }, /** * Disable data labels for box plot */ drawDataLabels: noop, /** * Translate data points from raw values x and y to plotX and plotY */ translate: function () { var series = this, yAxis = series.yAxis, pointArrayMap = series.pointArrayMap; seriesTypes.column.prototype.translate.apply(series); // do the translation on each point dimension each(series.points, function (point) { each(pointArrayMap, function (key) { if (point[key] !== null) { point[key + 'Plot'] = yAxis.translate(point[key], 0, 1, 0, 1); } }); }); }, /** * Draw the data points */ drawPoints: function () { var series = this, //state = series.state, points = series.points, options = series.options, chart = series.chart, renderer = chart.renderer, pointAttr, q1Plot, q3Plot, highPlot, lowPlot, medianPlot, crispCorr, crispX, graphic, stemPath, stemAttr, boxPath, whiskersPath, whiskersAttr, medianPath, medianAttr, width, left, right, halfWidth, shapeArgs, color, doQuartiles = series.doQuartiles !== false, // error bar inherits this series type but doesn't do quartiles whiskerLength = parseInt(series.options.whiskerLength, 10) / 100; each(points, function (point) { graphic = point.graphic; shapeArgs = point.shapeArgs; // the box stemAttr = {}; whiskersAttr = {}; medianAttr = {}; color = point.color || series.color; if (point.plotY !== UNDEFINED) { pointAttr = point.pointAttr[point.selected ? 'selected' : '']; // crisp vector coordinates width = shapeArgs.width; left = mathFloor(shapeArgs.x); right = left + width; halfWidth = mathRound(width / 2); //crispX = mathRound(left + halfWidth) + crispCorr; q1Plot = mathFloor(doQuartiles ? point.q1Plot : point.lowPlot);// + crispCorr; q3Plot = mathFloor(doQuartiles ? point.q3Plot : point.lowPlot);// + crispCorr; highPlot = mathFloor(point.highPlot);// + crispCorr; lowPlot = mathFloor(point.lowPlot);// + crispCorr; // Stem attributes stemAttr.stroke = point.stemColor || options.stemColor || color; stemAttr['stroke-width'] = pick(point.stemWidth, options.stemWidth, options.lineWidth); stemAttr.dashstyle = point.stemDashStyle || options.stemDashStyle; // Whiskers attributes whiskersAttr.stroke = point.whiskerColor || options.whiskerColor || color; whiskersAttr['stroke-width'] = pick(point.whiskerWidth, options.whiskerWidth, options.lineWidth); // Median attributes medianAttr.stroke = point.medianColor || options.medianColor || color; medianAttr['stroke-width'] = pick(point.medianWidth, options.medianWidth, options.lineWidth); // The stem crispCorr = (stemAttr['stroke-width'] % 2) / 2; crispX = left + halfWidth + crispCorr; stemPath = [ // stem up 'M', crispX, q3Plot, 'L', crispX, highPlot, // stem down 'M', crispX, q1Plot, 'L', crispX, lowPlot, 'z' ]; // The box if (doQuartiles) { crispCorr = (pointAttr['stroke-width'] % 2) / 2; crispX = mathFloor(crispX) + crispCorr; q1Plot = mathFloor(q1Plot) + crispCorr; q3Plot = mathFloor(q3Plot) + crispCorr; left += crispCorr; right += crispCorr; boxPath = [ 'M', left, q3Plot, 'L', left, q1Plot, 'L', right, q1Plot, 'L', right, q3Plot, 'L', left, q3Plot, 'z' ]; } // The whiskers if (whiskerLength) { crispCorr = (whiskersAttr['stroke-width'] % 2) / 2; highPlot = highPlot + crispCorr; lowPlot = lowPlot + crispCorr; whiskersPath = [ // High whisker 'M', crispX - halfWidth * whiskerLength, highPlot, 'L', crispX + halfWidth * whiskerLength, highPlot, // Low whisker 'M', crispX - halfWidth * whiskerLength, lowPlot, 'L', crispX + halfWidth * whiskerLength, lowPlot ]; } // The median crispCorr = (medianAttr['stroke-width'] % 2) / 2; medianPlot = mathRound(point.medianPlot) + crispCorr; medianPath = [ 'M', left, medianPlot, 'L', right, medianPlot, 'z' ]; // Create or update the graphics if (graphic) { // update point.stem.animate({ d: stemPath }); if (whiskerLength) { point.whiskers.animate({ d: whiskersPath }); } if (doQuartiles) { point.box.animate({ d: boxPath }); } point.medianShape.animate({ d: medianPath }); } else { // create new point.graphic = graphic = renderer.g() .add(series.group); point.stem = renderer.path(stemPath) .attr(stemAttr) .add(graphic); if (whiskerLength) { point.whiskers = renderer.path(whiskersPath) .attr(whiskersAttr) .add(graphic); } if (doQuartiles) { point.box = renderer.path(boxPath) .attr(pointAttr) .add(graphic); } point.medianShape = renderer.path(medianPath) .attr(medianAttr) .add(graphic); } } }); } }); /* **************************************************************************** * End Box plot series code * *****************************************************************************/ /* **************************************************************************** * Start error bar series code * *****************************************************************************/ // 1 - set default options defaultPlotOptions.errorbar = merge(defaultPlotOptions.boxplot, { color: '#000000', grouping: false, linkedTo: ':previous', tooltip: { pointFormat: defaultPlotOptions.arearange.tooltip.pointFormat }, whiskerWidth: null }); // 2 - Create the series object seriesTypes.errorbar = extendClass(seriesTypes.boxplot, { type: 'errorbar', pointArrayMap: ['low', 'high'], // array point configs are mapped to this toYData: function (point) { // return a plain array for speedy calculation return [point.low, point.high]; }, pointValKey: 'high', // defines the top of the tracker doQuartiles: false, /** * Get the width and X offset, either on top of the linked series column * or standalone */ getColumnMetrics: function () { return (this.linkedParent && this.linkedParent.columnMetrics) || seriesTypes.column.prototype.getColumnMetrics.call(this); } }); /* **************************************************************************** * End error bar series code * *****************************************************************************/ /* **************************************************************************** * Start Waterfall series code * *****************************************************************************/ wrap(axisProto, 'getSeriesExtremes', function (proceed, renew) { // Run uber method proceed.call(this, renew); if (this.isXAxis) { return; } var axis = this, visitedStacks = [], resetMinMax = true; // recalculate extremes for each waterfall stack each(axis.series, function (series) { // process only visible, waterfall series, one from each stack if (!series.visible || !series.stackKey || series.type !== 'waterfall' || HighchartsAdapter.inArray(series.stackKey) !== -1) { return; } // reset previously found dataMin and dataMax, do it only once if (resetMinMax) { axis.dataMin = axis.dataMax = null; resetMinMax = false; } var yData = series.processedYData, yDataLength = yData.length, seriesDataMin = yData[0], seriesDataMax = yData[0], threshold = series.options.threshold, stacks = axis.stacks, stackKey = series.stackKey, negKey = '-' + stackKey, total, previous, key, i; // set new stack totals including preceding values, finds new min and max values for (i = 0; i < yDataLength; i++) { key = yData[i] < threshold ? negKey : stackKey; total = stacks[key][i].total; if (i > threshold) { total += previous; stacks[key][i].setTotal(total); // _cum is used to avoid conflict with Series.translate method stacks[key][i]._cum = null; } // find min / max values if (total < seriesDataMin) { seriesDataMin = total; } if (total > seriesDataMax) { seriesDataMax = total; } previous = total; } // set new extremes series.dataMin = seriesDataMin; series.dataMax = seriesDataMax; axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin, threshold); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax, threshold); // remember series' stack key visitedStacks.push(series.stackKey); // Adjust to threshold. This code is duplicated from the parent getSeriesExtremes method. if (typeof threshold === 'number') { if (axis.dataMin >= threshold) { axis.dataMin = threshold; axis.ignoreMinPadding = true; } else if (axis.dataMax < threshold) { axis.dataMax = threshold; axis.ignoreMaxPadding = true; } } }); }); // 1 - set default options defaultPlotOptions.waterfall = merge(defaultPlotOptions.column, { lineWidth: 1, lineColor: '#333', dashStyle: 'dot', borderColor: '#333' }); // 2 - Create the series object seriesTypes.waterfall = extendClass(seriesTypes.column, { type: 'waterfall', upColorProp: 'fill', pointArrayMap: ['y', 'low'], pointValKey: 'y', /** * Init waterfall series, force stacking */ init: function (chart, options) { options.stacking = true; seriesTypes.column.prototype.init.call(this, chart, options); }, /** * Translate data points from raw values */ translate: function () { var series = this, options = series.options, axis = series.yAxis, len, i, points, point, shapeArgs, sum, sumStart, subSum, subSumStart, edges, cumulative, prevStack, prevY, stack, crispCorr = (options.borderWidth % 2) / 2; // run column series translate seriesTypes.column.prototype.translate.apply(this); points = this.points; subSumStart = sumStart = points[0]; sum = subSum = points[0].y; for (i = 1, len = points.length; i < len; i++) { // cache current point object point = points[i]; shapeArgs = point.shapeArgs; // get current and previous stack stack = series.getStack(i); prevStack = series.getStack(i - 1); prevY = series.getStackY(prevStack); // set new intermediate sum values after reset if (subSumStart === null) { subSumStart = point; subSum = 0; } // sum only points with value, not intermediate or total sum if (point.y && !point.isSum && !point.isIntermediateSum) { sum += point.y; subSum += point.y; } // calculate sum points if (point.isSum || point.isIntermediateSum) { if (point.isIntermediateSum) { edges = series.getSumEdges(subSumStart, points[i - 1]); point.y = subSum; subSumStart = null; } else { edges = series.getSumEdges(sumStart, points[i - 1]); point.y = sum; } shapeArgs.y = point.plotY = edges[1]; shapeArgs.height = edges[0] - edges[1]; // calculate other (up or down) points based on y value } else { // use "_cum" instead of already calculated "cum" to avoid reverse ordering negative columns cumulative = stack._cum === null ? prevStack.total : stack._cum; stack._cum = cumulative + point.y; if (point.y < 0) { shapeArgs.y = mathCeil(axis.translate(cumulative, 0, 1)) - crispCorr; shapeArgs.height = mathCeil(axis.translate(stack._cum, 0, 1) - shapeArgs.y); } else { if (prevStack.total + point.y < 0) { shapeArgs.y = axis.translate(stack._cum, 0, 1); } shapeArgs.height = mathFloor(prevY - shapeArgs.y); } } } }, /** * Call default processData then override yData to reflect waterfall's extremes on yAxis */ processData: function (force) { Series.prototype.processData.call(this, force); var series = this, options = series.options, yData = series.yData, length = yData.length, prev, curr, subSum, sum, i; prev = sum = subSum = options.threshold; for (i = 0; i < length; i++) { curr = yData[i]; // processed yData only if it's not already processed if (curr !== null && typeof curr !== 'number') { if (curr === "sum") { yData[i] = null; } else if (curr === "intermediateSum") { yData[i] = null; subSum = prev; } else { yData[i] = curr[0];// + prev; } prev = yData[i]; } } }, /** * Return [y, low] array, if low is not defined, it's replaced with null for further calculations */ toYData: function (pt) { if (pt.isSum) { return "sum"; } else if (pt.isIntermediateSum) { return "intermediateSum"; } return [pt.y]; }, /** * Postprocess mapping between options and SVG attributes */ getAttribs: function () { seriesTypes.column.prototype.getAttribs.apply(this, arguments); var series = this, options = series.options, stateOptions = options.states, upColor = options.upColor || series.color, hoverColor = Highcharts.Color(upColor).brighten(0.1).get(), seriesDownPointAttr = merge(series.pointAttr), upColorProp = series.upColorProp; seriesDownPointAttr[''][upColorProp] = upColor; seriesDownPointAttr.hover[upColorProp] = stateOptions.hover.upColor || hoverColor; seriesDownPointAttr.select[upColorProp] = stateOptions.select.upColor || upColor; each(series.points, function (point) { if (point.y > 0 && !point.color) { point.pointAttr = seriesDownPointAttr; point.color = upColor; } }); }, /** * Draw columns' connector lines */ getGraphPath: function () { var data = this.data, length = data.length, lineWidth = this.options.lineWidth + this.options.borderWidth, normalizer = mathRound(lineWidth) % 2 / 2, path = [], M = 'M', L = 'L', prevArgs, pointArgs, i, d; for (i = 1; i < length; i++) { pointArgs = data[i].shapeArgs; prevArgs = data[i - 1].shapeArgs; d = [ M, prevArgs.x + prevArgs.width, prevArgs.y + normalizer, L, pointArgs.x, prevArgs.y + normalizer ]; if (data[i - 1].y < 0) { d[2] += prevArgs.height; d[5] += prevArgs.height; } path = path.concat(d); } return path; }, getStack: function (i) { var axis = this.yAxis, stacks = axis.stacks, key = this.stackKey; if (this.processedYData[i] < this.options.threshold) { key = '-' + key; } return stacks[key][i]; }, getStackY: function (stack) { return mathCeil(this.yAxis.translate(stack.total, null, true)); }, /** * Return array of top and bottom position for sum column based on given edge points */ getSumEdges: function (pointA, pointB) { var valueA, valueB, tmp, threshold = this.options.threshold; valueA = pointA.y >= threshold ? pointA.shapeArgs.y + pointA.shapeArgs.height : pointA.shapeArgs.y; valueB = pointB.y >= threshold ? pointB.shapeArgs.y : pointB.shapeArgs.y + pointB.shapeArgs.height; if (valueB > valueA) { tmp = valueA; valueA = valueB; valueB = tmp; } return [valueA, valueB]; }, drawGraph: Series.prototype.drawGraph }); /* **************************************************************************** * End Waterfall series code * *****************************************************************************/ /* **************************************************************************** * Start Bubble series code * *****************************************************************************/ // 1 - set default options defaultPlotOptions.bubble = merge(defaultPlotOptions.scatter, { dataLabels: { inside: true, style: { color: 'white', textShadow: '0px 0px 3px black' }, verticalAlign: 'middle' }, // displayNegative: true, marker: { // fillOpacity: 0.5, lineColor: null, // inherit from series.color lineWidth: 1 }, minSize: 8, maxSize: '20%', // negativeColor: null, tooltip: { pointFormat: '({point.x}, {point.y}), Size: {point.z}' }, zThreshold: 0 }); // 2 - Create the series object seriesTypes.bubble = extendClass(seriesTypes.scatter, { type: 'bubble', pointArrayMap: ['y', 'z'], trackerGroups: ['group', 'dataLabelsGroup'], /** * Mapping between SVG attributes and the corresponding options */ pointAttrToOptions: { stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor' }, /** * Apply the fillOpacity to all fill positions */ applyOpacity: function (fill) { var markerOptions = this.options.marker, fillOpacity = pick(markerOptions.fillOpacity, 0.5); // When called from Legend.colorizeItem, the fill isn't predefined fill = fill || markerOptions.fillColor || this.color; if (fillOpacity !== 1) { fill = Highcharts.Color(fill).setOpacity(fillOpacity).get('rgba'); } return fill; }, /** * Extend the convertAttribs method by applying opacity to the fill */ convertAttribs: function () { var obj = Series.prototype.convertAttribs.apply(this, arguments); obj.fill = this.applyOpacity(obj.fill); return obj; }, /** * Get the radius for each point based on the minSize, maxSize and each point's Z value. This * must be done prior to Series.translate because the axis needs to add padding in * accordance with the point sizes. */ getRadii: function (zMin, zMax, minSize, maxSize) { var len, i, pos, zData = this.zData, radii = [], zRange; // Set the shape type and arguments to be picked up in drawPoints for (i = 0, len = zData.length; i < len; i++) { zRange = zMax - zMin; pos = zRange > 0 ? // relative size, a number between 0 and 1 (zData[i] - zMin) / (zMax - zMin) : 0.5; radii.push(math.ceil(minSize + pos * (maxSize - minSize)) / 2); } this.radii = radii; }, /** * Perform animation on the bubbles */ animate: function (init) { var animation = this.options.animation; if (!init) { // run the animation each(this.points, function (point) { var graphic = point.graphic, shapeArgs = point.shapeArgs; if (graphic && shapeArgs) { // start values graphic.attr('r', 1); // animate graphic.animate({ r: shapeArgs.r }, animation); } }); // delete this function to allow it only once this.animate = null; } }, /** * Extend the base translate method to handle bubble size */ translate: function () { var i, data = this.data, point, radius, radii = this.radii; // Run the parent method seriesTypes.scatter.prototype.translate.call(this); // Set the shape type and arguments to be picked up in drawPoints i = data.length; while (i--) { point = data[i]; radius = radii ? radii[i] : 0; // #1737 // Flag for negativeColor to be applied in Series.js point.negative = point.z < (this.options.zThreshold || 0); if (radius >= this.minPxSize / 2) { // Shape arguments point.shapeType = 'circle'; point.shapeArgs = { x: point.plotX, y: point.plotY, r: radius }; // Alignment box for the data label point.dlBox = { x: point.plotX - radius, y: point.plotY - radius, width: 2 * radius, height: 2 * radius }; } else { // below zThreshold point.shapeArgs = point.plotY = point.dlBox = UNDEFINED; // #1691 } } }, /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawLegendSymbol: function (legend, item) { var radius = pInt(legend.itemStyle.fontSize) / 2; item.legendSymbol = this.chart.renderer.circle( radius, legend.baseline - radius, radius ).attr({ zIndex: 3 }).add(item.legendGroup); }, drawPoints: seriesTypes.column.prototype.drawPoints, alignDataLabel: seriesTypes.column.prototype.alignDataLabel }); /** * Add logic to pad each axis with the amount of pixels * necessary to avoid the bubbles to overflow. */ Axis.prototype.beforePadding = function () { var axis = this, axisLength = this.len, chart = this.chart, pxMin = 0, pxMax = axisLength, isXAxis = this.isXAxis, dataKey = isXAxis ? 'xData' : 'yData', min = this.min, extremes = {}, smallestSize = math.min(chart.plotWidth, chart.plotHeight), zMin = Number.MAX_VALUE, zMax = -Number.MAX_VALUE, range = this.max - min, transA = axisLength / range, activeSeries = []; // Handle padding on the second pass, or on redraw if (this.tickPositions) { each(this.series, function (series) { var seriesOptions = series.options, zData; if (series.type === 'bubble' && series.visible) { // Correction for #1673 axis.allowZoomOutside = true; // Cache it activeSeries.push(series); if (isXAxis) { // because X axis is evaluated first // For each series, translate the size extremes to pixel values each(['minSize', 'maxSize'], function (prop) { var length = seriesOptions[prop], isPercent = /%$/.test(length); length = pInt(length); extremes[prop] = isPercent ? smallestSize * length / 100 : length; }); series.minPxSize = extremes.minSize; // Find the min and max Z zData = series.zData; if (zData.length) { // #1735 zMin = math.min( zMin, math.max( arrayMin(zData), seriesOptions.displayNegative === false ? seriesOptions.zThreshold : -Number.MAX_VALUE ) ); zMax = math.max(zMax, arrayMax(zData)); } } } }); each(activeSeries, function (series) { var data = series[dataKey], i = data.length, radius; if (isXAxis) { series.getRadii(zMin, zMax, extremes.minSize, extremes.maxSize); } if (range > 0) { while (i--) { radius = series.radii[i]; pxMin = Math.min(((data[i] - min) * transA) - radius, pxMin); pxMax = Math.max(((data[i] - min) * transA) + radius, pxMax); } } }); if (range > 0 && pick(this.options.min, this.userMin) === UNDEFINED && pick(this.options.max, this.userMax) === UNDEFINED) { pxMax -= axisLength; transA *= (axisLength + pxMin - pxMax) / axisLength; this.min += pxMin / transA; this.max += pxMax / transA; } } }; /* **************************************************************************** * End Bubble series code * *****************************************************************************/ /** * Extensions for polar charts. Additionally, much of the geometry required for polar charts is * gathered in RadialAxes.js. * */ var seriesProto = Series.prototype, pointerProto = Highcharts.Pointer.prototype; /** * Translate a point's plotX and plotY from the internal angle and radius measures to * true plotX, plotY coordinates */ seriesProto.toXY = function (point) { var xy, chart = this.chart, plotX = point.plotX, plotY = point.plotY; // Save rectangular plotX, plotY for later computation point.rectPlotX = plotX; point.rectPlotY = plotY; // Record the angle in degrees for use in tooltip point.clientX = plotX / Math.PI * 180; // Find the polar plotX and plotY xy = this.xAxis.postTranslate(point.plotX, this.yAxis.len - plotY); point.plotX = point.polarPlotX = xy.x - chart.plotLeft; point.plotY = point.polarPlotY = xy.y - chart.plotTop; }; /** * Add some special init logic to areas and areasplines */ function initArea(proceed, chart, options) { proceed.call(this, chart, options); if (this.chart.polar) { /** * Overridden method to close a segment path. While in a cartesian plane the area * goes down to the threshold, in the polar chart it goes to the center. */ this.closeSegment = function (path) { var center = this.xAxis.center; path.push( 'L', center[0], center[1] ); }; // Instead of complicated logic to draw an area around the inner area in a stack, // just draw it behind this.closedStacks = true; } } wrap(seriesTypes.area.prototype, 'init', initArea); wrap(seriesTypes.areaspline.prototype, 'init', initArea); /** * Overridden method for calculating a spline from one point to the next */ wrap(seriesTypes.spline.prototype, 'getPointSpline', function (proceed, segment, point, i) { var ret, smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc; denom = smoothing + 1, plotX, plotY, lastPoint, nextPoint, lastX, lastY, nextX, nextY, leftContX, leftContY, rightContX, rightContY, distanceLeftControlPoint, distanceRightControlPoint, leftContAngle, rightContAngle, jointAngle; if (this.chart.polar) { plotX = point.plotX; plotY = point.plotY; lastPoint = segment[i - 1]; nextPoint = segment[i + 1]; // Connect ends if (this.connectEnds) { if (!lastPoint) { lastPoint = segment[segment.length - 2]; // not the last but the second last, because the segment is already connected } if (!nextPoint) { nextPoint = segment[1]; } } // find control points if (lastPoint && nextPoint) { lastX = lastPoint.plotX; lastY = lastPoint.plotY; nextX = nextPoint.plotX; nextY = nextPoint.plotY; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; distanceLeftControlPoint = Math.sqrt(Math.pow(leftContX - plotX, 2) + Math.pow(leftContY - plotY, 2)); distanceRightControlPoint = Math.sqrt(Math.pow(rightContX - plotX, 2) + Math.pow(rightContY - plotY, 2)); leftContAngle = Math.atan2(leftContY - plotY, leftContX - plotX); rightContAngle = Math.atan2(rightContY - plotY, rightContX - plotX); jointAngle = (Math.PI / 2) + ((leftContAngle + rightContAngle) / 2); // Ensure the right direction, jointAngle should be in the same quadrant as leftContAngle if (Math.abs(leftContAngle - jointAngle) > Math.PI / 2) { jointAngle -= Math.PI; } // Find the corrected control points for a spline straight through the point leftContX = plotX + Math.cos(jointAngle) * distanceLeftControlPoint; leftContY = plotY + Math.sin(jointAngle) * distanceLeftControlPoint; rightContX = plotX + Math.cos(Math.PI + jointAngle) * distanceRightControlPoint; rightContY = plotY + Math.sin(Math.PI + jointAngle) * distanceRightControlPoint; // Record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // moveTo or lineTo if (!i) { ret = ['M', plotX, plotY]; } else { // curve from last point to this ret = [ 'C', lastPoint.rightContX || lastPoint.plotX, lastPoint.rightContY || lastPoint.plotY, leftContX || plotX, leftContY || plotY, plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later } } else { ret = proceed.call(this, segment, point, i); } return ret; }); /** * Extend translate. The plotX and plotY values are computed as if the polar chart were a * cartesian plane, where plotX denotes the angle in radians and (yAxis.len - plotY) is the pixel distance from * center. */ wrap(seriesProto, 'translate', function (proceed) { // Run uber method proceed.call(this); // Postprocess plot coordinates if (this.chart.polar && !this.preventPostTranslate) { var points = this.points, i = points.length; while (i--) { // Translate plotX, plotY from angle and radius to true plot coordinates this.toXY(points[i]); } } }); /** * Extend getSegmentPath to allow connecting ends across 0 to provide a closed circle in * line-like series. */ wrap(seriesProto, 'getSegmentPath', function (proceed, segment) { var points = this.points; // Connect the path if (this.chart.polar && this.options.connectEnds !== false && segment[segment.length - 1] === points[points.length - 1] && points[0].y !== null) { this.connectEnds = true; // re-used in splines segment = [].concat(segment, [points[0]]); } // Run uber method return proceed.call(this, segment); }); function polarAnimate(proceed, init) { var chart = this.chart, animation = this.options.animation, group = this.group, markerGroup = this.markerGroup, center = this.xAxis.center, plotLeft = chart.plotLeft, plotTop = chart.plotTop, attribs; // Specific animation for polar charts if (chart.polar) { // Enable animation on polar charts only in SVG. In VML, the scaling is different, plus animation // would be so slow it would't matter. if (chart.renderer.isSVG) { if (animation === true) { animation = {}; } // Initialize the animation if (init) { // Scale down the group and place it in the center attribs = { translateX: center[0] + plotLeft, translateY: center[1] + plotTop, scaleX: 0.001, // #1499 scaleY: 0.001 }; group.attr(attribs); if (markerGroup) { markerGroup.attrSetters = group.attrSetters; markerGroup.attr(attribs); } // Run the animation } else { attribs = { translateX: plotLeft, translateY: plotTop, scaleX: 1, scaleY: 1 }; group.animate(attribs, animation); if (markerGroup) { markerGroup.animate(attribs, animation); } // Delete this function to allow it only once this.animate = null; } } // For non-polar charts, revert to the basic animation } else { proceed.call(this, init); } } // Define the animate method for both regular series and column series and their derivatives wrap(seriesProto, 'animate', polarAnimate); wrap(colProto, 'animate', polarAnimate); /** * Throw in a couple of properties to let setTooltipPoints know we're indexing the points * in degrees (0-360), not plot pixel width. */ wrap(seriesProto, 'setTooltipPoints', function (proceed, renew) { if (this.chart.polar) { extend(this.xAxis, { tooltipLen: 360 // degrees are the resolution unit of the tooltipPoints array }); } // Run uber method return proceed.call(this, renew); }); /** * Extend the column prototype's translate method */ wrap(colProto, 'translate', function (proceed) { var xAxis = this.xAxis, len = this.yAxis.len, center = xAxis.center, startAngleRad = xAxis.startAngleRad, renderer = this.chart.renderer, start, points, point, i; this.preventPostTranslate = true; // Run uber method proceed.call(this); // Postprocess plot coordinates if (xAxis.isRadial) { points = this.points; i = points.length; while (i--) { point = points[i]; start = point.barX + startAngleRad; point.shapeType = 'path'; point.shapeArgs = { d: renderer.symbols.arc( center[0], center[1], len - point.plotY, null, { start: start, end: start + point.pointWidth, innerR: len - pick(point.yBottom, len) } ) }; this.toXY(point); // provide correct plotX, plotY for tooltip } } }); /** * Align column data labels outside the columns. #1199. */ wrap(colProto, 'alignDataLabel', function (proceed, point, dataLabel, options, alignTo, isNew) { if (this.chart.polar) { var angle = point.rectPlotX / Math.PI * 180, align, verticalAlign; // Align nicely outside the perimeter of the columns if (options.align === null) { if (angle > 20 && angle < 160) { align = 'left'; // right hemisphere } else if (angle > 200 && angle < 340) { align = 'right'; // left hemisphere } else { align = 'center'; // top or bottom } options.align = align; } if (options.verticalAlign === null) { if (angle < 45 || angle > 315) { verticalAlign = 'bottom'; // top part } else if (angle > 135 && angle < 225) { verticalAlign = 'top'; // bottom part } else { verticalAlign = 'middle'; // left or right } options.verticalAlign = verticalAlign; } seriesProto.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); } else { proceed.call(this, point, dataLabel, options, alignTo, isNew); } }); /** * Extend the mouse tracker to return the tooltip position index in terms of * degrees rather than pixels */ wrap(pointerProto, 'getIndex', function (proceed, e) { var ret, chart = this.chart, center, x, y; if (chart.polar) { center = chart.xAxis[0].center; x = e.chartX - center[0] - chart.plotLeft; y = e.chartY - center[1] - chart.plotTop; ret = 180 - Math.round(Math.atan2(x, y) / Math.PI * 180); } else { // Run uber method ret = proceed.call(this, e); } return ret; }); /** * Extend getCoordinates to prepare for polar axis values */ wrap(pointerProto, 'getCoordinates', function (proceed, e) { var chart = this.chart, ret = { xAxis: [], yAxis: [] }; if (chart.polar) { each(chart.axes, function (axis) { var isXAxis = axis.isXAxis, center = axis.center, x = e.chartX - center[0] - chart.plotLeft, y = e.chartY - center[1] - chart.plotTop; ret[isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.translate( isXAxis ? Math.PI - Math.atan2(x, y) : // angle Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)), // distance from center true ) }); }); } else { ret = proceed.call(this, e); } return ret; }); }(Highcharts));
JavaScript
/** * Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ // Tool scripts for the sample pages. // This file can be ignored and is not required to make use of CKEditor. ( function() { CKEDITOR.on( 'instanceReady', function( ev ) { // Check for sample compliance. var editor = ev.editor, meta = CKEDITOR.document.$.getElementsByName( 'ckeditor-sample-required-plugins' ), requires = meta.length ? CKEDITOR.dom.element.get( meta[ 0 ] ).getAttribute( 'content' ).split( ',' ) : [], missing = [], i; if ( requires.length ) { for ( i = 0; i < requires.length; i++ ) { if ( !editor.plugins[ requires[ i ] ] ) missing.push( '<code>' + requires[ i ] + '</code>' ); } if ( missing.length ) { var warn = CKEDITOR.dom.element.createFromHtml( '<div class="warning">' + '<span>To fully experience this demo, the ' + missing.join( ', ' ) + ' plugin' + ( missing.length > 1 ? 's are' : ' is' ) + ' required.</span>' + '</div>' ); warn.insertBefore( editor.container ); } } // Set icons. var doc = new CKEDITOR.dom.document( document ), icons = doc.find( '.button_icon' ); for ( i = 0; i < icons.count(); i++ ) { var icon = icons.getItem( i ), name = icon.getAttribute( 'data-icon' ), style = CKEDITOR.skin.getIconStyle( name, ( CKEDITOR.lang.dir == 'rtl' ) ); icon.addClass( 'cke_button_icon' ); icon.addClass( 'cke_button__' + name + '_icon' ); icon.setAttribute( 'style', style ); icon.setStyle( 'float', 'none' ); } } ); } )();
JavaScript
/** * Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'myDialog', function( editor ) { return { title: 'My Dialog', minWidth: 400, minHeight: 200, contents: [ { id: 'tab1', label: 'First Tab', title: 'First Tab', elements: [ { id: 'input1', type: 'text', label: 'Text Field' }, { id: 'select1', type: 'select', label: 'Select Field', items: [ [ 'option1', 'value1' ], [ 'option2', 'value2' ] ] } ] }, { id: 'tab2', label: 'Second Tab', title: 'Second Tab', elements: [ { id: 'button1', type: 'button', label: 'Button Field' } ] } ] }; } );
JavaScript
/** * @license Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time to build CKEditor again. * * If you would like to build CKEditor online again * (for example to upgrade), visit one the following links: * * (1) http://ckeditor.com/builder * Visit online builder to build CKEditor from scratch. * * (2) http://ckeditor.com/builder/e41bccb8290b6d530f8478ddafe95c48 * Visit online builder to build CKEditor, starting with the same setup as before. * * (3) http://ckeditor.com/builder/download/e41bccb8290b6d530f8478ddafe95c48 * Straight download link to the latest version of CKEditor (Optimized) with the same setup as before. * * NOTE: * This file is not used by CKEditor, you may remove it. * Changing this file will not change your CKEditor configuration. */ var CKBUILDER_CONFIG = { skin: 'moono', preset: 'standard', ignore: [ 'dev', '.gitignore', '.gitattributes', 'README.md', '.mailmap' ], plugins : { 'a11yhelp' : 1, 'about' : 1, 'basicstyles' : 1, 'blockquote' : 1, 'clipboard' : 1, 'contextmenu' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'filebrowser' : 1, 'floatingspace' : 1, 'format' : 1, 'horizontalrule' : 1, 'htmlwriter' : 1, 'image' : 1, 'indentlist' : 1, 'link' : 1, 'list' : 1, 'magicline' : 1, 'maximize' : 1, 'pastefromword' : 1, 'pastetext' : 1, 'removeformat' : 1, 'resize' : 1, 'scayt' : 1, 'showborders' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tabletools' : 1, 'toolbar' : 1, 'undo' : 1, 'wsc' : 1, 'wysiwygarea' : 1 }, languages : { 'af' : 1, 'ar' : 1, 'bg' : 1, 'bn' : 1, 'bs' : 1, 'ca' : 1, 'cs' : 1, 'cy' : 1, 'da' : 1, 'de' : 1, 'el' : 1, 'en' : 1, 'en-au' : 1, 'en-ca' : 1, 'en-gb' : 1, 'eo' : 1, 'es' : 1, 'et' : 1, 'eu' : 1, 'fa' : 1, 'fi' : 1, 'fo' : 1, 'fr' : 1, 'fr-ca' : 1, 'gl' : 1, 'gu' : 1, 'he' : 1, 'hi' : 1, 'hr' : 1, 'hu' : 1, 'id' : 1, 'is' : 1, 'it' : 1, 'ja' : 1, 'ka' : 1, 'km' : 1, 'ko' : 1, 'ku' : 1, 'lt' : 1, 'lv' : 1, 'mk' : 1, 'mn' : 1, 'ms' : 1, 'nb' : 1, 'nl' : 1, 'no' : 1, 'pl' : 1, 'pt' : 1, 'pt-br' : 1, 'ro' : 1, 'ru' : 1, 'si' : 1, 'sk' : 1, 'sl' : 1, 'sq' : 1, 'sr' : 1, 'sr-latn' : 1, 'sv' : 1, 'th' : 1, 'tr' : 1, 'tt' : 1, 'ug' : 1, 'uk' : 1, 'vi' : 1, 'zh' : 1, 'zh-cn' : 1 } };
JavaScript
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. // For complete reference see: // http://docs.ckeditor.com/#!/api/CKEDITOR.config // The toolbar groups arrangement, optimized for two toolbar rows. config.toolbarGroups = [ { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] }, { name: 'links' }, { name: 'insert' }, { name: 'forms' }, { name: 'tools' }, { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'others' }, '/', { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] }, { name: 'styles' }, { name: 'colors' }, { name: 'about' } ]; // Remove some buttons provided by the standard plugins, which are // not needed in the Standard(s) toolbar. config.removeButtons = 'Underline,Subscript,Superscript'; // Set the most common block elements. config.format_tags = 'p;h1;h2;h3;pre'; // Simplify the dialog windows. config.removeDialogTabs = 'image:advanced;link:advanced'; };
JavaScript
/** * Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ // This file contains style definitions that can be used by CKEditor plugins. // // The most common use for it is the "stylescombo" plugin, which shows a combo // in the editor toolbar, containing all styles. Other plugins instead, like // the div plugin, use a subset of the styles on their feature. // // If you don't have plugins that depend on this file, you can simply ignore it. // Otherwise it is strongly recommended to customize this file to match your // website requirements and design properly. CKEDITOR.stylesSet.add( 'default', [ /* Block Styles */ // These styles are already available in the "Format" combo ("format" plugin), // so they are not needed here by default. You may enable them to avoid // placing the "Format" combo in the toolbar, maintaining the same features. /* { name: 'Paragraph', element: 'p' }, { name: 'Heading 1', element: 'h1' }, { name: 'Heading 2', element: 'h2' }, { name: 'Heading 3', element: 'h3' }, { name: 'Heading 4', element: 'h4' }, { name: 'Heading 5', element: 'h5' }, { name: 'Heading 6', element: 'h6' }, { name: 'Preformatted Text',element: 'pre' }, { name: 'Address', element: 'address' }, */ { name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } }, { name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } }, { name: 'Special Container', element: 'div', styles: { padding: '5px 10px', background: '#eee', border: '1px solid #ccc' } }, /* Inline Styles */ // These are core styles available as toolbar buttons. You may opt enabling // some of them in the Styles combo, removing them from the toolbar. // (This requires the "stylescombo" plugin) /* { name: 'Strong', element: 'strong', overrides: 'b' }, { name: 'Emphasis', element: 'em' , overrides: 'i' }, { name: 'Underline', element: 'u' }, { name: 'Strikethrough', element: 'strike' }, { name: 'Subscript', element: 'sub' }, { name: 'Superscript', element: 'sup' }, */ { name: 'Marker', element: 'span', attributes: { 'class': 'marker' } }, { name: 'Big', element: 'big' }, { name: 'Small', element: 'small' }, { name: 'Typewriter', element: 'tt' }, { name: 'Computer Code', element: 'code' }, { name: 'Keyboard Phrase', element: 'kbd' }, { name: 'Sample Text', element: 'samp' }, { name: 'Variable', element: 'var' }, { name: 'Deleted Text', element: 'del' }, { name: 'Inserted Text', element: 'ins' }, { name: 'Cited Work', element: 'cite' }, { name: 'Inline Quotation', element: 'q' }, { name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } }, { name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } }, /* Object Styles */ { name: 'Styled image (left)', element: 'img', attributes: { 'class': 'left' } }, { name: 'Styled image (right)', element: 'img', attributes: { 'class': 'right' } }, { name: 'Compact table', element: 'table', attributes: { cellpadding: '5', cellspacing: '0', border: '1', bordercolor: '#ccc' }, styles: { 'border-collapse': 'collapse' } }, { name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } }, { name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } } ] );
JavaScript
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */
JavaScript
/* malihu custom scrollbar plugin - http://manos.malihu.gr */ (function ($) { $.fn.mCustomScrollbar = function (scrollType,animSpeed,easeType,bottomSpace,draggerDimType,mouseWheelSupport,scrollBtnsSupport,scrollBtnsSpeed){ var id = $(this).attr("id"); var $customScrollBox=$("#"+id+" .customScrollBox"); var $customScrollBox_container=$("#"+id+" .customScrollBox .container"); var $customScrollBox_content=$("#"+id+" .customScrollBox .content"); var $dragger_container=$("#"+id+" .dragger_container"); var $dragger=$("#"+id+" .dragger"); var $scrollUpBtn=$("#"+id+" .scrollUpBtn"); var $scrollDownBtn=$("#"+id+" .scrollDownBtn"); var $customScrollBox_horWrapper=$("#"+id+" .customScrollBox .horWrapper"); //get & store minimum dragger height & width (defined in css) if(!$customScrollBox.data("minDraggerHeight")){ $customScrollBox.data("minDraggerHeight",$dragger.height()); } if(!$customScrollBox.data("minDraggerWidth")){ $customScrollBox.data("minDraggerWidth",$dragger.width()); } //get & store original content height & width if(!$customScrollBox.data("contentHeight")){ $customScrollBox.data("contentHeight",$customScrollBox_container.height()); } if(!$customScrollBox.data("contentWidth")){ $customScrollBox.data("contentWidth",$customScrollBox_container.width()); } CustomScroller(); function CustomScroller(reloadType){ //horizontal scrolling ------------------------------ if(scrollType=="horizontal"){ var visibleWidth=$customScrollBox.width(); //set content width automatically $customScrollBox_horWrapper.css("width",999999); //set a rediculously high width value ;) $customScrollBox.data("totalContent",$customScrollBox_container.width()); //get inline div width $customScrollBox_horWrapper.css("width",$customScrollBox.data("totalContent")); //set back the proper content width value if($customScrollBox_container.width()>visibleWidth){ //enable scrollbar if content is long $dragger.css("display","block"); if(reloadType!="resize" && $customScrollBox_container.width()!=$customScrollBox.data("contentWidth")){ $dragger.css("left",0); $customScrollBox_container.css("left",0); $customScrollBox.data("contentWidth",$customScrollBox_container.width()); } $dragger_container.css("display","block"); $scrollDownBtn.css("display","inline-block"); $scrollUpBtn.css("display","inline-block"); var totalContent=$customScrollBox_content.width(); var minDraggerWidth=$customScrollBox.data("minDraggerWidth"); var draggerContainerWidth=$dragger_container.width(); function AdjustDraggerWidth(){ if(draggerDimType=="auto"){ var adjDraggerWidth=Math.round(totalContent-((totalContent-visibleWidth)*1.3)); //adjust dragger width analogous to content if(adjDraggerWidth<=minDraggerWidth){ //minimum dragger width $dragger.css("width",minDraggerWidth+"px"); } else if(adjDraggerWidth>=draggerContainerWidth){ $dragger.css("width",draggerContainerWidth-10+"px"); } else { $dragger.css("width",adjDraggerWidth+"px"); } } } AdjustDraggerWidth(); var targX=0; var draggerWidth=$dragger.width(); $dragger.draggable({ axis: "x", containment: "parent", drag: function(event, ui) { ScrollX(); }, stop: function(event, ui) { DraggerRelease(); } }); $dragger_container.click(function(e) { var $this=$(this); var mouseCoord=(e.pageX - $this.offset().left); if(mouseCoord<$dragger.position().left || mouseCoord>($dragger.position().left+$dragger.width())){ var targetPos=mouseCoord+$dragger.width(); if(targetPos<$dragger_container.width()){ $dragger.css("left",mouseCoord); ScrollX(); } else { $dragger.css("left",$dragger_container.width()-$dragger.width()); ScrollX(); } } }); //mousewheel $(function($) { if(mouseWheelSupport=="yes"){ $customScrollBox.unbind("mousewheel"); $customScrollBox.bind("mousewheel", function(event, delta) { var vel = Math.abs(delta*10); $dragger.css("left", $dragger.position().left-(delta*vel)); ScrollX(); if($dragger.position().left<0){ $dragger.css("left", 0); $customScrollBox_container.stop(); ScrollX(); } if($dragger.position().left>$dragger_container.width()-$dragger.width()){ $dragger.css("left", $dragger_container.width()-$dragger.width()); $customScrollBox_container.stop(); ScrollX(); } return false; }); } }); //scroll buttons if(scrollBtnsSupport=="yes"){ $scrollDownBtn.mouseup(function(){ BtnsScrollXStop(); }).mousedown(function(){ BtnsScrollX("down"); }).mouseout(function(){ BtnsScrollXStop(); }); $scrollUpBtn.mouseup(function(){ BtnsScrollXStop(); }).mousedown(function(){ BtnsScrollX("up"); }).mouseout(function(){ BtnsScrollXStop(); }); $scrollDownBtn.click(function(e) { e.preventDefault(); }); $scrollUpBtn.click(function(e) { e.preventDefault(); }); btnsScrollTimerX=0; function BtnsScrollX(dir){ if(dir=="down"){ var btnsScrollTo=$dragger_container.width()-$dragger.width(); var scrollSpeed=Math.abs($dragger.position().left-btnsScrollTo)*(100/scrollBtnsSpeed); $dragger.stop().animate({left: btnsScrollTo}, scrollSpeed,"linear"); } else { var btnsScrollTo=0; var scrollSpeed=Math.abs($dragger.position().left-btnsScrollTo)*(100/scrollBtnsSpeed); $dragger.stop().animate({left: -btnsScrollTo}, scrollSpeed,"linear"); } clearInterval(btnsScrollTimerX); btnsScrollTimerX = setInterval( ScrollX, 20); } function BtnsScrollXStop(){ clearInterval(btnsScrollTimerX); $dragger.stop(); } } //scroll var scrollAmount=(totalContent-visibleWidth)/(draggerContainerWidth-draggerWidth); function ScrollX(){ var draggerX=$dragger.position().left; var targX=-draggerX*scrollAmount; var thePos=$customScrollBox_container.position().left-targX; $customScrollBox_container.stop().animate({left: "-="+thePos}, animSpeed, easeType); } } else { //disable scrollbar if content is short $dragger.css("left",0).css("display","none"); //reset content scroll $customScrollBox_container.css("left",0); $dragger_container.css("display","none"); $scrollDownBtn.css("display","none"); $scrollUpBtn.css("display","none"); } //vertical scrolling ------------------------------ } else { var visibleHeight=$customScrollBox.height(); if($customScrollBox_container.height()>visibleHeight){ //enable scrollbar if content is long $dragger.css("display","block"); if(reloadType!="resize" && $customScrollBox_container.height()!=$customScrollBox.data("contentHeight")){ $dragger.css("top",0); $customScrollBox_container.css("top",0); $customScrollBox.data("contentHeight",$customScrollBox_container.height()); } $dragger_container.css("display","block"); $scrollDownBtn.css("display","inline-block"); $scrollUpBtn.css("display","inline-block"); var totalContent=$customScrollBox_content.height(); var minDraggerHeight=$customScrollBox.data("minDraggerHeight"); var draggerContainerHeight=$dragger_container.height(); function AdjustDraggerHeight(){ if(draggerDimType=="auto"){ var adjDraggerHeight=Math.round(totalContent-((totalContent-visibleHeight)*1.3)); //adjust dragger height analogous to content if(adjDraggerHeight<=minDraggerHeight){ //minimum dragger height $dragger.css("height",minDraggerHeight+"px").css("line-height",minDraggerHeight+"px"); } else if(adjDraggerHeight>=draggerContainerHeight){ $dragger.css("height",draggerContainerHeight-10+"px").css("line-height",draggerContainerHeight-10+"px"); } else { $dragger.css("height",adjDraggerHeight+"px").css("line-height",adjDraggerHeight+"px"); } } } AdjustDraggerHeight(); var targY=0; var draggerHeight=$dragger.height(); $dragger.draggable({ axis: "y", containment: "parent", drag: function(event, ui) { Scroll(); }, stop: function(event, ui) { DraggerRelease(); } }); $dragger_container.click(function(e) { var $this=$(this); var mouseCoord=(e.pageY - $this.offset().top); if(mouseCoord<$dragger.position().top || mouseCoord>($dragger.position().top+$dragger.height())){ var targetPos=mouseCoord+$dragger.height(); if(targetPos<$dragger_container.height()){ $dragger.css("top",mouseCoord); Scroll(); } else { $dragger.css("top",$dragger_container.height()-$dragger.height()); Scroll(); } } }); //mousewheel $(function($) { if(mouseWheelSupport=="yes"){ $customScrollBox.unbind("mousewheel"); $customScrollBox.bind("mousewheel", function(event, delta) { var vel = Math.abs(delta*10); $dragger.css("top", $dragger.position().top-(delta*vel)); Scroll(); if($dragger.position().top<0){ $dragger.css("top", 0); $customScrollBox_container.stop(); Scroll(); } if($dragger.position().top>$dragger_container.height()-$dragger.height()){ $dragger.css("top", $dragger_container.height()-$dragger.height()); $customScrollBox_container.stop(); Scroll(); } return false; }); } }); //scroll buttons if(scrollBtnsSupport=="yes"){ $scrollDownBtn.mouseup(function(){ BtnsScrollStop(); }).mousedown(function(){ BtnsScroll("down"); }).mouseout(function(){ BtnsScrollStop(); }); $scrollUpBtn.mouseup(function(){ BtnsScrollStop(); }).mousedown(function(){ BtnsScroll("up"); }).mouseout(function(){ BtnsScrollStop(); }); $scrollDownBtn.click(function(e) { e.preventDefault(); }); $scrollUpBtn.click(function(e) { e.preventDefault(); }); btnsScrollTimer=0; function BtnsScroll(dir){ if(dir=="down"){ var btnsScrollTo=$dragger_container.height()-$dragger.height(); var scrollSpeed=Math.abs($dragger.position().top-btnsScrollTo)*(100/scrollBtnsSpeed); $dragger.stop().animate({top: btnsScrollTo}, scrollSpeed,"linear"); } else { var btnsScrollTo=0; var scrollSpeed=Math.abs($dragger.position().top-btnsScrollTo)*(100/scrollBtnsSpeed); $dragger.stop().animate({top: -btnsScrollTo}, scrollSpeed,"linear"); } clearInterval(btnsScrollTimer); btnsScrollTimer = setInterval( Scroll, 20); } function BtnsScrollStop(){ clearInterval(btnsScrollTimer); $dragger.stop(); } } //scroll if(bottomSpace<1){ bottomSpace=1; //minimum bottomSpace value is 1 } var scrollAmount=(totalContent-(visibleHeight/bottomSpace))/(draggerContainerHeight-draggerHeight); function Scroll(){ var draggerY=$dragger.position().top; var targY=-draggerY*scrollAmount; var thePos=$customScrollBox_container.position().top-targY; $customScrollBox_container.stop().animate({top: "-="+thePos}, animSpeed, easeType); } } else { //disable scrollbar if content is short $dragger.css("top",0).css("display","none"); //reset content scroll $customScrollBox_container.css("top",0); $dragger_container.css("display","none"); $scrollDownBtn.css("display","none"); $scrollUpBtn.css("display","none"); } } $dragger.mouseup(function(){ DraggerRelease(); }).mousedown(function(){ DraggerPress(); }); function DraggerPress(){ $dragger.addClass("dragger_pressed"); } function DraggerRelease(){ $dragger.removeClass("dragger_pressed"); } } $(window).resize(function() { if(scrollType=="horizontal"){ if($dragger.position().left>$dragger_container.width()-$dragger.width()){ $dragger.css("left", $dragger_container.width()-$dragger.width()); } } else { if($dragger.position().top>$dragger_container.height()-$dragger.height()){ $dragger.css("top", $dragger_container.height()-$dragger.height()); } } CustomScroller("resize"); }); }; })(jQuery);
JavaScript
/*! * jQuery blockUI plugin * Version 2.59.0-2013.04.05 * @requires jQuery v1.7 or later * * Examples at: http://malsup.com/jquery/block/ * Copyright (c) 2007-2013 M. Alsup * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Thanks to Amir-Hossein Sobhi for some excellent contributions! */ ;(function() { /*jshint eqeqeq:false curly:false latedef:false */ "use strict"; function setup($) { $.fn._fadeIn = $.fn.fadeIn; var noOp = $.noop || function() {}; // this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle // retarded userAgent strings on Vista) var msie = /MSIE/.test(navigator.userAgent); var ie6 = /MSIE 6.0/.test(navigator.userAgent) && ! /MSIE 8.0/.test(navigator.userAgent); var mode = document.documentMode || 0; var setExpr = $.isFunction( document.createElement('div').style.setExpression ); // global $ methods for blocking/unblocking the entire page $.blockUI = function(opts) { install(window, opts); }; $.unblockUI = function(opts) { remove(window, opts); }; // convenience method for quick growl-like notifications (http://www.google.com/search?q=growl) $.growlUI = function(title, message, timeout, onClose) { var $m = $('<div class="growlUI"></div>'); if (title) $m.append('<h1>'+title+'</h1>'); if (message) $m.append('<h2>'+message+'</h2>'); if (timeout === undefined) timeout = 3000; $.blockUI({ message: $m, fadeIn: 700, fadeOut: 1000, centerY: false, timeout: timeout, showOverlay: false, onUnblock: onClose, css: $.blockUI.defaults.growlCSS }); }; // plugin method for blocking element content $.fn.block = function(opts) { if ( this[0] === window ) { $.blockUI( opts ); return this; } var fullOpts = $.extend({}, $.blockUI.defaults, opts || {}); this.each(function() { var $el = $(this); if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked')) return; $el.unblock({ fadeOut: 0 }); }); return this.each(function() { if ($.css(this,'position') == 'static') { this.style.position = 'relative'; $(this).data('blockUI.static', true); } this.style.zoom = 1; // force 'hasLayout' in ie install(this, opts); }); }; // plugin method for unblocking element content $.fn.unblock = function(opts) { if ( this[0] === window ) { $.unblockUI( opts ); return this; } return this.each(function() { remove(this, opts); }); }; $.blockUI.version = 2.59; // 2nd generation blocking at no extra cost! // override these in your code to change the default behavior and style $.blockUI.defaults = { // message displayed when blocking (use null for no message) message: '<h1>Please wait...</h1>', title: null, // title string; only used when theme == true draggable: true, // only used when theme == true (requires jquery-ui.js to be loaded) theme: false, // set to true to use with jQuery UI themes // styles for the message when blocking; if you wish to disable // these and use an external stylesheet then do this in your code: // $.blockUI.defaults.css = {}; css: { padding: 0, margin: 0, width: '30%', top: '40%', left: '35%', textAlign: 'center', color: '#000', border: '3px solid #aaa', backgroundColor:'#fff', cursor: 'wait' }, // minimal style set used when themes are used themedCSS: { width: '30%', top: '40%', left: '35%' }, // styles for the overlay overlayCSS: { backgroundColor: '#000', opacity: 0.6, cursor: 'wait' }, // style to replace wait cursor before unblocking to correct issue // of lingering wait cursor cursorReset: 'default', // styles applied when using $.growlUI growlCSS: { width: '350px', top: '10px', left: '', right: '10px', border: 'none', padding: '5px', opacity: 0.6, cursor: 'default', color: '#fff', backgroundColor: '#000', '-webkit-border-radius':'10px', '-moz-border-radius': '10px', 'border-radius': '10px' }, // IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w // (hat tip to Jorge H. N. de Vasconcelos) /*jshint scripturl:true */ iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', // force usage of iframe in non-IE browsers (handy for blocking applets) forceIframe: false, // z-index for the blocking overlay baseZ: 10000, // set these to true to have the message automatically centered centerX: true, // <-- only effects element blocking (page block controlled via css above) centerY: true, // allow body element to be stetched in ie6; this makes blocking look better // on "short" pages. disable if you wish to prevent changes to the body height allowBodyStretch: true, // enable if you want key and mouse events to be disabled for content that is blocked bindEvents: true, // be default blockUI will supress tab navigation from leaving blocking content // (if bindEvents is true) constrainTabKey: true, // fadeIn time in millis; set to 0 to disable fadeIn on block fadeIn: 50, // fadeOut time in millis; set to 0 to disable fadeOut on unblock fadeOut: 100, // time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock timeout: 0, // disable if you don't want to show the overlay showOverlay: true, // if true, focus will be placed in the first available input field when // page blocking focusInput: true, // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity) // no longer needed in 2012 // applyPlatformOpacityRules: true, // callback method invoked when fadeIn has completed and blocking message is visible onBlock: null, // callback method invoked when unblocking has completed; the callback is // passed the element that has been unblocked (which is the window object for page // blocks) and the options that were passed to the unblock call: // onUnblock(element, options) onUnblock: null, // callback method invoked when the overlay area is clicked. // setting this will turn the cursor to a pointer, otherwise cursor defined in overlayCss will be used. onOverlayClick: null, // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493 quirksmodeOffsetHack: 4, // class name of the message block blockMsgClass: 'blockMsg', // if it is already blocked, then ignore it (don't unblock and reblock) ignoreIfBlocked: false }; // private data and functions follow... var pageBlock = null; var pageBlockEls = []; function install(el, opts) { var css, themedCSS; var full = (el == window); var msg = (opts && opts.message !== undefined ? opts.message : undefined); opts = $.extend({}, $.blockUI.defaults, opts || {}); if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked')) return; opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {}); css = $.extend({}, $.blockUI.defaults.css, opts.css || {}); if (opts.onOverlayClick) opts.overlayCSS.cursor = 'pointer'; themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {}); msg = msg === undefined ? opts.message : msg; // remove the current block (if there is one) if (full && pageBlock) remove(window, {fadeOut:0}); // if an existing element is being used as the blocking content then we capture // its current place in the DOM (and current display style) so we can restore // it when we unblock if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) { var node = msg.jquery ? msg[0] : msg; var data = {}; $(el).data('blockUI.history', data); data.el = node; data.parent = node.parentNode; data.display = node.style.display; data.position = node.style.position; if (data.parent) data.parent.removeChild(node); } $(el).data('blockUI.onUnblock', opts.onUnblock); var z = opts.baseZ; // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform; // layer1 is the iframe layer which is used to supress bleed through of underlying content // layer2 is the overlay layer which has opacity and a wait cursor (by default) // layer3 is the message content that is displayed while blocking var lyr1, lyr2, lyr3, s; if (msie || opts.forceIframe) lyr1 = $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>'); else lyr1 = $('<div class="blockUI" style="display:none"></div>'); if (opts.theme) lyr2 = $('<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:'+ (z++) +';display:none"></div>'); else lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>'); if (opts.theme && full) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:fixed">'; if ( opts.title ) { s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>'; } s += '<div class="ui-widget-content ui-dialog-content"></div>'; s += '</div>'; } else if (opts.theme) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:absolute">'; if ( opts.title ) { s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>'; } s += '<div class="ui-widget-content ui-dialog-content"></div>'; s += '</div>'; } else if (full) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage" style="z-index:'+(z+10)+';display:none;position:fixed"></div>'; } else { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement" style="z-index:'+(z+10)+';display:none;position:absolute"></div>'; } lyr3 = $(s); // if we have a message, style it if (msg) { if (opts.theme) { lyr3.css(themedCSS); lyr3.addClass('ui-widget-content'); } else lyr3.css(css); } // style the overlay if (!opts.theme /*&& (!opts.applyPlatformOpacityRules)*/) lyr2.css(opts.overlayCSS); lyr2.css('position', full ? 'fixed' : 'absolute'); // make iframe layer transparent in IE if (msie || opts.forceIframe) lyr1.css('opacity',0.0); //$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el); var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el); $.each(layers, function() { this.appendTo($par); }); if (opts.theme && opts.draggable && $.fn.draggable) { lyr3.draggable({ handle: '.ui-dialog-titlebar', cancel: 'li' }); } // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling) var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0); if (ie6 || expr) { // give body 100% height if (full && opts.allowBodyStretch && $.support.boxModel) $('html,body').css('height','100%'); // fix ie6 issue when blocked element has a border width if ((ie6 || !$.support.boxModel) && !full) { var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth'); var fixT = t ? '(0 - '+t+')' : 0; var fixL = l ? '(0 - '+l+')' : 0; } // simulate fixed position $.each(layers, function(i,o) { var s = o[0].style; s.position = 'absolute'; if (i < 2) { if (full) s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"'); else s.setExpression('height','this.parentNode.offsetHeight + "px"'); if (full) s.setExpression('width','jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"'); else s.setExpression('width','this.parentNode.offsetWidth + "px"'); if (fixL) s.setExpression('left', fixL); if (fixT) s.setExpression('top', fixT); } else if (opts.centerY) { if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"'); s.marginTop = 0; } else if (!opts.centerY && full) { var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0; var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"'; s.setExpression('top',expression); } }); } // show the message if (msg) { if (opts.theme) lyr3.find('.ui-widget-content').append(msg); else lyr3.append(msg); if (msg.jquery || msg.nodeType) $(msg).show(); } if ((msie || opts.forceIframe) && opts.showOverlay) lyr1.show(); // opacity is zero if (opts.fadeIn) { var cb = opts.onBlock ? opts.onBlock : noOp; var cb1 = (opts.showOverlay && !msg) ? cb : noOp; var cb2 = msg ? cb : noOp; if (opts.showOverlay) lyr2._fadeIn(opts.fadeIn, cb1); if (msg) lyr3._fadeIn(opts.fadeIn, cb2); } else { if (opts.showOverlay) lyr2.show(); if (msg) lyr3.show(); if (opts.onBlock) opts.onBlock(); } // bind key and mouse events bind(1, el, opts); if (full) { pageBlock = lyr3[0]; pageBlockEls = $(':input:enabled:visible',pageBlock); if (opts.focusInput) setTimeout(focus, 20); } else center(lyr3[0], opts.centerX, opts.centerY); if (opts.timeout) { // auto-unblock var to = setTimeout(function() { if (full) $.unblockUI(opts); else $(el).unblock(opts); }, opts.timeout); $(el).data('blockUI.timeout', to); } } // remove the block function remove(el, opts) { var count; var full = (el == window); var $el = $(el); var data = $el.data('blockUI.history'); var to = $el.data('blockUI.timeout'); if (to) { clearTimeout(to); $el.removeData('blockUI.timeout'); } opts = $.extend({}, $.blockUI.defaults, opts || {}); bind(0, el, opts); // unbind events if (opts.onUnblock === null) { opts.onUnblock = $el.data('blockUI.onUnblock'); $el.removeData('blockUI.onUnblock'); } var els; if (full) // crazy selector to handle odd field errors in ie6/7 els = $('body').children().filter('.blockUI').add('body > .blockUI'); else els = $el.find('>.blockUI'); // fix cursor issue if ( opts.cursorReset ) { if ( els.length > 1 ) els[1].style.cursor = opts.cursorReset; if ( els.length > 2 ) els[2].style.cursor = opts.cursorReset; } if (full) pageBlock = pageBlockEls = null; if (opts.fadeOut) { count = els.length; els.fadeOut(opts.fadeOut, function() { if ( --count === 0) reset(els,data,opts,el); }); } else reset(els, data, opts, el); } // move blocking element back into the DOM where it started function reset(els,data,opts,el) { var $el = $(el); els.each(function(i,o) { // remove via DOM calls so we don't lose event handlers if (this.parentNode) this.parentNode.removeChild(this); }); if (data && data.el) { data.el.style.display = data.display; data.el.style.position = data.position; if (data.parent) data.parent.appendChild(data.el); $el.removeData('blockUI.history'); } if ($el.data('blockUI.static')) { $el.css('position', 'static'); // #22 } if (typeof opts.onUnblock == 'function') opts.onUnblock(el,opts); // fix issue in Safari 6 where block artifacts remain until reflow var body = $(document.body), w = body.width(), cssW = body[0].style.width; body.width(w-1).width(w); body[0].style.width = cssW; } // bind/unbind the handler function bind(b, el, opts) { var full = el == window, $el = $(el); // don't bother unbinding if there is nothing to unbind if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked'))) return; $el.data('blockUI.isBlocked', b); // don't bind events when overlay is not in use or if bindEvents is false if (!full || !opts.bindEvents || (b && !opts.showOverlay)) return; // bind anchors and inputs for mouse and key events var events = 'mousedown mouseup keydown keypress keyup touchstart touchend touchmove'; if (b) $(document).bind(events, opts, handler); else $(document).unbind(events, handler); // former impl... // var $e = $('a,:input'); // b ? $e.bind(events, opts, handler) : $e.unbind(events, handler); } // event handler to suppress keyboard/mouse events when blocking function handler(e) { // allow tab navigation (conditionally) if (e.keyCode && e.keyCode == 9) { if (pageBlock && e.data.constrainTabKey) { var els = pageBlockEls; var fwd = !e.shiftKey && e.target === els[els.length-1]; var back = e.shiftKey && e.target === els[0]; if (fwd || back) { setTimeout(function(){focus(back);},10); return false; } } } var opts = e.data; var target = $(e.target); if (target.hasClass('blockOverlay') && opts.onOverlayClick) opts.onOverlayClick(); // allow events within the message content if (target.parents('div.' + opts.blockMsgClass).length > 0) return true; // allow events for content that is not being blocked return target.parents().children().filter('div.blockUI').length === 0; } function focus(back) { if (!pageBlockEls) return; var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0]; if (e) e.focus(); } function center(el, x, y) { var p = el.parentNode, s = el.style; var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth'); var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth'); if (x) s.left = l > 0 ? (l+'px') : '0'; if (y) s.top = t > 0 ? (t+'px') : '0'; } function sz(el, p) { return parseInt($.css(el,p),10)||0; } } /*global define:true */ if (typeof define === 'function' && define.amd && define.amd.jQuery) { define(['jquery'], setup); } else { setup(jQuery); } })();
JavaScript
/*! * jQuery Cycle Plugin (with Transition Definitions) * Examples and documentation at: http://jquery.malsup.com/cycle/ * Copyright (c) 2007-2013 M. Alsup * Version: 3.0.3 (11-JUL-2013) * Dual licensed under the MIT and GPL licenses. * http://jquery.malsup.com/license.html * Requires: jQuery v1.7.1 or later */ ;(function($, undefined) { "use strict"; var ver = '3.0.3'; function debug(s) { if ($.fn.cycle.debug) log(s); } function log() { /*global console */ if (window.console && console.log) console.log('[cycle] ' + Array.prototype.join.call(arguments,' ')); } $.expr[':'].paused = function(el) { return el.cyclePause; }; // the options arg can be... // a number - indicates an immediate transition should occur to the given slide index // a string - 'pause', 'resume', 'toggle', 'next', 'prev', 'stop', 'destroy' or the name of a transition effect (ie, 'fade', 'zoom', etc) // an object - properties to control the slideshow // // the arg2 arg can be... // the name of an fx (only used in conjunction with a numeric value for 'options') // the value true (only used in first arg == 'resume') and indicates // that the resume should occur immediately (not wait for next timeout) $.fn.cycle = function(options, arg2) { var o = { s: this.selector, c: this.context }; // in 1.3+ we can fix mistakes with the ready state if (this.length === 0 && options != 'stop') { if (!$.isReady && o.s) { log('DOM not ready, queuing slideshow'); $(function() { $(o.s,o.c).cycle(options,arg2); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } // iterate the matched nodeset return this.each(function() { var opts = handleArguments(this, options, arg2); if (opts === false) return; opts.updateActivePagerLink = opts.updateActivePagerLink || $.fn.cycle.updateActivePagerLink; // stop existing slideshow for this container (if there is one) if (this.cycleTimeout) clearTimeout(this.cycleTimeout); this.cycleTimeout = this.cyclePause = 0; this.cycleStop = 0; // issue #108 var $cont = $(this); var $slides = opts.slideExpr ? $(opts.slideExpr, this) : $cont.children(); var els = $slides.get(); if (els.length < 2) { log('terminating; too few slides: ' + els.length); return; } var opts2 = buildOptions($cont, $slides, els, opts, o); if (opts2 === false) return; var startTime = opts2.continuous ? 10 : getTimeout(els[opts2.currSlide], els[opts2.nextSlide], opts2, !opts2.backwards); // if it's an auto slideshow, kick it off if (startTime) { startTime += (opts2.delay || 0); if (startTime < 10) startTime = 10; debug('first timeout: ' + startTime); this.cycleTimeout = setTimeout(function(){go(els,opts2,0,!opts.backwards);}, startTime); } }); }; function triggerPause(cont, byHover, onPager) { var opts = $(cont).data('cycle.opts'); if (!opts) return; var paused = !!cont.cyclePause; if (paused && opts.paused) opts.paused(cont, opts, byHover, onPager); else if (!paused && opts.resumed) opts.resumed(cont, opts, byHover, onPager); } // process the args that were passed to the plugin fn function handleArguments(cont, options, arg2) { if (cont.cycleStop === undefined) cont.cycleStop = 0; if (options === undefined || options === null) options = {}; if (options.constructor == String) { switch(options) { case 'destroy': case 'stop': var opts = $(cont).data('cycle.opts'); if (!opts) return false; cont.cycleStop++; // callbacks look for change if (cont.cycleTimeout) clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; if (opts.elements) $(opts.elements).stop(); $(cont).removeData('cycle.opts'); if (options == 'destroy') destroy(cont, opts); return false; case 'toggle': cont.cyclePause = (cont.cyclePause === 1) ? 0 : 1; checkInstantResume(cont.cyclePause, arg2, cont); triggerPause(cont); return false; case 'pause': cont.cyclePause = 1; triggerPause(cont); return false; case 'resume': cont.cyclePause = 0; checkInstantResume(false, arg2, cont); triggerPause(cont); return false; case 'prev': case 'next': opts = $(cont).data('cycle.opts'); if (!opts) { log('options not found, "prev/next" ignored'); return false; } if (typeof arg2 == 'string') opts.oneTimeFx = arg2; $.fn.cycle[options](opts); return false; default: options = { fx: options }; } return options; } else if (options.constructor == Number) { // go to the requested slide var num = options; options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not advance slide'); return false; } if (num < 0 || num >= options.elements.length) { log('invalid slide index: ' + num); return false; } options.nextSlide = num; if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } if (typeof arg2 == 'string') options.oneTimeFx = arg2; go(options.elements, options, 1, num >= options.currSlide); return false; } return options; function checkInstantResume(isPaused, arg2, cont) { if (!isPaused && arg2 === true) { // resume now! var options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not resume'); return false; } if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } go(options.elements, options, 1, !options.backwards); } } } function removeFilter(el, opts) { if (!$.support.opacity && opts.cleartype && el.style.filter) { try { el.style.removeAttribute('filter'); } catch(smother) {} // handle old opera versions } } // unbind event handlers function destroy(cont, opts) { if (opts.next) $(opts.next).unbind(opts.prevNextEvent); if (opts.prev) $(opts.prev).unbind(opts.prevNextEvent); if (opts.pager || opts.pagerAnchorBuilder) $.each(opts.pagerAnchors || [], function() { this.unbind().remove(); }); opts.pagerAnchors = null; $(cont).unbind('mouseenter.cycle mouseleave.cycle'); if (opts.destroy) // callback opts.destroy(opts); } // one-time initialization function buildOptions($cont, $slides, els, options, o) { var startingSlideSpecified; // support metadata plugin (v1.0 and v2.0) var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {}); var meta = $.isFunction($cont.data) ? $cont.data(opts.metaAttr) : null; if (meta) opts = $.extend(opts, meta); if (opts.autostop) opts.countdown = opts.autostopCount || els.length; var cont = $cont[0]; $cont.data('cycle.opts', opts); opts.$cont = $cont; opts.stopCount = cont.cycleStop; opts.elements = els; opts.before = opts.before ? [opts.before] : []; opts.after = opts.after ? [opts.after] : []; // push some after callbacks if (!$.support.opacity && opts.cleartype) opts.after.push(function() { removeFilter(this, opts); }); if (opts.continuous) opts.after.push(function() { go(els,opts,0,!opts.backwards); }); saveOriginalOpts(opts); // clearType corrections if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($slides); // container requires non-static position so that slides can be position within if ($cont.css('position') == 'static') $cont.css('position', 'relative'); if (opts.width) $cont.width(opts.width); if (opts.height && opts.height != 'auto') $cont.height(opts.height); if (opts.startingSlide !== undefined) { opts.startingSlide = parseInt(opts.startingSlide,10); if (opts.startingSlide >= els.length || opts.startSlide < 0) opts.startingSlide = 0; // catch bogus input else startingSlideSpecified = true; } else if (opts.backwards) opts.startingSlide = els.length - 1; else opts.startingSlide = 0; // if random, mix up the slide array if (opts.random) { opts.randomMap = []; for (var i = 0; i < els.length; i++) opts.randomMap.push(i); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); if (startingSlideSpecified) { // try to find the specified starting slide and if found set start slide index in the map accordingly for ( var cnt = 0; cnt < els.length; cnt++ ) { if ( opts.startingSlide == opts.randomMap[cnt] ) { opts.randomIndex = cnt; } } } else { opts.randomIndex = 1; opts.startingSlide = opts.randomMap[1]; } } else if (opts.startingSlide >= els.length) opts.startingSlide = 0; // catch bogus input opts.currSlide = opts.startingSlide || 0; var first = opts.startingSlide; // set position and zIndex on all the slides $slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) { var z; if (opts.backwards) z = first ? i <= first ? els.length + (i-first) : first-i : els.length-i; else z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i; $(this).css('z-index', z); }); // make sure first slide is visible $(els[first]).css('opacity',1).show(); // opacity bit needed to handle restart use case removeFilter(els[first], opts); // stretch slides if (opts.fit) { if (!opts.aspect) { if (opts.width) $slides.width(opts.width); if (opts.height && opts.height != 'auto') $slides.height(opts.height); } else { $slides.each(function(){ var $slide = $(this); var ratio = (opts.aspect === true) ? $slide.width()/$slide.height() : opts.aspect; if( opts.width && $slide.width() != opts.width ) { $slide.width( opts.width ); $slide.height( opts.width / ratio ); } if( opts.height && $slide.height() < opts.height ) { $slide.height( opts.height ); $slide.width( opts.height * ratio ); } }); } } if (opts.center && ((!opts.fit) || opts.aspect)) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } if (opts.center && !opts.fit && !opts.slideResize) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } // stretch container var reshape = (opts.containerResize || opts.containerResizeHeight) && $cont.innerHeight() < 1; if (reshape) { // do this only if container has no size http://tinyurl.com/da2oa9 var maxw = 0, maxh = 0; for(var j=0; j < els.length; j++) { var $e = $(els[j]), e = $e[0], w = $e.outerWidth(), h = $e.outerHeight(); if (!w) w = e.offsetWidth || e.width || $e.attr('width'); if (!h) h = e.offsetHeight || e.height || $e.attr('height'); maxw = w > maxw ? w : maxw; maxh = h > maxh ? h : maxh; } if (opts.containerResize && maxw > 0 && maxh > 0) $cont.css({width:maxw+'px',height:maxh+'px'}); if (opts.containerResizeHeight && maxh > 0) $cont.css({height:maxh+'px'}); } var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pause) $cont.bind('mouseenter.cycle', function(){ pauseFlag = true; this.cyclePause++; triggerPause(cont, true); }).bind('mouseleave.cycle', function(){ if (pauseFlag) this.cyclePause--; triggerPause(cont, true); }); if (supportMultiTransitions(opts) === false) return false; // apparently a lot of people use image slideshows without height/width attributes on the images. // Cycle 2.50+ requires the sizing info for every slide; this block tries to deal with that. var requeue = false; options.requeueAttempts = options.requeueAttempts || 0; $slides.each(function() { // try to get height/width of each slide var $el = $(this); this.cycleH = (opts.fit && opts.height) ? opts.height : ($el.height() || this.offsetHeight || this.height || $el.attr('height') || 0); this.cycleW = (opts.fit && opts.width) ? opts.width : ($el.width() || this.offsetWidth || this.width || $el.attr('width') || 0); if ( $el.is('img') ) { var loading = (this.cycleH === 0 && this.cycleW === 0 && !this.complete); // don't requeue for images that are still loading but have a valid size if (loading) { if (o.s && opts.requeueOnImageNotLoaded && ++options.requeueAttempts < 100) { // track retry count so we don't loop forever log(options.requeueAttempts,' - img slide not loaded, requeuing slideshow: ', this.src, this.cycleW, this.cycleH); setTimeout(function() {$(o.s,o.c).cycle(options);}, opts.requeueTimeout); requeue = true; return false; // break each loop } else { log('could not determine size of image: '+this.src, this.cycleW, this.cycleH); } } } return true; }); if (requeue) return false; opts.cssBefore = opts.cssBefore || {}; opts.cssAfter = opts.cssAfter || {}; opts.cssFirst = opts.cssFirst || {}; opts.animIn = opts.animIn || {}; opts.animOut = opts.animOut || {}; $slides.not(':eq('+first+')').css(opts.cssBefore); $($slides[first]).css(opts.cssFirst); if (opts.timeout) { opts.timeout = parseInt(opts.timeout,10); // ensure that timeout and speed settings are sane if (opts.speed.constructor == String) opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed,10); if (!opts.sync) opts.speed = opts.speed / 2; var buffer = opts.fx == 'none' ? 0 : opts.fx == 'shuffle' ? 500 : 250; while((opts.timeout - opts.speed) < buffer) // sanitize timeout opts.timeout += opts.speed; } if (opts.easing) opts.easeIn = opts.easeOut = opts.easing; if (!opts.speedIn) opts.speedIn = opts.speed; if (!opts.speedOut) opts.speedOut = opts.speed; opts.slideCount = els.length; opts.currSlide = opts.lastSlide = first; if (opts.random) { if (++opts.randomIndex == els.length) opts.randomIndex = 0; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.backwards) opts.nextSlide = opts.startingSlide === 0 ? (els.length-1) : opts.startingSlide-1; else opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1; // run transition init fn if (!opts.multiFx) { var init = $.fn.cycle.transitions[opts.fx]; if ($.isFunction(init)) init($cont, $slides, opts); else if (opts.fx != 'custom' && !opts.multiFx) { log('unknown transition: ' + opts.fx,'; slideshow terminating'); return false; } } // fire artificial events var e0 = $slides[first]; if (!opts.skipInitializationCallbacks) { if (opts.before.length) opts.before[0].apply(e0, [e0, e0, opts, true]); if (opts.after.length) opts.after[0].apply(e0, [e0, e0, opts, true]); } if (opts.next) $(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,1);}); if (opts.prev) $(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,0);}); if (opts.pager || opts.pagerAnchorBuilder) buildPager(els,opts); exposeAddSlide(opts, els); return opts; } // save off original opts so we can restore after clearing state function saveOriginalOpts(opts) { opts.original = { before: [], after: [] }; opts.original.cssBefore = $.extend({}, opts.cssBefore); opts.original.cssAfter = $.extend({}, opts.cssAfter); opts.original.animIn = $.extend({}, opts.animIn); opts.original.animOut = $.extend({}, opts.animOut); $.each(opts.before, function() { opts.original.before.push(this); }); $.each(opts.after, function() { opts.original.after.push(this); }); } function supportMultiTransitions(opts) { var i, tx, txs = $.fn.cycle.transitions; // look for multiple effects if (opts.fx.indexOf(',') > 0) { opts.multiFx = true; opts.fxs = opts.fx.replace(/\s*/g,'').split(','); // discard any bogus effect names for (i=0; i < opts.fxs.length; i++) { var fx = opts.fxs[i]; tx = txs[fx]; if (!tx || !txs.hasOwnProperty(fx) || !$.isFunction(tx)) { log('discarding unknown transition: ',fx); opts.fxs.splice(i,1); i--; } } // if we have an empty list then we threw everything away! if (!opts.fxs.length) { log('No valid transitions named; slideshow terminating.'); return false; } } else if (opts.fx == 'all') { // auto-gen the list of transitions opts.multiFx = true; opts.fxs = []; for (var p in txs) { if (txs.hasOwnProperty(p)) { tx = txs[p]; if (txs.hasOwnProperty(p) && $.isFunction(tx)) opts.fxs.push(p); } } } if (opts.multiFx && opts.randomizeEffects) { // munge the fxs array to make effect selection random var r1 = Math.floor(Math.random() * 20) + 30; for (i = 0; i < r1; i++) { var r2 = Math.floor(Math.random() * opts.fxs.length); opts.fxs.push(opts.fxs.splice(r2,1)[0]); } debug('randomized fx sequence: ',opts.fxs); } return true; } // provide a mechanism for adding slides after the slideshow has started function exposeAddSlide(opts, els) { opts.addSlide = function(newSlide, prepend) { var $s = $(newSlide), s = $s[0]; if (!opts.autostopCount) opts.countdown++; els[prepend?'unshift':'push'](s); if (opts.els) opts.els[prepend?'unshift':'push'](s); // shuffle needs this opts.slideCount = els.length; // add the slide to the random map and resort if (opts.random) { opts.randomMap.push(opts.slideCount-1); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } $s.css('position','absolute'); $s[prepend?'prependTo':'appendTo'](opts.$cont); if (prepend) { opts.currSlide++; opts.nextSlide++; } if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($s); if (opts.fit && opts.width) $s.width(opts.width); if (opts.fit && opts.height && opts.height != 'auto') $s.height(opts.height); s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height(); s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width(); $s.css(opts.cssBefore); if (opts.pager || opts.pagerAnchorBuilder) $.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts); if ($.isFunction(opts.onAddSlide)) opts.onAddSlide($s); else $s.hide(); // default behavior }; } // reset internal state; we do this on every pass in order to support multiple effects $.fn.cycle.resetState = function(opts, fx) { fx = fx || opts.fx; opts.before = []; opts.after = []; opts.cssBefore = $.extend({}, opts.original.cssBefore); opts.cssAfter = $.extend({}, opts.original.cssAfter); opts.animIn = $.extend({}, opts.original.animIn); opts.animOut = $.extend({}, opts.original.animOut); opts.fxFn = null; $.each(opts.original.before, function() { opts.before.push(this); }); $.each(opts.original.after, function() { opts.after.push(this); }); // re-init var init = $.fn.cycle.transitions[fx]; if ($.isFunction(init)) init(opts.$cont, $(opts.elements), opts); }; // this is the main engine fn, it handles the timeouts, callbacks and slide index mgmt function go(els, opts, manual, fwd) { var p = opts.$cont[0], curr = els[opts.currSlide], next = els[opts.nextSlide]; // opts.busy is true if we're in the middle of an animation if (manual && opts.busy && opts.manualTrump) { // let manual transitions requests trump active ones debug('manualTrump in go(), stopping active transition'); $(els).stop(true,true); opts.busy = 0; clearTimeout(p.cycleTimeout); } // don't begin another timeout-based transition if there is one active if (opts.busy) { debug('transition active, ignoring new tx request'); return; } // stop cycling if we have an outstanding stop request if (p.cycleStop != opts.stopCount || p.cycleTimeout === 0 && !manual) return; // check to see if we should stop cycling based on autostop options if (!manual && !p.cyclePause && !opts.bounce && ((opts.autostop && (--opts.countdown <= 0)) || (opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) { if (opts.end) opts.end(opts); return; } // if slideshow is paused, only transition on a manual trigger var changed = false; if ((manual || !p.cyclePause) && (opts.nextSlide != opts.currSlide)) { changed = true; var fx = opts.fx; // keep trying to get the slide size if we don't have it yet curr.cycleH = curr.cycleH || $(curr).height(); curr.cycleW = curr.cycleW || $(curr).width(); next.cycleH = next.cycleH || $(next).height(); next.cycleW = next.cycleW || $(next).width(); // support multiple transition types if (opts.multiFx) { if (fwd && (opts.lastFx === undefined || ++opts.lastFx >= opts.fxs.length)) opts.lastFx = 0; else if (!fwd && (opts.lastFx === undefined || --opts.lastFx < 0)) opts.lastFx = opts.fxs.length - 1; fx = opts.fxs[opts.lastFx]; } // one-time fx overrides apply to: $('div').cycle(3,'zoom'); if (opts.oneTimeFx) { fx = opts.oneTimeFx; opts.oneTimeFx = null; } $.fn.cycle.resetState(opts, fx); // run the before callbacks if (opts.before.length) $.each(opts.before, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); // stage the after callacks var after = function() { opts.busy = 0; $.each(opts.after, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); if (!p.cycleStop) { // queue next transition queueNext(); } }; debug('tx firing('+fx+'); currSlide: ' + opts.currSlide + '; nextSlide: ' + opts.nextSlide); // get ready to perform the transition opts.busy = 1; if (opts.fxFn) // fx function provided? opts.fxFn(curr, next, opts, after, fwd, manual && opts.fastOnEvent); else if ($.isFunction($.fn.cycle[opts.fx])) // fx plugin ? $.fn.cycle[opts.fx](curr, next, opts, after, fwd, manual && opts.fastOnEvent); else $.fn.cycle.custom(curr, next, opts, after, fwd, manual && opts.fastOnEvent); } else { queueNext(); } if (changed || opts.nextSlide == opts.currSlide) { // calculate the next slide var roll; opts.lastSlide = opts.currSlide; if (opts.random) { opts.currSlide = opts.nextSlide; if (++opts.randomIndex == els.length) { opts.randomIndex = 0; opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } opts.nextSlide = opts.randomMap[opts.randomIndex]; if (opts.nextSlide == opts.currSlide) opts.nextSlide = (opts.currSlide == opts.slideCount - 1) ? 0 : opts.currSlide + 1; } else if (opts.backwards) { roll = (opts.nextSlide - 1) < 0; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = 1; opts.currSlide = 0; } else { opts.nextSlide = roll ? (els.length-1) : opts.nextSlide-1; opts.currSlide = roll ? 0 : opts.nextSlide+1; } } else { // sequence roll = (opts.nextSlide + 1) == els.length; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = els.length-2; opts.currSlide = els.length-1; } else { opts.nextSlide = roll ? 0 : opts.nextSlide+1; opts.currSlide = roll ? els.length-1 : opts.nextSlide-1; } } } if (changed && opts.pager) opts.updateActivePagerLink(opts.pager, opts.currSlide, opts.activePagerClass); function queueNext() { // stage the next transition var ms = 0, timeout = opts.timeout; if (opts.timeout && !opts.continuous) { ms = getTimeout(els[opts.currSlide], els[opts.nextSlide], opts, fwd); if (opts.fx == 'shuffle') ms -= opts.speedOut; } else if (opts.continuous && p.cyclePause) // continuous shows work off an after callback, not this timer logic ms = 10; if (ms > 0) p.cycleTimeout = setTimeout(function(){ go(els, opts, 0, !opts.backwards); }, ms); } } // invoked after transition $.fn.cycle.updateActivePagerLink = function(pager, currSlide, clsName) { $(pager).each(function() { $(this).children().removeClass(clsName).eq(currSlide).addClass(clsName); }); }; // calculate timeout value for current transition function getTimeout(curr, next, opts, fwd) { if (opts.timeoutFn) { // call user provided calc fn var t = opts.timeoutFn.call(curr,curr,next,opts,fwd); while (opts.fx != 'none' && (t - opts.speed) < 250) // sanitize timeout t += opts.speed; debug('calculated timeout: ' + t + '; speed: ' + opts.speed); if (t !== false) return t; } return opts.timeout; } // expose next/prev function, caller must pass in state $.fn.cycle.next = function(opts) { advance(opts,1); }; $.fn.cycle.prev = function(opts) { advance(opts,0);}; // advance slide forward or back function advance(opts, moveForward) { var val = moveForward ? 1 : -1; var els = opts.elements; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } if (opts.random && val < 0) { // move back to the previously display slide opts.randomIndex--; if (--opts.randomIndex == -2) opts.randomIndex = els.length-2; else if (opts.randomIndex == -1) opts.randomIndex = els.length-1; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.random) { opts.nextSlide = opts.randomMap[opts.randomIndex]; } else { opts.nextSlide = opts.currSlide + val; if (opts.nextSlide < 0) { if (opts.nowrap) return false; opts.nextSlide = els.length - 1; } else if (opts.nextSlide >= els.length) { if (opts.nowrap) return false; opts.nextSlide = 0; } } var cb = opts.onPrevNextEvent || opts.prevNextClick; // prevNextClick is deprecated if ($.isFunction(cb)) cb(val > 0, opts.nextSlide, els[opts.nextSlide]); go(els, opts, 1, moveForward); return false; } function buildPager(els, opts) { var $p = $(opts.pager); $.each(els, function(i,o) { $.fn.cycle.createPagerAnchor(i,o,$p,els,opts); }); opts.updateActivePagerLink(opts.pager, opts.startingSlide, opts.activePagerClass); } $.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) { var a; if ($.isFunction(opts.pagerAnchorBuilder)) { a = opts.pagerAnchorBuilder(i,el); debug('pagerAnchorBuilder('+i+', el) returned: ' + a); } else a = '<a href="#">'+(i+1)+'</a>'; if (!a) return; var $a = $(a); // don't reparent if anchor is in the dom if ($a.parents('body').length === 0) { var arr = []; if ($p.length > 1) { $p.each(function() { var $clone = $a.clone(true); $(this).append($clone); arr.push($clone[0]); }); $a = $(arr); } else { $a.appendTo($p); } } opts.pagerAnchors = opts.pagerAnchors || []; opts.pagerAnchors.push($a); var pagerFn = function(e) { e.preventDefault(); opts.nextSlide = i; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } var cb = opts.onPagerEvent || opts.pagerClick; // pagerClick is deprecated if ($.isFunction(cb)) cb(opts.nextSlide, els[opts.nextSlide]); go(els,opts,1,opts.currSlide < i); // trigger the trans // return false; // <== allow bubble }; if ( /mouseenter|mouseover/i.test(opts.pagerEvent) ) { $a.hover(pagerFn, function(){/* no-op */} ); } else { $a.bind(opts.pagerEvent, pagerFn); } if ( ! /^click/.test(opts.pagerEvent) && !opts.allowPagerClickBubble) $a.bind('click.cycle', function(){return false;}); // suppress click var cont = opts.$cont[0]; var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pauseOnPagerHover) { $a.hover( function() { pauseFlag = true; cont.cyclePause++; triggerPause(cont,true,true); }, function() { if (pauseFlag) cont.cyclePause--; triggerPause(cont,true,true); } ); } }; // helper fn to calculate the number of slides between the current and the next $.fn.cycle.hopsFromLast = function(opts, fwd) { var hops, l = opts.lastSlide, c = opts.currSlide; if (fwd) hops = c > l ? c - l : opts.slideCount - l; else hops = c < l ? l - c : l + opts.slideCount - c; return hops; }; // fix clearType problems in ie6 by setting an explicit bg color // (otherwise text slides look horrible during a fade transition) function clearTypeFix($slides) { debug('applying clearType background-color hack'); function hex(s) { s = parseInt(s,10).toString(16); return s.length < 2 ? '0'+s : s; } function getBg(e) { for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) { var v = $.css(e,'background-color'); if (v && v.indexOf('rgb') >= 0 ) { var rgb = v.match(/\d+/g); return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]); } if (v && v != 'transparent') return v; } return '#ffffff'; } $slides.each(function() { $(this).css('background-color', getBg(this)); }); } // reset common props before the next transition $.fn.cycle.commonReset = function(curr,next,opts,w,h,rev) { $(opts.elements).not(curr).hide(); if (typeof opts.cssBefore.opacity == 'undefined') opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; if (opts.slideResize && w !== false && next.cycleW > 0) opts.cssBefore.width = next.cycleW; if (opts.slideResize && h !== false && next.cycleH > 0) opts.cssBefore.height = next.cycleH; opts.cssAfter = opts.cssAfter || {}; opts.cssAfter.display = 'none'; $(curr).css('zIndex',opts.slideCount + (rev === true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev === true ? 0 : 1)); }; // the actual fn for effecting a transition $.fn.cycle.custom = function(curr, next, opts, cb, fwd, speedOverride) { var $l = $(curr), $n = $(next); var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut, animInDelay = opts.animInDelay, animOutDelay = opts.animOutDelay; $n.css(opts.cssBefore); if (speedOverride) { if (typeof speedOverride == 'number') speedIn = speedOut = speedOverride; else speedIn = speedOut = 1; easeIn = easeOut = null; } var fn = function() { $n.delay(animInDelay).animate(opts.animIn, speedIn, easeIn, function() { cb(); }); }; $l.delay(animOutDelay).animate(opts.animOut, speedOut, easeOut, function() { $l.css(opts.cssAfter); if (!opts.sync) fn(); }); if (opts.sync) fn(); }; // transition definitions - only fade is defined here, transition pack defines the rest $.fn.cycle.transitions = { fade: function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css('opacity',0); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.opacity = 0; }); opts.animIn = { opacity: 1 }; opts.animOut = { opacity: 0 }; opts.cssBefore = { top: 0, left: 0 }; } }; $.fn.cycle.ver = function() { return ver; }; // override these globally if you like (they are all optional) $.fn.cycle.defaults = { activePagerClass: 'activeSlide', // class name used for the active pager link after: null, // transition callback (scope set to element that was shown): function(currSlideElement, nextSlideElement, options, forwardFlag) allowPagerClickBubble: false, // allows or prevents click event on pager anchors from bubbling animIn: null, // properties that define how the slide animates in animInDelay: 0, // allows delay before next slide transitions in animOut: null, // properties that define how the slide animates out animOutDelay: 0, // allows delay before current slide transitions out aspect: false, // preserve aspect ratio during fit resizing, cropping if necessary (must be used with fit option) autostop: 0, // true to end slideshow after X transitions (where X == slide count) autostopCount: 0, // number of transitions (optionally used with autostop to define X) backwards: false, // true to start slideshow at last slide and move backwards through the stack before: null, // transition callback (scope set to element to be shown): function(currSlideElement, nextSlideElement, options, forwardFlag) center: null, // set to true to have cycle add top/left margin to each slide (use with width and height options) cleartype: !$.support.opacity, // true if clearType corrections should be applied (for IE) cleartypeNoBg: false, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides) containerResize: 1, // resize container to fit largest slide containerResizeHeight: 0, // resize containers height to fit the largest slide but leave the width dynamic continuous: 0, // true to start next transition immediately after current one completes cssAfter: null, // properties that defined the state of the slide after transitioning out cssBefore: null, // properties that define the initial state of the slide before transitioning in delay: 0, // additional delay (in ms) for first transition (hint: can be negative) easeIn: null, // easing for "in" transition easeOut: null, // easing for "out" transition easing: null, // easing method for both in and out transitions end: null, // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options) fastOnEvent: 0, // force fast transitions when triggered manually (via pager or prev/next); value == time in ms fit: 0, // force slides to fit container fx: 'fade', // name of transition effect (or comma separated names, ex: 'fade,scrollUp,shuffle') fxFn: null, // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag) height: 'auto', // container height (if the 'fit' option is true, the slides will be set to this height as well) manualTrump: true, // causes manual transition to stop an active transition instead of being ignored metaAttr: 'cycle', // data- attribute that holds the option data for the slideshow next: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for next slide nowrap: 0, // true to prevent slideshow from wrapping onPagerEvent: null, // callback fn for pager events: function(zeroBasedSlideIndex, slideElement) onPrevNextEvent: null, // callback fn for prev/next events: function(isNext, zeroBasedSlideIndex, slideElement) pager: null, // element, jQuery object, or jQuery selector string for the element to use as pager container pagerAnchorBuilder: null, // callback fn for building anchor links: function(index, DOMelement) pagerEvent: 'click.cycle', // name of event which drives the pager navigation pause: 0, // true to enable "pause on hover" pauseOnPagerHover: 0, // true to pause when hovering over pager link prev: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for previous slide prevNextEvent: 'click.cycle',// event which drives the manual transition to the previous or next slide random: 0, // true for random, false for sequence (not applicable to shuffle fx) randomizeEffects: 1, // valid when multiple effects are used; true to make the effect sequence random requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded requeueTimeout: 250, // ms delay for requeue rev: 0, // causes animations to transition in reverse (for effects that support it such as scrollHorz/scrollVert/shuffle) shuffle: null, // coords for shuffle animation, ex: { top:15, left: 200 } skipInitializationCallbacks: false, // set to true to disable the first before/after callback that occurs prior to any transition slideExpr: null, // expression for selecting slides (if something other than all children is required) slideResize: 1, // force slide width/height to fixed size before every transition speed: 1000, // speed of the transition (any valid fx speed value) speedIn: null, // speed of the 'in' transition speedOut: null, // speed of the 'out' transition startingSlide: undefined,// zero-based index of the first slide to be displayed sync: 1, // true if in/out transitions should occur simultaneously timeout: 4000, // milliseconds between slide transitions (0 to disable auto advance) timeoutFn: null, // callback for determining per-slide timeout value: function(currSlideElement, nextSlideElement, options, forwardFlag) updateActivePagerLink: null,// callback fn invoked to update the active pager link (adds/removes activePagerClass style) width: null // container width (if the 'fit' option is true, the slides will be set to this width as well) }; })(jQuery); /*! * jQuery Cycle Plugin Transition Definitions * This script is a plugin for the jQuery Cycle Plugin * Examples and documentation at: http://malsup.com/jquery/cycle/ * Copyright (c) 2007-2010 M. Alsup * Version: 2.73 * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function($) { "use strict"; // // These functions define slide initialization and properties for the named // transitions. To save file size feel free to remove any of these that you // don't need. // $.fn.cycle.transitions.none = function($cont, $slides, opts) { opts.fxFn = function(curr,next,opts,after){ $(next).show(); $(curr).hide(); after(); }; }; // not a cross-fade, fadeout only fades out the top slide $.fn.cycle.transitions.fadeout = function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css({ display: 'block', 'opacity': 1 }); opts.before.push(function(curr,next,opts,w,h,rev) { $(curr).css('zIndex',opts.slideCount + (rev !== true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev !== true ? 0 : 1)); }); opts.animIn.opacity = 1; opts.animOut.opacity = 0; opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; opts.cssAfter.zIndex = 0; }; // scrollUp/Down/Left/Right $.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.cssFirst.top = 0; opts.animIn.top = 0; opts.animOut.top = -h; }; $.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssFirst.top = 0; opts.cssBefore.top = -h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; $.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = 0-w; }; $.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = -w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; $.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) { $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW); opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW; }); opts.cssFirst.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.top = 0; }; $.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.top = fwd ? (1-next.cycleH) : (next.cycleH-1); opts.animOut.top = fwd ? curr.cycleH : -curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.left = 0; }; // slideX/slideY $.fn.cycle.transitions.slideX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.width = 'show'; opts.animOut.width = 0; }; $.fn.cycle.transitions.slideY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animIn.height = 'show'; opts.animOut.height = 0; }; // shuffle $.fn.cycle.transitions.shuffle = function($cont, $slides, opts) { var i, w = $cont.css('overflow', 'visible').width(); $slides.css({left: 0, top: 0}); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); }); // only adjust speed once! if (!opts.speedAdjusted) { opts.speed = opts.speed / 2; // shuffle has 2 transitions opts.speedAdjusted = true; } opts.random = 0; opts.shuffle = opts.shuffle || {left:-w, top:15}; opts.els = []; for (i=0; i < $slides.length; i++) opts.els.push($slides[i]); for (i=0; i < opts.currSlide; i++) opts.els.push(opts.els.shift()); // custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!) opts.fxFn = function(curr, next, opts, cb, fwd) { if (opts.rev) fwd = !fwd; var $el = fwd ? $(curr) : $(next); $(next).css(opts.cssBefore); var count = opts.slideCount; $el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() { var hops = $.fn.cycle.hopsFromLast(opts, fwd); for (var k=0; k < hops; k++) { if (fwd) opts.els.push(opts.els.shift()); else opts.els.unshift(opts.els.pop()); } if (fwd) { for (var i=0, len=opts.els.length; i < len; i++) $(opts.els[i]).css('z-index', len-i+count); } else { var z = $(curr).css('z-index'); $el.css('z-index', parseInt(z,10)+1+count); } $el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() { $(fwd ? this : curr).hide(); if (cb) cb(); }); }); }; $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); }; // turnUp/Down/Left/Right $.fn.cycle.transitions.turnUp = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = next.cycleH; opts.animIn.height = next.cycleH; opts.animOut.width = next.cycleW; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.height = 0; opts.animIn.top = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnDown = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = next.cycleW; opts.animIn.width = next.cycleW; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.left = 0; opts.animOut.width = 0; }; $.fn.cycle.transitions.turnRight = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); $.extend(opts.cssBefore, { top: 0, left: 0, width: 0 }); opts.animIn.left = 0; opts.animOut.width = 0; }; // zoom $.fn.cycle.transitions.zoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false,true); opts.cssBefore.top = next.cycleH/2; opts.cssBefore.left = next.cycleW/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); $.extend(opts.animOut, { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 }); }); opts.cssFirst.top = 0; opts.cssFirst.left = 0; opts.cssBefore.width = 0; opts.cssBefore.height = 0; }; // fadeZoom $.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false); opts.cssBefore.left = next.cycleW/2; opts.cssBefore.top = next.cycleH/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); }); opts.cssBefore.width = 0; opts.cssBefore.height = 0; opts.animOut.opacity = 0; }; // blindX $.fn.cycle.transitions.blindX = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; // blindY $.fn.cycle.transitions.blindY = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; // blindZ $.fn.cycle.transitions.blindZ = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); var w = $cont.width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = w; opts.animIn.top = 0; opts.animIn.left = 0; opts.animOut.top = h; opts.animOut.left = w; }; // growX - grow horizontally from centered 0 width $.fn.cycle.transitions.growX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = this.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // growY - grow vertically from centered 0 height $.fn.cycle.transitions.growY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = this.cycleH/2; opts.animIn.top = 0; opts.animIn.height = this.cycleH; opts.animOut.top = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // curtainX - squeeze in both edges horizontally $.fn.cycle.transitions.curtainX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true,true); opts.cssBefore.left = next.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = curr.cycleW/2; opts.animOut.width = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // curtainY - squeeze in both edges vertically $.fn.cycle.transitions.curtainY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false,true); opts.cssBefore.top = next.cycleH/2; opts.animIn.top = 0; opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH/2; opts.animOut.height = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // cover - curr slide covered by next slide $.fn.cycle.transitions.cover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssAfter.display = ''; if (d == 'right') opts.cssBefore.left = -w; else if (d == 'up') opts.cssBefore.top = h; else if (d == 'down') opts.cssBefore.top = -h; else opts.cssBefore.left = w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // uncover - curr slide moves off next slide $.fn.cycle.transitions.uncover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); if (d == 'right') opts.animOut.left = w; else if (d == 'up') opts.animOut.top = -h; else if (d == 'down') opts.animOut.top = h; else opts.animOut.left = -w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // toss - move top slide and fade away $.fn.cycle.transitions.toss = function($cont, $slides, opts) { var w = $cont.css('overflow','visible').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); // provide default toss settings if animOut not provided if (!opts.animOut.left && !opts.animOut.top) $.extend(opts.animOut, { left: w*2, top: -h/2, opacity: 0 }); else opts.animOut.opacity = 0; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; }; // wipe - clip animation $.fn.cycle.transitions.wipe = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.cssBefore = opts.cssBefore || {}; var clip; if (opts.clip) { if (/l2r/.test(opts.clip)) clip = 'rect(0px 0px '+h+'px 0px)'; else if (/r2l/.test(opts.clip)) clip = 'rect(0px '+w+'px '+h+'px '+w+'px)'; else if (/t2b/.test(opts.clip)) clip = 'rect(0px '+w+'px 0px 0px)'; else if (/b2t/.test(opts.clip)) clip = 'rect('+h+'px '+w+'px '+h+'px 0px)'; else if (/zoom/.test(opts.clip)) { var top = parseInt(h/2,10); var left = parseInt(w/2,10); clip = 'rect('+top+'px '+left+'px '+top+'px '+left+'px)'; } } opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)'; var d = opts.cssBefore.clip.match(/(\d+)/g); var t = parseInt(d[0],10), r = parseInt(d[1],10), b = parseInt(d[2],10), l = parseInt(d[3],10); opts.before.push(function(curr, next, opts) { if (curr == next) return; var $curr = $(curr), $next = $(next); $.fn.cycle.commonReset(curr,next,opts,true,true,false); opts.cssAfter.display = 'block'; var step = 1, count = parseInt((opts.speedIn / 13),10) - 1; (function f() { var tt = t ? t - parseInt(step * (t/count),10) : 0; var ll = l ? l - parseInt(step * (l/count),10) : 0; var bb = b < h ? b + parseInt(step * ((h-b)/count || 1),10) : h; var rr = r < w ? r + parseInt(step * ((w-r)/count || 1),10) : w; $next.css({ clip: 'rect('+tt+'px '+rr+'px '+bb+'px '+ll+'px)' }); (step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none'); })(); }); $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); opts.animIn = { left: 0 }; opts.animOut = { left: 0 }; }; })(jQuery);
JavaScript
if (typeof $ !== "undefined"){ $('head').append('<style type="text/css">.stickyleft{ width:150px; position:fixed; left:50px; bottom:0; height:300px }.stickyleft div{ margin-top:3px!important }</style>'); $("body").append('<div class="stickyleft" id="stickyleft"><a href="http://www.tinmoi.vn/C/dap-an-de-thi-tot-nghiep-thpt-2014" target="_blank"><img width="150" height="300" src="http://www.doisongphapluat.com/images/ads/150x300.gif" title="" alt=""></a></div>'); (function(){ var obj = $('#stickyleft'); var fixAds = function(){ var rate = screen.width/$(window).width(); console.log(rate); var x = Math.floor(((screen.width - (1020 * rate) - (2*rate*obj.width())) / 2)/ rate); obj.css({ left : x > 0 ? x : 0-obj.width() }); }; fixAds(); $(window).resize(function(){ fixAds(); }); $(window).scroll(function(){ obj.css({ bottom : $(document).scrollTop() > 160 ? 0 : 0 }); }); })(); }
JavaScript
var mobile = function(){ return { detect:function(){ var uagent = navigator.userAgent.toLowerCase(); var list = this.mobiles; var ismobile = false; for(var d=0;d<list.length;d+=1){ if(uagent.indexOf(list[d])!=-1){ ismobile = true; } } return ismobile; }, mobiles:[ "midp","240x320","blackberry","netfront","nokia","panasonic", "portalmmm","sharp","sie-","sonyericsson","symbian", "windows ce","benq","mda","mot-","opera mini", "philips","pocket pc","sagem","samsung","sda", "sgh-","vodafone","xda","palm","iphone", "ipod","android" ], setCookie:function(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value + ";" + 'path=/'; }, getCookie:function(c_name) { var c_value = document.cookie; var c_start = c_value.indexOf(" " + c_name + "="); if (c_start == -1) { c_start = c_value.indexOf(c_name + "="); } if (c_start == -1) { c_value = null; } else { c_start = c_value.indexOf("=", c_start) + 1; var c_end = c_value.indexOf(";", c_start); if (c_end == -1) { c_end = c_value.length; } c_value = unescape(c_value.substring(c_start,c_end)); } return c_value; } }; }(); uri = window.location.pathname; query_string = window.location.search; ui = 1; if (/ui\=desktop/.test(query_string)){ mobile.setCookie('is_mobile_detected', 'no', 1); ui = 0; } allow_redirect = 0; if (/^\/su-kien\/(\d+)/.test(uri) || /^\/tag/.test(uri) || /^\/gioithieu\.html/.test(uri) || /^\/dich-vu\.html/.test(uri) || /^\/lien-quan/.test(uri)){ allow_redirect = 0; } else if (uri == "/" || "" || /\/photo/.test(uri) || /\/photo\/page\/(\d+)/.test(uri) || /\/photo\/(\w+)/.test(uri) || /\/photo\/(\w+)\/page\/(\d+)/.test(uri) || /\.html/.test(uri) || /\/([a-zA-Z0-9\-\/]+)\/page\/(\d+)/.test(uri) || /\/([a-zA-Z0-9\-\/]+)/.test(uri) ){ allow_redirect = 1; } if(allow_redirect && ui){ var checker = mobile.getCookie('is_mobile_detected'); if (checker === null) { if (mobile.detect()) { mobile.setCookie('is_mobile_detected', 'yes', 1); //window.location="http://m.doisongphapluat.com" + uri; } else { mobile.setCookie('is_mobile_detected', 'no', 1); } } else { if (checker === 'yes') { //window.location="http://m.doisongphapluat.com" + uri; } } }
JavaScript
(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/vi_VN/all.js#xfbml=1&appId=197055007120496"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); function share_facebook(url){ //u= '{/literal}{$data.link}{literal}'; title = document.title; window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(url)+'&t='+encodeURIComponent(title),'sharer','toolbar=0,status=0,width=626,height=436'); }
JavaScript
$(document).ready(function(){ $("#weather-sl").toggle(function(){ $(".weather-city").css('display','block'); }, function(){ $(".weather-city").css('display','none'); }); setInterval(clockRealtime, 1000); getWeatherInfo(); }); function clockRealtime() { var now = new Date(); curHour = now.getHours(); _curHour = (curHour <= 12) ? curHour : (curHour-12); curMinute = now.getMinutes(); if (curMinute < 10) { curMinute = "0" + curMinute; } var clock = '<span class="hour">'+_curHour+'</span> <span class="min">'+curMinute; if (curHour <= 12) { clock += '<strong>AM</strong></span>'; } else { clock += '<strong>PM</strong></span>'; } $('.datetime').find('.clock').html(clock); } function makeid() { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for( var i=0; i < 5; i++ ) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } function getWeatherInfo() { $.ajax({ url : '/', type : 'GET', data : {act : 'Weather',r:makeid()}, success : function(json) { var data = jQuery.parseJSON(json); $('.weather').html(data); } }); } $(window).load(function() { mCustomScrollbars(); }); function mCustomScrollbars(){ $("#mcs_container").mCustomScrollbar("vertical",400,"easeOutCirc",1.05,"auto","yes","yes",10); $("#mcs_container3").mCustomScrollbar("vertical",400,"easeOutCirc",1.05,"auto","yes","yes",10); } /* function to fix the -10000 pixel limit of jquery.animate */ $.fx.prototype.cur = function(){ if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var r = parseFloat( jQuery.css( this.elem, this.prop ) ); return typeof r == 'undefined' ? 0 : r; } /* function to load new content dynamically */ function LoadNewContent(id,file){ $("#"+id+" .customScrollBox .content").load(file,function(){ mCustomScrollbars(); }); } //scrollbar
JavaScript
/** * Plugin: jquery.zWeatherFeed * * Version: 1.2.1 * (c) Copyright 2011-2013, Zazar Ltd * * Description: jQuery plugin for display of Yahoo! Weather feeds * * History: * 1.2.1 - Handle invalid locations * 1.2.0 - Added forecast data option * 1.1.0 - Added user callback function * New option to use WOEID identifiers * New day/night CSS class for feed items * Updated full forecast link to feed link location * 1.0.3 - Changed full forecast link to Weather Channel due to invalid Yahoo! link Add 'linktarget' option for forecast link * 1.0.2 - Correction to options / link * 1.0.1 - Added hourly caching to YQL to avoid rate limits * Uses Weather Channel location ID and not Yahoo WOEID * Displays day or night background images * **/ (function($){ $.fn.weatherfeed = function(locations, options, fn) { //alert(locations); // Set plugin defaults var defaults = { unit: 'c', image: true, country: false, highlow: true, wind: true, humidity: false, visibility: false, sunrise: false, sunset: false, forecast: false, link: true, showerror: true, linktarget: '_self', woeid: false }; var options = $.extend(defaults, options); var row = 'odd'; // Functions return this.each(function(i, e) { var $e = $(e); // Add feed class to user div if (!$e.hasClass('weatherFeed')) $e.addClass('weatherFeed'); // Check and append locations if (!$.isArray(locations)) return false; var count = locations.length; if (count > 10) count = 10; var locationid = ''; for (var i=0; i<count; i++) { if (locationid != '') locationid += ','; locationid += "'"+ locations[i] + "'"; } // Cache results for an hour to prevent overuse now = new Date(); // Select location ID type var queryType = options.woeid ? 'woeid' : 'location'; // Create Yahoo Weather feed API address var query = "select * from weather.forecast where "+ queryType +" in ("+ locationid +") and u='"+ options.unit +"'"; var api = 'http://query.yahooapis.com/v1/public/yql?q='+ encodeURIComponent(query) +'&rnd='+ now.getFullYear() + now.getMonth() + now.getDay() + now.getHours() +'&format=json&callback=?'; console.log(api);//alert(api); // Send request $.ajax({ type: 'GET', url: api, dataType: 'json', success: function(data) { if (data.query) { if (data.query.results.channel.length > 0 ) { // Multiple locations var result = data.query.results.channel.length; for (var i=0; i<result; i++) { // Create weather feed item _process(e, data.query.results.channel[i], options); } } else { // Single location only _process(e, data.query.results.channel, options); } //alert(JSON.stringify(data.query.results.channel)); // Optional user callback function if ($.isFunction(fn)) fn.call(this,$e); } else { if (options.showerror) $e.html('<p>Weather information unavailable</p>'); } }, error: function(data) { if (options.showerror) $e.html('<p>Weather request failed</p>'); } }); // Function to each feed item var _process = function(e, feed, options) { var $e = $(e); // Check for invalid location if (feed.description != 'Yahoo! Weather Error') { // Format feed items var wd = feed.wind.direction; if (wd>=348.75&&wd<=360){wd="N"};if(wd>=0&&wd<11.25){wd="N"};if(wd>=11.25&&wd<33.75){wd="NNE"};if(wd>=33.75&&wd<56.25){wd="NE"};if(wd>=56.25&&wd<78.75){wd="ENE"};if(wd>=78.75&&wd<101.25){wd="E"};if(wd>=101.25&&wd<123.75){wd="ESE"};if(wd>=123.75&&wd<146.25){wd="SE"};if(wd>=146.25&&wd<168.75){wd="SSE"};if(wd>=168.75&&wd<191.25){wd="S"};if(wd>=191.25 && wd<213.75){wd="SSW"};if(wd>=213.75&&wd<236.25){wd="SW"};if(wd>=236.25&&wd<258.75){wd="WSW"};if(wd>=258.75 && wd<281.25){wd="W"};if(wd>=281.25&&wd<303.75){wd="WNW"};if(wd>=303.75&&wd<326.25){wd="NW"};if(wd>=326.25&&wd<348.75){wd="NNW"}; var wf = feed.item.forecast[0]; // Determine day or night image wpd = feed.item.pubDate; n = wpd.indexOf(":"); tpb = _getTimeAsDate(wpd.substr(n-2,8)); tsr = _getTimeAsDate(feed.astronomy.sunrise); tss = _getTimeAsDate(feed.astronomy.sunset); // Get night or day if (tpb>tsr && tpb<tss) { daynight = 'day'; } else { daynight = 'night'; } // Add item container var html = '<div class="weatherItem '+ row +' '+ daynight +'"'; if (options.image) html += ' style="background-size: 80px;height: 50px;margin-top: -5px;background-image: url(http://l.yimg.com/a/i/us/nws/weather/gr/'+ feed.item.condition.code + daynight.substring(0,1) +'.png); background-repeat: no-repeat;"'; html += '>'; // Add item data //html += '<div class="weatherCity" style="position: absolute;top: -29px;right: 0px;color: #0b6098;font-weight: bold;">'+ feed.location.city +'</div>'; html += '<div class="weatherTemp" style="font-size: 22px;position: absolute;right: 0;top: -8px;">'+ feed.item.condition.temp +'&deg;</div>'; // Add optional data if (options.highlow) html += '<div class="weatherRange" style="font-size: 18px;position: absolute;right: -10px;top: 18px;">'+ wf.low +'&deg; ~ '+ wf.high +'&deg;</div>'; // Add item forecast data if (options.forecast) { html += '<div class="weatherForecast">'; var wfi = feed.item.forecast; for (var i=0; i<wfi.length; i++) { html += '<div class="weatherForecastItem" style="background-image: url(http://l.yimg.com/a/i/us/nws/weather/gr/'+ wfi[i].code +'s.png); background-repeat: no-repeat;">'; html += '<div class="weatherForecastDay">'+ wfi[i].day +'</div>'; html += '<div class="weatherForecastDate">'+ wfi[i].date +'</div>'; html += '<div class="weatherForecastText">'+ wfi[i].text +'</div>'; html += '<div class="weatherForecastRange">High: '+ wfi[i].high +' Low: '+ wfi[i].low +'</div>'; html += '</div>' } html += '</div>' } //if (options.link) html += '<div class="weatherLink"><a href="'+ feed.link +'" target="'+ options.linktarget +'" title="Read full forecast">Full forecast</a></div>'; } else { var html = '<div class="weatherItem '+ row +'">'; html += '<div class="weatherError">City not found</div>'; } html += '</div>'; // Alternate row classes if (row == 'odd') { row = 'even'; } else { row = 'odd'; } $e.append(html); }; // Get time string as date var _getTimeAsDate = function(t) { d = new Date(); r = new Date(d.toDateString() +' '+ t); return r; }; }); }; })(jQuery);
JavaScript
/** * BxSlider v4.1 - Fully loaded, responsive content slider * http://bxslider.com * * Copyright 2012, Steven Wanderski - http://stevenwanderski.com - http://bxcreative.com * Written while drinking Belgian ales and listening to jazz * * Released under the WTFPL license - http://sam.zoy.org/wtfpl/ */ ;(function($){ var plugin = {}; var defaults = { // GENERAL mode: 'horizontal', slideSelector: '', infiniteLoop: true, hideControlOnEnd: false, speed: 900, easing: null, slideMargin: 0, startSlide: 0, randomStart: false, captions: false, ticker: false, tickerHover: false, adaptiveHeight: false, adaptiveHeightSpeed: 500, video: false, useCSS: true, preloadImages: 'visible', // TOUCH touchEnabled: true, swipeThreshold: 50, oneToOneTouch: false, preventDefaultSwipeX: true, preventDefaultSwipeY: false, // PAGER pager: true, pagerType: 'full', pagerShortSeparator: ' / ', pagerSelector: null, buildPager: null, pagerCustom: null, // CONTROLS controls: true, nextText: 'Next', prevText: 'Prev', nextSelector: null, prevSelector: null, autoControls: false, startText: 'Start', stopText: 'Stop', autoControlsCombine: false, autoControlsSelector: null, // AUTO auto: false, pause: 3000, autoStart: true, autoDirection: 'next', autoHover: true, autoDelay: 0, // CAROUSEL minSlides: 1, maxSlides: 1, moveSlides: 0, slideWidth: 0, // CALLBACKS onSliderLoad: function() {}, onSlideBefore: function() {}, onSlideAfter: function() {}, onSlideNext: function() {}, onSlidePrev: function() {} } $.fn.bxSlider = function(options){ if(this.length == 0) return this; // support mutltiple elements if(this.length > 1){ this.each(function(){$(this).bxSlider(options)}); return this; } // create a namespace to be used throughout the plugin var slider = {}; // set a reference to our slider element var el = this; plugin.el = this; /** * Makes slideshow responsive */ // first get the original window dimens (thanks alot IE) var windowWidth = $(window).width(); var windowHeight = $(window).height(); /** * =================================================================================== * = PRIVATE FUNCTIONS * =================================================================================== */ /** * Initializes namespace settings to be used throughout plugin */ var init = function(){ // merge user-supplied options with the defaults slider.settings = $.extend({}, defaults, options); // parse slideWidth setting slider.settings.slideWidth = parseInt(slider.settings.slideWidth); // store the original children slider.children = el.children(slider.settings.slideSelector); // check if actual number of slides is less than minSlides / maxSlides if(slider.children.length < slider.settings.minSlides) slider.settings.minSlides = slider.children.length; if(slider.children.length < slider.settings.maxSlides) slider.settings.maxSlides = slider.children.length; // if random start, set the startSlide setting to random number if(slider.settings.randomStart) slider.settings.startSlide = Math.floor(Math.random() * slider.children.length); // store active slide information slider.active = { index: slider.settings.startSlide } // store if the slider is in carousel mode (displaying / moving multiple slides) slider.carousel = slider.settings.minSlides > 1 || slider.settings.maxSlides > 1; // if carousel, force preloadImages = 'all' if(slider.carousel) slider.settings.preloadImages = 'all'; // calculate the min / max width thresholds based on min / max number of slides // used to setup and update carousel slides dimensions slider.minThreshold = (slider.settings.minSlides * slider.settings.slideWidth) + ((slider.settings.minSlides - 1) * slider.settings.slideMargin); slider.maxThreshold = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin); // store the current state of the slider (if currently animating, working is true) slider.working = false; // initialize the controls object slider.controls = {}; // initialize an auto interval slider.interval = null; // determine which property to use for transitions slider.animProp = slider.settings.mode == 'vertical' ? 'top' : 'left'; // determine if hardware acceleration can be used slider.usingCSS = slider.settings.useCSS && slider.settings.mode != 'fade' && (function(){ // create our test div element var div = document.createElement('div'); // css transition properties var props = ['WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective']; // test for each property for(var i in props){ if(div.style[props[i]] !== undefined){ slider.cssPrefix = props[i].replace('Perspective', '').toLowerCase(); slider.animProp = '-' + slider.cssPrefix + '-transform'; return true; } } return false; }()); // if vertical mode always make maxSlides and minSlides equal if(slider.settings.mode == 'vertical') slider.settings.maxSlides = slider.settings.minSlides; // perform all DOM / CSS modifications setup(); } /** * Performs all DOM and CSS modifications */ var setup = function(){ // wrap el in a wrapper el.wrap('<div class="bx-wrapper"><div class="bx-viewport"></div></div>'); // store a namspace reference to .bx-viewport slider.viewport = el.parent(); // add a loading div to display while images are loading slider.loader = $('<div class="bx-loading" />'); slider.viewport.prepend(slider.loader); // set el to a massive width, to hold any needed slides // also strip any margin and padding from el el.css({ width: slider.settings.mode == 'horizontal' ? slider.children.length * 215 + '%' : 'auto', position: 'relative' }); // if using CSS, add the easing property if(slider.usingCSS && slider.settings.easing){ el.css('-' + slider.cssPrefix + '-transition-timing-function', slider.settings.easing); // if not using CSS and no easing value was supplied, use the default JS animation easing (swing) }else if(!slider.settings.easing){ slider.settings.easing = 'swing'; } var slidesShowing = getNumberSlidesShowing(); // make modifications to the viewport (.bx-viewport) slider.viewport.css({ width: '100%', overflow: 'hidden', position: 'relative' }); slider.viewport.parent().css({ maxWidth: getViewportMaxWidth() }); // apply css to all slider children slider.children.css({ 'float': slider.settings.mode == 'horizontal' ? 'left' : 'none', listStyle: 'none', position: 'relative' }); // apply the calculated width after the float is applied to prevent scrollbar interference slider.children.width(getSlideWidth()); // if slideMargin is supplied, add the css if(slider.settings.mode == 'horizontal' && slider.settings.slideMargin > 0) slider.children.css('marginRight', slider.settings.slideMargin); if(slider.settings.mode == 'vertical' && slider.settings.slideMargin > 0) slider.children.css('marginBottom', slider.settings.slideMargin); // if "fade" mode, add positioning and z-index CSS if(slider.settings.mode == 'fade'){ slider.children.css({ position: 'absolute', zIndex: 0, display: 'none' }); // prepare the z-index on the showing element slider.children.eq(slider.settings.startSlide).css({zIndex: 50, display: 'block'}); } // create an element to contain all slider controls (pager, start / stop, etc) slider.controls.el = $('<div class="bx-controls" />'); // if captions are requested, add them if(slider.settings.captions) appendCaptions(); // if infinite loop, prepare additional slides if(slider.settings.infiniteLoop && slider.settings.mode != 'fade' && !slider.settings.ticker){ var slice = slider.settings.mode == 'vertical' ? slider.settings.minSlides : slider.settings.maxSlides; var sliceAppend = slider.children.slice(0, slice).clone().addClass('bx-clone'); var slicePrepend = slider.children.slice(-slice).clone().addClass('bx-clone'); el.append(sliceAppend).prepend(slicePrepend); } // check if startSlide is last slide slider.active.last = slider.settings.startSlide == getPagerQty() - 1; // if video is true, set up the fitVids plugin if(slider.settings.video) el.fitVids(); // set the default preload selector (visible) var preloadSelector = slider.children.eq(slider.settings.startSlide); if (slider.settings.preloadImages == "all") preloadSelector = el.children(); // only check for control addition if not in "ticker" mode if(!slider.settings.ticker){ // if pager is requested, add it if(slider.settings.pager) appendPager(); // if controls are requested, add them if(slider.settings.controls) appendControls(); // if auto is true, and auto controls are requested, add them if(slider.settings.auto && slider.settings.autoControls) appendControlsAuto(); // if any control option is requested, add the controls wrapper if(slider.settings.controls || slider.settings.autoControls || slider.settings.pager) slider.viewport.after(slider.controls.el); // if ticker mode, do not allow a pager }else{ slider.settings.pager = false; } // preload all images, then perform final DOM / CSS modifications that depend on images being loaded preloadSelector.imagesLoaded(start); } /** * Start the slider */ var start = function(){ // remove the loading DOM element slider.loader.remove(); // set the left / top position of "el" setSlidePosition(); // if "vertical" mode, always use adaptiveHeight to prevent odd behavior if (slider.settings.mode == 'vertical') slider.settings.adaptiveHeight = true; // set the viewport height slider.viewport.height(getViewportHeight()); // make sure everything is positioned just right (same as a window resize) el.redrawSlider(); // onSliderLoad callback slider.settings.onSliderLoad(slider.active.index); // slider has been fully initialized slider.initialized = true; // bind the resize call to the window $(window).bind('resize', resizeWindow); // if auto is true, start the show if (slider.settings.auto && slider.settings.autoStart) initAuto(); // if ticker is true, start the ticker if (slider.settings.ticker) initTicker(); // if pager is requested, make the appropriate pager link active if (slider.settings.pager) updatePagerActive(slider.settings.startSlide); // check for any updates to the controls (like hideControlOnEnd updates) if (slider.settings.controls) updateDirectionControls(); // if touchEnabled is true, setup the touch events if (slider.settings.touchEnabled && !slider.settings.ticker) initTouch(); } /** * Returns the calculated height of the viewport, used to determine either adaptiveHeight or the maxHeight value */ var getViewportHeight = function(){ var height = 0; // first determine which children (slides) should be used in our height calculation var children = $(); // if mode is not "vertical" and adaptiveHeight is false, include all children if(slider.settings.mode != 'vertical' && !slider.settings.adaptiveHeight){ children = slider.children; }else{ // if not carousel, return the single active child if(!slider.carousel){ children = slider.children.eq(slider.active.index); // if carousel, return a slice of children }else{ // get the individual slide index var currentIndex = slider.settings.moveSlides == 1 ? slider.active.index : slider.active.index * getMoveBy(); // add the current slide to the children children = slider.children.eq(currentIndex); // cycle through the remaining "showing" slides for (i = 1; i <= slider.settings.maxSlides - 1; i++){ // if looped back to the start if(currentIndex + i >= slider.children.length){ children = children.add(slider.children.eq(i - 1)); }else{ children = children.add(slider.children.eq(currentIndex + i)); } } } } // if "vertical" mode, calculate the sum of the heights of the children if(slider.settings.mode == 'vertical'){ children.each(function(index) { height += $(this).outerHeight(); }); // add user-supplied margins if(slider.settings.slideMargin > 0){ height += slider.settings.slideMargin * (slider.settings.minSlides - 1); } // if not "vertical" mode, calculate the max height of the children }else{ height = Math.max.apply(Math, children.map(function(){ return $(this).outerHeight(false); }).get()); } return height; } /** * Returns the calculated width to be used for the outer wrapper / viewport */ var getViewportMaxWidth = function(){ var width = '100%'; if(slider.settings.slideWidth > 0){ if(slider.settings.mode == 'horizontal'){ width = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin); }else{ width = slider.settings.slideWidth; } } return width; } /** * Returns the calculated width to be applied to each slide */ var getSlideWidth = function(){ // start with any user-supplied slide width var newElWidth = slider.settings.slideWidth; // get the current viewport width var wrapWidth = slider.viewport.width(); // if slide width was not supplied, or is larger than the viewport use the viewport width if(slider.settings.slideWidth == 0 || (slider.settings.slideWidth > wrapWidth && !slider.carousel) || slider.settings.mode == 'vertical'){ newElWidth = wrapWidth; // if carousel, use the thresholds to determine the width }else if(slider.settings.maxSlides > 1 && slider.settings.mode == 'horizontal'){ if(wrapWidth > slider.maxThreshold){ // newElWidth = (wrapWidth - (slider.settings.slideMargin * (slider.settings.maxSlides - 1))) / slider.settings.maxSlides; }else if(wrapWidth < slider.minThreshold){ newElWidth = (wrapWidth - (slider.settings.slideMargin * (slider.settings.minSlides - 1))) / slider.settings.minSlides; } } return newElWidth; } /** * Returns the number of slides currently visible in the viewport (includes partially visible slides) */ var getNumberSlidesShowing = function(){ var slidesShowing = 1; if(slider.settings.mode == 'horizontal' && slider.settings.slideWidth > 0){ // if viewport is smaller than minThreshold, return minSlides if(slider.viewport.width() < slider.minThreshold){ slidesShowing = slider.settings.minSlides; // if viewport is larger than minThreshold, return maxSlides }else if(slider.viewport.width() > slider.maxThreshold){ slidesShowing = slider.settings.maxSlides; // if viewport is between min / max thresholds, divide viewport width by first child width }else{ var childWidth = slider.children.first().width(); slidesShowing = Math.floor(slider.viewport.width() / childWidth); } // if "vertical" mode, slides showing will always be minSlides }else if(slider.settings.mode == 'vertical'){ slidesShowing = slider.settings.minSlides; } return slidesShowing; } /** * Returns the number of pages (one full viewport of slides is one "page") */ var getPagerQty = function(){ var pagerQty = 0; // if moveSlides is specified by the user if(slider.settings.moveSlides > 0){ if(slider.settings.infiniteLoop){ pagerQty = slider.children.length / getMoveBy(); }else{ // use a while loop to determine pages var breakPoint = 0; var counter = 0 // when breakpoint goes above children length, counter is the number of pages while (breakPoint < slider.children.length){ ++pagerQty; breakPoint = counter + getNumberSlidesShowing(); counter += slider.settings.moveSlides <= getNumberSlidesShowing() ? slider.settings.moveSlides : getNumberSlidesShowing(); } } // if moveSlides is 0 (auto) divide children length by sides showing, then round up }else{ pagerQty = Math.ceil(slider.children.length / getNumberSlidesShowing()); } return pagerQty; } /** * Returns the number of indivual slides by which to shift the slider */ var getMoveBy = function(){ // if moveSlides was set by the user and moveSlides is less than number of slides showing if(slider.settings.moveSlides > 0 && slider.settings.moveSlides <= getNumberSlidesShowing()){ return slider.settings.moveSlides; } // if moveSlides is 0 (auto) return getNumberSlidesShowing(); } /** * Sets the slider's (el) left or top position */ var setSlidePosition = function(){ // if last slide, not infinite loop, and number of children is larger than specified maxSlides if(slider.children.length > slider.settings.maxSlides && slider.active.last && !slider.settings.infiniteLoop){ if (slider.settings.mode == 'horizontal'){ // get the last child's position var lastChild = slider.children.last(); var position = lastChild.position(); // set the left position setPositionProperty(-(position.left - (slider.viewport.width() - lastChild.width())), 'reset', 0); }else if(slider.settings.mode == 'vertical'){ // get the last showing index's position var lastShowingIndex = slider.children.length - slider.settings.minSlides; var position = slider.children.eq(lastShowingIndex).position(); // set the top position setPositionProperty(-position.top, 'reset', 0); } // if not last slide }else{ // get the position of the first showing slide var position = slider.children.eq(slider.active.index * getMoveBy()).position(); // check for last slide if (slider.active.index == getPagerQty() - 1) slider.active.last = true; // set the repective position if (position != undefined){ if (slider.settings.mode == 'horizontal') setPositionProperty(-position.left, 'reset', 0); else if (slider.settings.mode == 'vertical') setPositionProperty(-position.top, 'reset', 0); } } } /** * Sets the el's animating property position (which in turn will sometimes animate el). * If using CSS, sets the transform property. If not using CSS, sets the top / left property. * * @param value (int) * - the animating property's value * * @param type (string) 'slider', 'reset', 'ticker' * - the type of instance for which the function is being * * @param duration (int) * - the amount of time (in ms) the transition should occupy * * @param params (array) optional * - an optional parameter containing any variables that need to be passed in */ var setPositionProperty = function(value, type, duration, params){ // use CSS transform if(slider.usingCSS){ // determine the translate3d value var propValue = slider.settings.mode == 'vertical' ? 'translate3d(0, ' + value + 'px, 0)' : 'translate3d(' + value + 'px, 0, 0)'; // add the CSS transition-duration el.css('-' + slider.cssPrefix + '-transition-duration', duration / 1000 + 's'); if(type == 'slide'){ // set the property value el.css(slider.animProp, propValue); // bind a callback method - executes when CSS transition completes el.bind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(){ // unbind the callback el.unbind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd'); updateAfterSlideTransition(); }); }else if(type == 'reset'){ el.css(slider.animProp, propValue); }else if(type == 'ticker'){ // make the transition use 'linear' el.css('-' + slider.cssPrefix + '-transition-timing-function', 'linear'); el.css(slider.animProp, propValue); // bind a callback method - executes when CSS transition completes el.bind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(){ // unbind the callback el.unbind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd'); // reset the position setPositionProperty(params['resetValue'], 'reset', 0); // start the loop again tickerLoop(); }); } // use JS animate }else{ var animateObj = {}; animateObj[slider.animProp] = value; if(type == 'slide'){ el.animate(animateObj, duration, slider.settings.easing, function(){ updateAfterSlideTransition(); }); }else if(type == 'reset'){ el.css(slider.animProp, value) }else if(type == 'ticker'){ el.animate(animateObj, speed, 'linear', function(){ setPositionProperty(params['resetValue'], 'reset', 0); // run the recursive loop after animation tickerLoop(); }); } } } /** * Populates the pager with proper amount of pages */ var populatePager = function(){ var pagerHtml = ''; var pagerQty = getPagerQty(); // loop through each pager item for(var i=0; i < pagerQty; i++){ var linkContent = ''; // if a buildPager function is supplied, use it to get pager link value, else use index + 1 if(slider.settings.buildPager && $.isFunction(slider.settings.buildPager)){ linkContent = slider.settings.buildPager(i); slider.pagerEl.addClass('bx-custom-pager'); }else{ linkContent = i + 1; slider.pagerEl.addClass('bx-default-pager'); } // var linkContent = slider.settings.buildPager && $.isFunction(slider.settings.buildPager) ? slider.settings.buildPager(i) : i + 1; // add the markup to the string pagerHtml += '<div class="bx-pager-item"><a href="" data-slide-index="' + i + '" class="bx-pager-link">' + linkContent + '</a></div>'; }; // populate the pager element with pager links slider.pagerEl.html(pagerHtml); } /** * Appends the pager to the controls element */ var appendPager = function(){ if(!slider.settings.pagerCustom){ // create the pager DOM element slider.pagerEl = $('<div class="bx-pager" />'); // if a pager selector was supplied, populate it with the pager if(slider.settings.pagerSelector){ $(slider.settings.pagerSelector).html(slider.pagerEl); // if no pager selector was supplied, add it after the wrapper }else{ slider.controls.el.addClass('bx-has-pager').append(slider.pagerEl); } // populate the pager populatePager(); }else{ slider.pagerEl = $(slider.settings.pagerCustom); } // assign the pager click binding slider.pagerEl.delegate('a', 'click', clickPagerBind); } /** * Appends prev / next controls to the controls element */ var appendControls = function(){ slider.controls.next = $('<a class="bx-next" href="">' + slider.settings.nextText + '</a>'); slider.controls.prev = $('<a class="bx-prev" href="">' + slider.settings.prevText + '</a>'); // bind click actions to the controls slider.controls.next.bind('click', clickNextBind); slider.controls.prev.bind('click', clickPrevBind); // if nextSlector was supplied, populate it if(slider.settings.nextSelector){ $(slider.settings.nextSelector).append(slider.controls.next); } // if prevSlector was supplied, populate it if(slider.settings.prevSelector){ $(slider.settings.prevSelector).append(slider.controls.prev); } // if no custom selectors were supplied if(!slider.settings.nextSelector && !slider.settings.prevSelector){ // add the controls to the DOM slider.controls.directionEl = $('<div class="bx-controls-direction" />'); // add the control elements to the directionEl slider.controls.directionEl.append(slider.controls.prev).append(slider.controls.next); // slider.viewport.append(slider.controls.directionEl); slider.controls.el.addClass('bx-has-controls-direction').append(slider.controls.directionEl); } } /** * Appends start / stop auto controls to the controls element */ var appendControlsAuto = function(){ slider.controls.start = $('<div class="bx-controls-auto-item"><a class="bx-start" href="">' + slider.settings.startText + '</a></div>'); slider.controls.stop = $('<div class="bx-controls-auto-item"><a class="bx-stop" href="">' + slider.settings.stopText + '</a></div>'); // add the controls to the DOM slider.controls.autoEl = $('<div class="bx-controls-auto" />'); // bind click actions to the controls slider.controls.autoEl.delegate('.bx-start', 'click', clickStartBind); slider.controls.autoEl.delegate('.bx-stop', 'click', clickStopBind); // if autoControlsCombine, insert only the "start" control if(slider.settings.autoControlsCombine){ slider.controls.autoEl.append(slider.controls.start); // if autoControlsCombine is false, insert both controls }else{ slider.controls.autoEl.append(slider.controls.start).append(slider.controls.stop); } // if auto controls selector was supplied, populate it with the controls if(slider.settings.autoControlsSelector){ $(slider.settings.autoControlsSelector).html(slider.controls.autoEl); // if auto controls selector was not supplied, add it after the wrapper }else{ slider.controls.el.addClass('bx-has-controls-auto').append(slider.controls.autoEl); } // update the auto controls updateAutoControls(slider.settings.autoStart ? 'stop' : 'start'); } /** * Appends image captions to the DOM */ var appendCaptions = function(){ // cycle through each child slider.children.each(function(index){ // get the image title attribute var title = $(this).find('img:first').attr('title'); // append the caption if (title != undefined) $(this).append('<div class="bx-caption"><span>' + title + '</span></div>'); }); } /** * Click next binding * * @param e (event) * - DOM event object */ var clickNextBind = function(e){ // if auto show is running, stop it if (slider.settings.auto) el.startAuto(); el.goToNextSlide(); e.preventDefault(); } /** * Click prev binding * * @param e (event) * - DOM event object */ var clickPrevBind = function(e){ // if auto show is running, stop it if (slider.settings.auto) el.stopAuto(); el.goToPrevSlide(); e.preventDefault(); } /** * Click start binding * * @param e (event) * - DOM event object */ var clickStartBind = function(e){ el.startAuto(); e.preventDefault(); } /** * Click stop binding * * @param e (event) * - DOM event object */ var clickStopBind = function(e){ el.stopAuto(); e.preventDefault(); } /** * Click pager binding * * @param e (event) * - DOM event object */ var clickPagerBind = function(e){ // if auto show is running, stop it if (slider.settings.auto) el.stopAuto(); var pagerLink = $(e.currentTarget); var pagerIndex = parseInt(pagerLink.attr('data-slide-index')); // if clicked pager link is not active, continue with the goToSlide call if(pagerIndex != slider.active.index) el.goToSlide(pagerIndex); e.preventDefault(); } /** * Updates the pager links with an active class * * @param slideIndex (int) * - index of slide to make active */ var updatePagerActive = function(slideIndex){ // if "short" pager type if(slider.settings.pagerType == 'short'){ slider.pagerEl.html((slideIndex + 1) + slider.settings.pagerShortSeparator + slider.children.length); return; } // remove all pager active classes slider.pagerEl.find('a').removeClass('active'); // apply the active class for all pagers slider.pagerEl.each(function(i, el) { $(el).find('a').eq(slideIndex).addClass('active'); }); } /** * Performs needed actions after a slide transition */ var updateAfterSlideTransition = function(){ // if infinte loop is true if(slider.settings.infiniteLoop){ var position = ''; // first slide if(slider.active.index == 0){ // set the new position position = slider.children.eq(0).position(); // carousel, last slide }else if(slider.active.index == getPagerQty() - 1 && slider.carousel){ position = slider.children.eq((getPagerQty() - 1) * getMoveBy()).position(); // last slide }else if(slider.active.index == slider.children.length - 1){ position = slider.children.eq(slider.children.length - 1).position(); } if (slider.settings.mode == 'horizontal') { setPositionProperty(-position.left, 'reset', 0);; } else if (slider.settings.mode == 'vertical') { setPositionProperty(-position.top, 'reset', 0);; } } // declare that the transition is complete slider.working = false; // onSlideAfter callback slider.settings.onSlideAfter(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); } /** * Updates the auto controls state (either active, or combined switch) * * @param state (string) "start", "stop" * - the new state of the auto show */ var updateAutoControls = function(state){ // if autoControlsCombine is true, replace the current control with the new state if(slider.settings.autoControlsCombine){ slider.controls.autoEl.html(slider.controls[state]); // if autoControlsCombine is false, apply the "active" class to the appropriate control }else{ slider.controls.autoEl.find('a').removeClass('active'); slider.controls.autoEl.find('a:not(.bx-' + state + ')').addClass('active'); } } /** * Updates the direction controls (checks if either should be hidden) */ var updateDirectionControls = function(){ if(getPagerQty() == 1){ slider.controls.prev.addClass('disabled'); slider.controls.next.addClass('disabled'); }else if(!slider.settings.infiniteLoop && slider.settings.hideControlOnEnd){ // if first slide if (slider.active.index == 0){ slider.controls.prev.addClass('disabled'); slider.controls.next.removeClass('disabled'); // if last slide }else if(slider.active.index == getPagerQty() - 1){ slider.controls.next.addClass('disabled'); slider.controls.prev.removeClass('disabled'); // if any slide in the middle }else{ slider.controls.prev.removeClass('disabled'); slider.controls.next.removeClass('disabled'); } } } /** * Initialzes the auto process */ var initAuto = function(){ // if autoDelay was supplied, launch the auto show using a setTimeout() call if(slider.settings.autoDelay > 0){ var timeout = setTimeout(el.startAuto, slider.settings.autoDelay); // if autoDelay was not supplied, start the auto show normally }else{ el.startAuto(); } // if autoHover is requested if(slider.settings.autoHover){ // on el hover el.hover(function(){ // if the auto show is currently playing (has an active interval) if(slider.interval){ // stop the auto show and pass true agument which will prevent control update el.stopAuto(true); // create a new autoPaused value which will be used by the relative "mouseout" event slider.autoPaused = true; } }, function(){ // if the autoPaused value was created be the prior "mouseover" event if(slider.autoPaused){ // start the auto show and pass true agument which will prevent control update el.startAuto(true); // reset the autoPaused value slider.autoPaused = null; } }); } } /** * Initialzes the ticker process */ var initTicker = function(){ var startPosition = 0; // if autoDirection is "next", append a clone of the entire slider if(slider.settings.autoDirection == 'next'){ el.append(slider.children.clone().addClass('bx-clone')); // if autoDirection is "prev", prepend a clone of the entire slider, and set the left position }else{ el.prepend(slider.children.clone().addClass('bx-clone')); var position = slider.children.first().position(); startPosition = slider.settings.mode == 'horizontal' ? -position.left : -position.top; } setPositionProperty(startPosition, 'reset', 0); // do not allow controls in ticker mode slider.settings.pager = false; slider.settings.controls = false; slider.settings.autoControls = false; // if autoHover is requested if(slider.settings.tickerHover && !slider.usingCSS){ // on el hover slider.viewport.hover(function(){ el.stop(); }, function(){ // calculate the total width of children (used to calculate the speed ratio) var totalDimens = 0; slider.children.each(function(index){ totalDimens += slider.settings.mode == 'horizontal' ? $(this).outerWidth(true) : $(this).outerHeight(true); }); // calculate the speed ratio (used to determine the new speed to finish the paused animation) var ratio = slider.settings.speed / totalDimens; // determine which property to use var property = slider.settings.mode == 'horizontal' ? 'left' : 'top'; // calculate the new speed var newSpeed = ratio * (totalDimens - (Math.abs(parseInt(el.css(property))))); tickerLoop(newSpeed); }); } // start the ticker loop tickerLoop(); } /** * Runs a continuous loop, news ticker-style */ var tickerLoop = function(resumeSpeed){ speed = resumeSpeed ? resumeSpeed : slider.settings.speed; var position = {left: 0, top: 0}; var reset = {left: 0, top: 0}; // if "next" animate left position to last child, then reset left to 0 if(slider.settings.autoDirection == 'next'){ position = el.find('.bx-clone').first().position(); // if "prev" animate left position to 0, then reset left to first non-clone child }else{ reset = slider.children.first().position(); } var animateProperty = slider.settings.mode == 'horizontal' ? -position.left : -position.top; var resetValue = slider.settings.mode == 'horizontal' ? -reset.left : -reset.top; var params = {resetValue: resetValue}; setPositionProperty(animateProperty, 'ticker', speed, params); } /** * Initializes touch events */ var initTouch = function(){ // initialize object to contain all touch values slider.touch = { start: {x: 0, y: 0}, end: {x: 0, y: 0} } slider.viewport.bind('touchstart', onTouchStart); } /** * Event handler for "touchstart" * * @param e (event) * - DOM event object */ var onTouchStart = function(e){ if(slider.working){ e.preventDefault(); }else{ // record the original position when touch starts slider.touch.originalPos = el.position(); var orig = e.originalEvent; // record the starting touch x, y coordinates slider.touch.start.x = orig.changedTouches[0].pageX; slider.touch.start.y = orig.changedTouches[0].pageY; // bind a "touchmove" event to the viewport slider.viewport.bind('touchmove', onTouchMove); // bind a "touchend" event to the viewport slider.viewport.bind('touchend', onTouchEnd); } } /** * Event handler for "touchmove" * * @param e (event) * - DOM event object */ var onTouchMove = function(e){ var orig = e.originalEvent; // if scrolling on y axis, do not prevent default var xMovement = Math.abs(orig.changedTouches[0].pageX - slider.touch.start.x); var yMovement = Math.abs(orig.changedTouches[0].pageY - slider.touch.start.y); // x axis swipe if((xMovement * 3) > yMovement && slider.settings.preventDefaultSwipeX){ e.preventDefault(); // y axis swipe }else if((yMovement * 3) > xMovement && slider.settings.preventDefaultSwipeY){ e.preventDefault(); } if(slider.settings.mode != 'fade' && slider.settings.oneToOneTouch){ var value = 0; // if horizontal, drag along x axis if(slider.settings.mode == 'horizontal'){ var change = orig.changedTouches[0].pageX - slider.touch.start.x; value = slider.touch.originalPos.left + change; // if vertical, drag along y axis }else{ var change = orig.changedTouches[0].pageY - slider.touch.start.y; value = slider.touch.originalPos.top + change; } setPositionProperty(value, 'reset', 0); } } /** * Event handler for "touchend" * * @param e (event) * - DOM event object */ var onTouchEnd = function(e){ slider.viewport.unbind('touchmove', onTouchMove); var orig = e.originalEvent; var value = 0; // record end x, y positions slider.touch.end.x = orig.changedTouches[0].pageX; slider.touch.end.y = orig.changedTouches[0].pageY; // if fade mode, check if absolute x distance clears the threshold if(slider.settings.mode == 'fade'){ var distance = Math.abs(slider.touch.start.x - slider.touch.end.x); if(distance >= slider.settings.swipeThreshold){ slider.touch.start.x > slider.touch.end.x ? el.goToNextSlide() : el.goToPrevSlide(); el.stopAuto(); } // not fade mode }else{ var distance = 0; // calculate distance and el's animate property if(slider.settings.mode == 'horizontal'){ distance = slider.touch.end.x - slider.touch.start.x; value = slider.touch.originalPos.left; }else{ distance = slider.touch.end.y - slider.touch.start.y; value = slider.touch.originalPos.top; } // if not infinite loop and first / last slide, do not attempt a slide transition if(!slider.settings.infiniteLoop && ((slider.active.index == 0 && distance > 0) || (slider.active.last && distance < 0))){ setPositionProperty(value, 'reset', 200); }else{ // check if distance clears threshold if(Math.abs(distance) >= slider.settings.swipeThreshold){ distance < 0 ? el.goToNextSlide() : el.goToPrevSlide(); el.stopAuto(); }else{ // el.animate(property, 200); setPositionProperty(value, 'reset', 200); } } } slider.viewport.unbind('touchend', onTouchEnd); } /** * Window resize event callback */ var resizeWindow = function(e){ // get the new window dimens (again, thank you IE) var windowWidthNew = $(window).width(); var windowHeightNew = $(window).height(); // make sure that it is a true window resize // *we must check this because our dinosaur friend IE fires a window resize event when certain DOM elements // are resized. Can you just die already?* if(windowWidth != windowWidthNew || windowHeight != windowHeightNew){ // set the new window dimens windowWidth = windowWidthNew; windowHeight = windowHeightNew; // update all dynamic elements el.redrawSlider(); } } /** * =================================================================================== * = PUBLIC FUNCTIONS * =================================================================================== */ /** * Performs slide transition to the specified slide * * @param slideIndex (int) * - the destination slide's index (zero-based) * * @param direction (string) * - INTERNAL USE ONLY - the direction of travel ("prev" / "next") */ el.goToSlide = function(slideIndex, direction){ // if plugin is currently in motion, ignore request if(slider.working || slider.active.index == slideIndex) return; // declare that plugin is in motion slider.working = true; // store the old index slider.oldIndex = slider.active.index; // if slideIndex is less than zero, set active index to last child (this happens during infinite loop) if(slideIndex < 0){ slider.active.index = getPagerQty() - 1; // if slideIndex is greater than children length, set active index to 0 (this happens during infinite loop) }else if(slideIndex >= getPagerQty()){ slider.active.index = 0; // set active index to requested slide }else{ slider.active.index = slideIndex; } // onSlideBefore, onSlideNext, onSlidePrev callbacks slider.settings.onSlideBefore(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); if(direction == 'next'){ slider.settings.onSlideNext(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); }else if(direction == 'prev'){ slider.settings.onSlidePrev(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); } // check if last slide slider.active.last = slider.active.index >= getPagerQty() - 1; // update the pager with active class if(slider.settings.pager) updatePagerActive(slider.active.index); // // check for direction control update if(slider.settings.controls) updateDirectionControls(); // if slider is set to mode: "fade" if(slider.settings.mode == 'fade'){ // if adaptiveHeight is true and next height is different from current height, animate to the new height if(slider.settings.adaptiveHeight && slider.viewport.height() != getViewportHeight()){ slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed); } // fade out the visible child and reset its z-index value slider.children.filter(':visible').fadeOut(slider.settings.speed).css({zIndex: 0}); // fade in the newly requested slide slider.children.eq(slider.active.index).css('zIndex', 51).fadeIn(slider.settings.speed, function(){ $(this).css('zIndex', 50); updateAfterSlideTransition(); }); // slider mode is not "fade" }else{ // if adaptiveHeight is true and next height is different from current height, animate to the new height if(slider.settings.adaptiveHeight && slider.viewport.height() != getViewportHeight()){ slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed); } var moveBy = 0; var position = {left: 0, top: 0}; // if carousel and not infinite loop if(!slider.settings.infiniteLoop && slider.carousel && slider.active.last){ if(slider.settings.mode == 'horizontal'){ // get the last child position var lastChild = slider.children.eq(slider.children.length - 1); position = lastChild.position(); // calculate the position of the last slide moveBy = slider.viewport.width() - lastChild.width(); }else{ // get last showing index position var lastShowingIndex = slider.children.length - slider.settings.minSlides; position = slider.children.eq(lastShowingIndex).position(); } // horizontal carousel, going previous while on first slide (infiniteLoop mode) }else if(slider.carousel && slider.active.last && direction == 'prev'){ // get the last child position var eq = slider.settings.moveSlides == 1 ? slider.settings.maxSlides - getMoveBy() : ((getPagerQty() - 1) * getMoveBy()) - (slider.children.length - slider.settings.maxSlides); var lastChild = el.children('.bx-clone').eq(eq); position = lastChild.position(); // if infinite loop and "Next" is clicked on the last slide }else if(direction == 'next' && slider.active.index == 0){ // get the last clone position position = el.find('> .bx-clone').eq(slider.settings.maxSlides).position(); slider.active.last = false; // normal non-zero requests }else if(slideIndex >= 0){ var requestEl = slideIndex * getMoveBy(); position = slider.children.eq(requestEl).position(); } /* If the position doesn't exist * (e.g. if you destroy the slider on a next click), * it doesn't throw an error. */ if ("undefined" !== typeof(position)) { var value = slider.settings.mode == 'horizontal' ? -(position.left - moveBy) : -position.top; // plugin values to be animated setPositionProperty(value, 'slide', slider.settings.speed); } } } /** * Transitions to the next slide in the show */ el.goToNextSlide = function(){ // if infiniteLoop is false and last page is showing, disregard call if (!slider.settings.infiniteLoop && slider.active.last) return; var pagerIndex = parseInt(slider.active.index) + 1; el.goToSlide(pagerIndex, 'next'); } /** * Transitions to the prev slide in the show */ el.goToPrevSlide = function(){ // if infiniteLoop is false and last page is showing, disregard call if (!slider.settings.infiniteLoop && slider.active.index == 0) return; var pagerIndex = parseInt(slider.active.index) - 1; el.goToSlide(pagerIndex, 'prev'); } /** * Starts the auto show * * @param preventControlUpdate (boolean) * - if true, auto controls state will not be updated */ el.startAuto = function(preventControlUpdate){ // if an interval already exists, disregard call if(slider.interval) return; // create an interval slider.interval = setInterval(function(){ slider.settings.autoDirection == 'next' ? el.goToNextSlide() : el.goToPrevSlide(); }, slider.settings.pause); // if auto controls are displayed and preventControlUpdate is not true if (slider.settings.autoControls && preventControlUpdate != true) updateAutoControls('stop'); } /** * Stops the auto show * * @param preventControlUpdate (boolean) * - if true, auto controls state will not be updated */ el.stopAuto = function(preventControlUpdate){ // if no interval exists, disregard call if(!slider.interval) return; // clear the interval clearInterval(slider.interval); slider.interval = null; // if auto controls are displayed and preventControlUpdate is not true if (slider.settings.autoControls && preventControlUpdate != true) updateAutoControls('start'); } /** * Returns current slide index (zero-based) */ el.getCurrentSlide = function(){ return slider.active.index; } /** * Returns number of slides in show */ el.getSlideCount = function(){ return slider.children.length; } /** * Update all dynamic slider elements */ el.redrawSlider = function(){ // resize all children in ratio to new screen size slider.children.add(el.find('.bx-clone')).width(getSlideWidth()); // adjust the height slider.viewport.css('height', getViewportHeight()); // update the slide position if(!slider.settings.ticker) setSlidePosition(); // if active.last was true before the screen resize, we want // to keep it last no matter what screen size we end on if (slider.active.last) slider.active.index = getPagerQty() - 1; // if the active index (page) no longer exists due to the resize, simply set the index as last if (slider.active.index >= getPagerQty()) slider.active.last = true; // if a pager is being displayed and a custom pager is not being used, update it if(slider.settings.pager && !slider.settings.pagerCustom){ populatePager(); updatePagerActive(slider.active.index); } } /** * Destroy the current instance of the slider (revert everything back to original state) */ el.destroySlider = function(){ // don't do anything if slider has already been destroyed if(!slider.initialized) return; slider.initialized = false; $('.bx-clone', this).remove(); slider.children.removeAttr('style'); this.removeAttr('style').unwrap().unwrap(); if(slider.controls.el) slider.controls.el.remove(); if(slider.controls.next) slider.controls.next.remove(); if(slider.controls.prev) slider.controls.prev.remove(); if(slider.pagerEl) slider.pagerEl.remove(); $('.bx-caption', this).remove(); if(slider.controls.autoEl) slider.controls.autoEl.remove(); clearInterval(slider.interval); $(window).unbind('resize', resizeWindow); } /** * Reload the slider (revert all DOM changes, and re-initialize) */ el.reloadSlider = function(settings){ if (settings != undefined) options = settings; el.destroySlider(); init(); } init(); // returns the current jQuery object return this; } })(jQuery); /*! * jQuery imagesLoaded plugin v2.1.0 * http://github.com/desandro/imagesloaded * * MIT License. by Paul Irish et al. */ /*jshint curly: true, eqeqeq: true, noempty: true, strict: true, undef: true, browser: true */ /*global jQuery: false */ (function(c,n){var l="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";c.fn.imagesLoaded=function(f){function m(){var b=c(i),a=c(h);d&&(h.length?d.reject(e,b,a):d.resolve(e));c.isFunction(f)&&f.call(g,e,b,a)}function j(b,a){b.src===l||-1!==c.inArray(b,k)||(k.push(b),a?h.push(b):i.push(b),c.data(b,"imagesLoaded",{isBroken:a,src:b.src}),o&&d.notifyWith(c(b),[a,e,c(i),c(h)]),e.length===k.length&&(setTimeout(m),e.unbind(".imagesLoaded")))}var g=this,d=c.isFunction(c.Deferred)?c.Deferred(): 0,o=c.isFunction(d.notify),e=g.find("img").add(g.filter("img")),k=[],i=[],h=[];c.isPlainObject(f)&&c.each(f,function(b,a){if("callback"===b)f=a;else if(d)d[b](a)});e.length?e.bind("load.imagesLoaded error.imagesLoaded",function(b){j(b.target,"error"===b.type)}).each(function(b,a){var d=a.src,e=c.data(a,"imagesLoaded");if(e&&e.src===d)j(a,e.isBroken);else if(a.complete&&a.naturalWidth!==n)j(a,0===a.naturalWidth||0===a.naturalHeight);else if(a.readyState||a.complete)a.src=l,a.src=d}):m();return d?d.promise(g): g}})(jQuery);
JavaScript
/** * jQuery Masonry v2.1.03 * A dynamic layout plugin for jQuery * The flip-side of CSS Floats * http://masonry.desandro.com * * Licensed under the MIT license. * Copyright 2011 David DeSandro */ /*jshint browser: true, curly: true, eqeqeq: true, forin: false, immed: false, newcap: true, noempty: true, strict: true, undef: true */ /*global jQuery: false */ (function( window, $, undefined ){ 'use strict'; /* * smartresize: debounced resize event for jQuery * * latest version and complete README available on Github: * https://github.com/louisremi/jquery.smartresize.js * * Copyright 2011 @louis_remi * Licensed under the MIT license. */ var $event = $.event, resizeTimeout; $event.special.smartresize = { setup: function() { $(this).bind( "resize", $event.special.smartresize.handler ); }, teardown: function() { $(this).unbind( "resize", $event.special.smartresize.handler ); }, handler: function( event, execAsap ) { // Save the context var context = this, args = arguments; // set correct event type event.type = "smartresize"; if ( resizeTimeout ) { clearTimeout( resizeTimeout ); } resizeTimeout = setTimeout(function() { jQuery.event.handle.apply( context, args ); }, execAsap === "execAsap"? 0 : 100 ); } }; $.fn.smartresize = function( fn ) { return fn ? this.bind( "smartresize", fn ) : this.trigger( "smartresize", ["execAsap"] ); }; // ========================= Masonry =============================== // our "Widget" object constructor $.Mason = function( options, element ){ this.element = $( element ); this._create( options ); this._init(); }; $.Mason.settings = { isResizable: true, isAnimated: false, animationOptions: { queue: false, duration: 500 }, gutterWidth: 0, isRTL: false, isFitWidth: false, containerStyle: { position: 'relative' } }; $.Mason.prototype = { _filterFindBricks: function( $elems ) { var selector = this.options.itemSelector; // if there is a selector // filter/find appropriate item elements return !selector ? $elems : $elems.filter( selector ).add( $elems.find( selector ) ); }, _getBricks: function( $elems ) { var $bricks = this._filterFindBricks( $elems ) .css({ position: 'absolute' }) .addClass('masonry-brick'); return $bricks; }, // sets up widget _create : function( options ) { this.options = $.extend( true, {}, $.Mason.settings, options ); this.styleQueue = []; // get original styles in case we re-apply them in .destroy() var elemStyle = this.element[0].style; this.originalStyle = { // get height height: elemStyle.height || '' }; // get other styles that will be overwritten var containerStyle = this.options.containerStyle; for ( var prop in containerStyle ) { this.originalStyle[ prop ] = elemStyle[ prop ] || ''; } this.element.css( containerStyle ); this.horizontalDirection = this.options.isRTL ? 'right' : 'left'; this.offset = { x: parseInt( this.element.css( 'padding-' + this.horizontalDirection ), 10 ), y: parseInt( this.element.css( 'padding-top' ), 10 ) }; this.isFluid = this.options.columnWidth && typeof this.options.columnWidth === 'function'; // add masonry class first time around var instance = this; setTimeout( function() { instance.element.addClass('masonry'); }, 0 ); // bind resize method if ( this.options.isResizable ) { $(window).bind( 'smartresize.masonry', function() { instance.resize(); }); } // need to get bricks this.reloadItems(); }, // _init fires when instance is first created // and when instance is triggered again -> $el.masonry(); _init : function( callback ) { this._getColumns(); this._reLayout( callback ); }, option: function( key, value ){ // set options AFTER initialization: // signature: $('#foo').bar({ cool:false }); if ( $.isPlainObject( key ) ){ this.options = $.extend(true, this.options, key); } }, // ====================== General Layout ====================== // used on collection of atoms (should be filtered, and sorted before ) // accepts atoms-to-be-laid-out to start with layout : function( $bricks, callback ) { // place each brick for (var i=0, len = $bricks.length; i < len; i++) { this._placeBrick( $bricks[i] ); } // set the size of the container var containerSize = {}; containerSize.height = Math.max.apply( Math, this.colYs ); if ( this.options.isFitWidth ) { var unusedCols = 0; i = this.cols; // count unused columns while ( --i ) { if ( this.colYs[i] !== 0 ) { break; } unusedCols++; } // fit container to columns that have been used; containerSize.width = (this.cols - unusedCols) * this.columnWidth - this.options.gutterWidth; } this.styleQueue.push({ $el: this.element, style: containerSize }); // are we animating the layout arrangement? // use plugin-ish syntax for css or animate var styleFn = !this.isLaidOut ? 'css' : ( this.options.isAnimated ? 'animate' : 'css' ), animOpts = this.options.animationOptions; // process styleQueue var obj; for (i=0, len = this.styleQueue.length; i < len; i++) { obj = this.styleQueue[i]; obj.$el[ styleFn ]( obj.style, animOpts ); } // clear out queue for next time this.styleQueue = []; // provide $elems as context for the callback if ( callback ) { callback.call( $bricks ); } this.isLaidOut = true; }, // calculates number of columns // i.e. this.columnWidth = 200 _getColumns : function() { var container = this.options.isFitWidth ? this.element.parent() : this.element, containerWidth = container.width(); // use fluid columnWidth function if there this.columnWidth = this.isFluid ? this.options.columnWidth( containerWidth ) : // if not, how about the explicitly set option? this.options.columnWidth || // or use the size of the first item this.$bricks.outerWidth(true) || // if there's no items, use size of container containerWidth; this.columnWidth += this.options.gutterWidth; this.cols = Math.floor( ( containerWidth + this.options.gutterWidth ) / this.columnWidth ); this.cols = Math.max( this.cols, 1 ); }, // layout logic _placeBrick: function( brick ) { var $brick = $(brick), colSpan, groupCount, groupY, groupColY, j; //how many columns does this brick span colSpan = Math.ceil( $brick.outerWidth(true) / ( this.columnWidth + this.options.gutterWidth ) ); colSpan = Math.min( colSpan, this.cols ); if ( colSpan === 1 ) { // if brick spans only one column, just like singleMode groupY = this.colYs; } else { // brick spans more than one column // how many different places could this brick fit horizontally groupCount = this.cols + 1 - colSpan; groupY = []; // for each group potential horizontal position for ( j=0; j < groupCount; j++ ) { // make an array of colY values for that one group groupColY = this.colYs.slice( j, j+colSpan ); // and get the max value of the array groupY[j] = Math.max.apply( Math, groupColY ); } } // get the minimum Y value from the columns var minimumY = Math.min.apply( Math, groupY ), shortCol = 0; // Find index of short column, the first from the left for (var i=0, len = groupY.length; i < len; i++) { if ( groupY[i] === minimumY ) { shortCol = i; break; } } // position the brick var position = { top: minimumY + this.offset.y }; // position.left or position.right position[ this.horizontalDirection ] = this.columnWidth * shortCol + this.offset.x; this.styleQueue.push({ $el: $brick, style: position }); // apply setHeight to necessary columns var setHeight = minimumY + $brick.outerHeight(true), setSpan = this.cols + 1 - len; for ( i=0; i < setSpan; i++ ) { this.colYs[ shortCol + i ] = setHeight; } }, resize: function() { var prevColCount = this.cols; // get updated colCount this._getColumns(); if ( this.isFluid || this.cols !== prevColCount ) { // if column count has changed, trigger new layout this._reLayout(); } }, _reLayout : function( callback ) { // reset columns var i = this.cols; this.colYs = []; while (i--) { this.colYs.push( 0 ); } // apply layout logic to all bricks this.layout( this.$bricks, callback ); }, // ====================== Convenience methods ====================== // goes through all children again and gets bricks in proper order reloadItems : function() { this.$bricks = this._getBricks( this.element.children() ); }, reload : function( callback ) { this.reloadItems(); this._init( callback ); }, // convienence method for working with Infinite Scroll appended : function( $content, isAnimatedFromBottom, callback ) { if ( isAnimatedFromBottom ) { // set new stuff to the bottom this._filterFindBricks( $content ).css({ top: this.element.height() }); var instance = this; setTimeout( function(){ instance._appended( $content, callback ); }, 1 ); } else { this._appended( $content, callback ); } }, _appended : function( $content, callback ) { var $newBricks = this._getBricks( $content ); // add new bricks to brick pool this.$bricks = this.$bricks.add( $newBricks ); this.layout( $newBricks, callback ); }, // removes elements from Masonry widget remove : function( $content ) { this.$bricks = this.$bricks.not( $content ); $content.remove(); }, // destroys widget, returns elements and container back (close) to original style destroy : function() { this.$bricks .removeClass('masonry-brick') .each(function(){ this.style.position = ''; this.style.top = ''; this.style.left = ''; }); // re-apply saved container styles var elemStyle = this.element[0].style; for ( var prop in this.originalStyle ) { elemStyle[ prop ] = this.originalStyle[ prop ]; } this.element .unbind('.masonry') .removeClass('masonry') .removeData('masonry'); $(window).unbind('.masonry'); } }; // ======================= imagesLoaded Plugin =============================== /*! * jQuery imagesLoaded plugin v1.1.0 * http://github.com/desandro/imagesloaded * * MIT License. by Paul Irish et al. */ // $('#my-container').imagesLoaded(myFunction) // or // $('img').imagesLoaded(myFunction) // execute a callback when all images have loaded. // needed because .load() doesn't work on cached images // callback function gets image collection as argument // `this` is the container $.fn.imagesLoaded = function( callback ) { var $this = this, $images = $this.find('img').add( $this.filter('img') ), len = $images.length, blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==', loaded = []; function triggerCallback() { callback.call( $this, $images ); } function imgLoaded( event ) { var img = event.target; if ( img.src !== blank && $.inArray( img, loaded ) === -1 ){ loaded.push( img ); if ( --len <= 0 ){ setTimeout( triggerCallback ); $images.unbind( '.imagesLoaded', imgLoaded ); } } } // if no images, trigger immediately if ( !len ) { triggerCallback(); } $images.bind( 'load.imagesLoaded error.imagesLoaded', imgLoaded ).each( function() { // cached images don't fire load sometimes, so we reset src. var src = this.src; // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f // data uri bypasses webkit log warning (thx doug jones) this.src = blank; this.src = src; }); return $this; }; // helper function for logging errors // $.error breaks jQuery chaining var logError = function( message ) { if ( window.console ) { window.console.error( message ); } }; // ======================= Plugin bridge =============================== // leverages data method to either create or return $.Mason constructor // A bit from jQuery UI // https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js // A bit from jcarousel // https://github.com/jsor/jcarousel/blob/master/lib/jquery.jcarousel.js $.fn.masonry = function( options ) { if ( typeof options === 'string' ) { // call method var args = Array.prototype.slice.call( arguments, 1 ); this.each(function(){ var instance = $.data( this, 'masonry' ); if ( !instance ) { logError( "cannot call methods on masonry prior to initialization; " + "attempted to call method '" + options + "'" ); return; } if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) { logError( "no such method '" + options + "' for masonry instance" ); return; } // apply method instance[ options ].apply( instance, args ); }); } else { this.each(function() { var instance = $.data( this, 'masonry' ); if ( instance ) { // apply options & init instance.option( options || {} ); instance._init(); } else { // initialize new instance $.data( this, 'masonry', new $.Mason( options, this ) ); } }); } return this; }; })( window, jQuery );
JavaScript
/*! * Davis - http://davisjs.com - JavaScript Routing - 0.9.9 * Copyright (C) 2011 Oliver Nightingale * MIT Licensed */ ; /** * Convinience method for instantiating a new Davis app and configuring it to use the passed * routes and subscriptions. * * @param {Function} config A function that will be run with a newly created Davis.App as its context, * should be used to set up app routes, subscriptions and settings etc. * @namespace * @returns {Davis.App} */ Davis = function (config) { var app = new Davis.App config && config.call(app) Davis.$(function () { app.start() }) return app }; /** * Stores the DOM library that Davis will use. Can be overriden to use libraries other than jQuery. */ if (window.jQuery) { Davis.$ = jQuery } else { Davis.$ = null }; /** * Checks whether Davis is supported in the current browser * * @returns {Boolean} */ Davis.supported = function () { return (typeof window.history.pushState == 'function') } /*! * A function that does nothing, used as a default param for any callbacks. * * @private * @returns {Function} */ Davis.noop = function () {} /** * Method to extend the Davis library with an extension. * * An extension is just a function that will modify the Davis framework in some way, * for example changing how the routing works or adjusting where Davis thinks it is supported. * * Example: * Davis.extend(Davis.hashBasedRouting) * * @param {Function} extension the function that will extend Davis * */ Davis.extend = function (extension) { extension(Davis) } /*! * the version */ Davis.version = "0.9.9";/*! * Davis - utils * Copyright (C) 2011 Oliver Nightingale * MIT Licensed */ /*! * A module that provides wrappers around modern JavaScript so that native implementations are used * whereever possible and JavaScript implementations are used in those browsers that do not natively * support them. */ Davis.utils = (function () { /*! * A wrapper around native Array.prototype.every. * * Falls back to a pure JavaScript implementation in browsers that do not support Array.prototype.every. * For more details see the full docs on MDC https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every * * @private * @param {array} the array to loop through * @param {fn} the function to that performs the every check * @param {thisp} an optional param that will be set as fn's this value * @returns {Array} */ if (Array.prototype.every) { var every = function (array, fn) { return array.every(fn, arguments[2]) } } else { var every = function (array, fn) { if (array === void 0 || array === null) throw new TypeError(); var t = Object(array); var len = t.length >>> 0; if (typeof fn !== "function") throw new TypeError(); var thisp = arguments[2]; for (var i = 0; i < len; i++) { if (i in t && !fn.call(thisp, t[i], i, t)) return false; } return true; } }; /*! * A wrapper around native Array.prototype.forEach. * * Falls back to a pure JavaScript implementation in browsers that do not support Array.prototype.forEach. * For more details see the full docs on MDC https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach * * @private * @param {array} the array to loop through * @param {fn} the function to apply to every element of the array * @param {thisp} an optional param that will be set as fn's this value * @returns {Array} */ if (Array.prototype.forEach) { var forEach = function (array, fn) { return array.forEach(fn, arguments[2]) } } else { var forEach = function (array, fn) { if (array === void 0 || array === null) throw new TypeError(); var t = Object(array); var len = t.length >>> 0; if (typeof fn !== "function") throw new TypeError(); var thisp = arguments[2]; for (var i = 0; i < len; i++) { if (i in t) fn.call(thisp, t[i], i, t); } }; }; /*! * A wrapper around native Array.prototype.filter. * Falls back to a pure JavaScript implementation in browsers that do not support Array.prototype.filter. * For more details see the full docs on MDC https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter * * @private * @param {array} the array to filter * @param {fn} the function to do the filtering * @param {thisp} an optional param that will be set as fn's this value * @returns {Array} */ if (Array.prototype.filter) { var filter = function (array, fn) { return array.filter(fn, arguments[2]) } } else { var filter = function(array, fn) { if (array === void 0 || array === null) throw new TypeError(); var t = Object(array); var len = t.length >>> 0; if (typeof fn !== "function") throw new TypeError(); var res = []; var thisp = arguments[2]; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // in case fn mutates this if (fn.call(thisp, val, i, t)) res.push(val); } } return res; }; }; /*! * A wrapper around native Array.prototype.map. * Falls back to a pure JavaScript implementation in browsers that do not support Array.prototype.map. * For more details see the full docs on MDC https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map * * @private * @param {array} the array to map * @param {fn} the function to do the mapping * @param {thisp} an optional param that will be set as fn's this value * @returns {Array} */ if (Array.prototype.map) { var map = function (array, fn) { return array.map(fn, arguments[2]) } } else { var map = function(array, fn) { if (array === void 0 || array === null) throw new TypeError(); var t = Object(array); var len = t.length >>> 0; if (typeof fn !== "function") throw new TypeError(); var res = new Array(len); var thisp = arguments[2]; for (var i = 0; i < len; i++) { if (i in t) res[i] = fn.call(thisp, t[i], i, t); } return res; }; }; /*! * A convinience function for converting arguments to a proper array * * @private * @param {args} a functions arguments * @param {start} an integer at which to start converting the arguments to an array * @returns {Array} */ var toArray = function (args, start) { return Array.prototype.slice.call(args, start || 0) } /*! * Exposing the public interface to the Utils module * @private */ return { every: every, forEach: forEach, filter: filter, toArray: toArray, map: map } })() /*! * Davis - listener * Copyright (C) 2011 Oliver Nightingale * MIT Licensed */ /** * A module to bind to link clicks and form submits and turn what would normally be http requests * into instances of Davis.Request. These request objects are then pushed onto the history stack * using the Davis.history module. * * This module uses Davis.$, which by defualt is jQuery for its event binding and event object normalization. * To use Davis with any, or no, JavaScript framework be sure to provide support for all the methods called * on Davis.$. * * @module */ Davis.listener = function () { /*! * Methods to check whether an element has an href or action that is local to this page * @private */ var originChecks = { A: function (elem) { return elem.host !== window.location.host || elem.protocol !== window.location.protocol }, FORM: function (elem) { var a = document.createElement('a') a.href = elem.action return this.A(a) } } /*! * Checks whether the target of a click or submit event has an href or action that is local to the * current page. Only links or targets with local hrefs or actions will be handled by davis, all * others will be ignored. * @private */ var differentOrigin = function (elem) { if (!originChecks[elem.nodeName.toUpperCase()]) return true // the elem is neither a link or a form return originChecks[elem.nodeName.toUpperCase()](elem) } var hasModifier = function (event) { return (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) } /*! * A handler that creates a new Davis.Request and pushes it onto the history stack using Davis.history. * * @param {Function} targetExtractor a function that will be called with the event target jQuery object and should return an object with path, title and method. * @private */ var handler = function (targetExtractor) { return function (event) { if (hasModifier(event)) return true if (differentOrigin(this)) return true var request = new Davis.Request (targetExtractor.call(Davis.$(this))); Davis.location.assign(request) event.stopPropagation() event.preventDefault() return false; }; }; /*! * A handler specialized for click events. Gets the request details from a link elem * @private */ var clickHandler = handler(function () { var self = this return { method: 'get', fullPath: this.prop('href'), title: this.attr('title'), delegateToServer: function () { window.location = self.prop('href') } }; }); /*! * A handler specialized for submit events. Gets the request details from a form elem * @private */ var submitHandler = handler(function () { var self = this return { method: this.attr('method'), fullPath: (this.serialize() ? [this.prop('action'), this.serialize()].join("?") : this.prop('action')), title: this.attr('title'), delegateToServer: function () { self.submit() } }; }); /** * Binds to both link clicks and form submits using jQuery's deleagate. * * Will catch all current and future links and forms. Uses the apps settings for the selector to use for links and forms * * @see Davis.App.settings * @memberOf listener */ this.listen = function () { Davis.$(document).delegate(this.settings.formSelector, 'submit', submitHandler) Davis.$(document).delegate(this.settings.linkSelector, 'click', clickHandler) } /** * Unbinds all click and submit handlers that were attatched with listen. * * Will efectivley stop the current app from processing any requests and all links and forms will have their default * behaviour restored. * * @see Davis.App.settings * @memberOf listener */ this.unlisten = function () { Davis.$(document).undelegate(this.settings.linkSelector, 'click', clickHandler) Davis.$(document).undelegate(this.settings.formSelector, 'submit', submitHandler) } } /*! * Davis - event * Copyright (C) 2011 Oliver Nightingale * MIT Licensed */ /** * A plugin that adds basic event capabilities to a Davis app, it is included by default. * * @module */ Davis.event = function () { /*! * callback storage */ var callbacks = {} /** * Binds a callback to a named event. * * The following events are triggered internally by Davis and can be bound to * * * start : Triggered when the application is started * * lookupRoute : Triggered before looking up a route. The request being looked up is passed as an argument * * runRoute : Triggered before running a route. The request and route being run are passed as arguments * * routeNotFound : Triggered if no route for the current request can be found. The current request is passed as an arugment * * requestHalted : Triggered when a before filter halts the current request. The current request is passed as an argument * * unsupported : Triggered when starting a Davis app in a browser that doesn't support html5 pushState * * Example * * app.bind('runRoute', function () { * console.log('about to run a route') * }) * * @param {String} event event name * @param {Function} fn callback * @memberOf event */ this.bind = function (event, fn) { (callbacks[event] = callbacks[event] || []).push(fn); return this; }; /** * Triggers an event with the given arguments. * * @param {String} event event name * @param {Mixed} ... * @memberOf event */ this.trigger = function (event) { var args = Davis.utils.toArray(arguments, 1), handlers = callbacks[event]; if (!handlers) return this for (var i = 0, len = handlers.length; i < len; ++i) { handlers[i].apply(this, args) } return this; }; } /*! * Davis - logger * Copyright (C) 2011 Oliver Nightingale * MIT Licensed */ /** * A plugin for enhancing the standard logging available through the console object. * Automatically included in all Davis apps. * * Generates log messages of varying severity in the format * * `[Sun Jan 23 2011 16:15:21 GMT+0000 (GMT)] <message>` * * @module */ Davis.logger = function () { /*! * Generating the timestamp portion of the log message * @private */ function timestamp(){ return "[" + Date() + "]"; } /*! * Pushing the timestamp onto the front of the arguments to log * @private */ function prepArgs(args) { var a = Davis.utils.toArray(args) a.unshift(timestamp()) return a.join(' '); } var logType = function (logLevel) { return function () { if (window.console) console[logLevel](prepArgs(arguments)); } } /** * Prints an error message to the console if the console is available. * * @params {String} All arguments are combined and logged to the console. * @memberOf logger */ var error = logType('error') /** * Prints an info message to the console if the console is available. * * @params {String} All arguments are combined and logged to the console. * @memberOf logger */ var info = logType('info') /** * Prints a warning message to the console if the console is available. * * @params {String} All arguments are combined and logged to the console. * @memberOf logger */ var warn = logType('warn') /*! * Exposes the public methods of the module * @private */ this.logger = { error: error, info: info, warn: warn } }/*! * Davis - Route * Copyright (C) 2011 Oliver Nightingale * MIT Licensed */ Davis.Route = (function () { var pathNameRegex = /:([\w\d]+)/g; var pathNameReplacement = "([^\/]+)"; var splatNameRegex = /\*([\w\d]+)/g; var splatNameReplacement = "(.*)"; var nameRegex = /[:|\*]([\w\d]+)/g /** * Davis.Routes are the main part of a Davis application. They consist of an HTTP method, a path * and a callback function. When a link or a form that Davis has bound to are clicked or submitted * a request is pushed on the history stack and a route that matches the path and method of the * generated request is run. * * The path for the route can consist of placeholders for attributes, these will then be available * on the request. Simple variables should be prefixed with a colan, and for splat style params use * an asterisk. * * Inside the callback function 'this' is bound to the request. * * Example: * * var route = new Davis.Route ('get', '/foo/:id', function (req) { * var id = req.params['id'] * // do something interesting! * }) * * var route = new Davis.Route ('get', '/foo/*splat', function (req) { * var id = req.params['splat'] * // splat will contain everything after the /foo/ in the path. * }) * * You can include any number of route level 'middleware' when defining routes. These middlewares are * run in order and need to explicitly call the next handler in the stack. Using route middleware allows * you to share common logic between routes and is also a good place to load any data or do any async calls * keeping your main handler simple and focused. * * Example: * * var loadUser = function (req, next) { * $.get('/users/current', function (user) { * req.user = user * next(req) * }) * } * * var route = new Davis.Route ('get', '/foo/:id', loadUser, function (req) { * renderUser(req.user) * }) * * @constructor * @param {String} method This should be one of either 'get', 'post', 'put', 'delete', 'before', 'after' or 'state' * @param {String} path This string can contain place holders for variables, e.g. '/user/:id' or '/user/*splat' * @param {Function} callback One or more callbacks that will be called in order when a request matching both the path and method is triggered. */ var Route = function (method, path, handlers) { var convertPathToRegExp = function () { if (!(path instanceof RegExp)) { var str = path .replace(pathNameRegex, pathNameReplacement) .replace(splatNameRegex, splatNameReplacement); // Most browsers will reset this to zero after a replace call. IE will // set it to the index of the last matched character. path.lastIndex = 0; return new RegExp("^" + str + "$", "gi"); } else { return path; }; }; var convertMethodToRegExp = function () { if (!(method instanceof RegExp)) { return new RegExp("^" + method + "$", "i"); } else { return method }; } var capturePathParamNames = function () { var names = [], a; while ((a = nameRegex.exec(path))) names.push(a[1]); return names; }; this.paramNames = capturePathParamNames(); this.path = convertPathToRegExp(); this.method = convertMethodToRegExp(); if (typeof handlers === 'function') { this.handlers = [handlers] } else { this.handlers = handlers; } } /** * Tests whether or not a route matches a particular request. * * Example: * * route.match('get', '/foo/12') * * @param {String} method the method to match against * @param {String} path the path to match against * @returns {Boolean} */ Route.prototype.match = function (method, path) { this.reset(); return (this.method.test(method)) && (this.path.test(path)) } /** * Resets the RegExps for method and path */ Route.prototype.reset = function () { this.method.lastIndex = 0; this.path.lastIndex = 0; } /** * Runs the callback associated with a particular route against the passed request. * * Any named params in the request path are extracted, as per the routes path, and * added onto the requests params object. * * Example: * * route.run(request) * * @params {Davis.Request} request * @returns {Object} whatever the routes callback returns */ Route.prototype.run = function (request) { this.reset(); var matches = this.path.exec(request.path); if (matches) { matches.shift(); for (var i=0; i < matches.length; i++) { request.params[this.paramNames[i]] = matches[i]; }; }; var handlers = Davis.utils.map(this.handlers, function (handler, i) { return function (req) { return handler.call(req, req, handlers[i+1]) } }) return handlers[0](request) } /** * Converts the route to a string representation of itself by combining the method and path * attributes. * * @returns {String} string representation of the route */ Route.prototype.toString = function () { return [this.method, this.path].join(' '); } /*! * exposing the constructor * @private */ return Route; })() /*! * Davis - router * Copyright (C) 2011 Oliver Nightingale * MIT Licensed */ /** * A decorator that adds convinience methods to a Davis.App for easily creating instances * of Davis.Route and looking up routes for a particular request. * * Provides get, post put and delete method shortcuts for creating instances of Davis.Routes * with the corresponding method. This allows simple REST styled routing for a client side * JavaScript application. * * ### Example * * app.get('/foo/:id', function (req) { * // get the foo with id = req.params['id'] * }) * * app.post('/foo', function (req) { * // create a new instance of foo with req.params * }) * * app.put('/foo/:id', function (req) { * // update the instance of foo with id = req.params['id'] * }) * * app.del('/foo/:id', function (req) { * // delete the instance of foo with id = req.params['id'] * }) * * As well as providing convinience methods for creating instances of Davis.Routes the router * also provides methods for creating special instances of routes called filters. Before filters * run before any matching route is run, and after filters run after any matched route has run. * A before filter can return false to halt the running of any matched routes or other before filters. * * A filter can take an optional path to match on, or without a path will match every request. * * ### Example * * app.before('/foo/:id', function (req) { * // will only run before request matching '/foo/:id' * }) * * app.before(function (req) { * // will run before all routes * }) * * app.after('/foo/:id', function (req) { * // will only run after routes matching '/foo/:id' * }) * * app.after(function (req) { * // will run after all routes * }) * * Another special kind of route, called state routes, are also generated using the router. State routes * are for requests that will not change the current page location. Instead the page location will remain * the same but the current state of the page has changed. This allows for states which the server will not * be expected to know about and support. * * ### Example * * app.state('/foo/:id', function (req) { * // will run when the app transitions into the '/foo/:id' state. * }) * * Using the `trans` method an app can transition to these kind of states without changing the url location. * * For convinience routes can be defined within a common base scope, this is useful for keeping your route * definitions simpler and DRYer. A scope can either cover the whole app, or just a subset of the routes. * * ### Example * * app.scope('/foo', function () { * this.get('/:id', function () { * // will run for routes that match '/foo/:id' * }) * }) * * @module */ Davis.router = function () { /** * Low level method for adding routes to your application. * * If called with just a method will return a partially applied function that can create routes with * that method. This is used internally to provide shortcuts for get, post, put, delete and state * routes. * * You normally want to use the higher level methods such as get and post, but this can be useful for extending * Davis to work with other kinds of requests. * * Example: * * app.route('get', '/foo', function (req) { * // will run when a get request is made to '/foo' * }) * * app.patch = app.route('patch') // will return a function that can be used to handle requests with method of patch. * app.patch('/bar', function (req) { * // will run when a patch request is made to '/bar' * }) * * @param {String} method The method for this route. * @param {String} path The path for this route. * @param {Function} handler The handler for this route, will be called with the request that triggered the route. * @returns {Davis.Route} the route that has just been created and added to the route list. * @memberOf router */ this.route = function (method, path) { var createRoute = function (path) { var handlers = Davis.utils.toArray(arguments, 1), scope = scopePaths.join(''), fullPath, route (typeof path == 'string') ? fullPath = scope + path : fullPath = path route = new Davis.Route (method, fullPath, handlers) routeCollection.push(route) return route } return (arguments.length == 1) ? createRoute : createRoute.apply(this, Davis.utils.toArray(arguments, 1)) } /** * A convinience wrapper around `app.route` for creating get routes. * * @param {String} path The path for this route. * @param {Function} handler The handler for this route, will be called with the request that triggered the route. * @returns {Davis.Route} the route that has just been created and added to the route list. * @see Davis.router.route * @memberOf router */ this.get = this.route('get') /** * A convinience wrapper around `app.route` for creating post routes. * * @param {String} path The path for this route. * @param {Function} handler The handler for this route, will be called with the request that triggered the route. * @returns {Davis.Route} the route that has just been created and added to the route list. * @see Davis.router.route * @memberOf router */ this.post = this.route('post') /** * A convinience wrapper around `app.route` for creating put routes. * * @param {String} path The path for this route. * @param {Function} handler The handler for this route, will be called with the request that triggered the route. * @returns {Davis.Route} the route that has just been created and added to the route list. * @see Davis.router.route * @memberOf router */ this.put = this.route('put') /** * A convinience wrapper around `app.route` for creating delete routes. * * delete is a reserved word in javascript so use the `del` method when creating a Davis.Route with a method of delete. * * @param {String} path The path for this route. * @param {Function} handler The handler for this route, will be called with the request that triggered the route. * @returns {Davis.Route} the route that has just been created and added to the route list. * @see Davis.router.route * @memberOf router */ this.del = this.route('delete') /** * Adds a state route into the apps route collection. * * These special kind of routes are not triggered by clicking links or submitting forms, instead they * are triggered manually by calling `trans`. * * Routes added using the state method act in the same way as other routes except that they generate * a route that is listening for requests that will not change the page location. * * Example: * * app.state('/foo/:id', function (req) { * // will run when the app transitions into the '/foo/:id' state. * }) * * @param {String} path The path for this route, this will never be seen in the url bar. * @param {Function} handler The handler for this route, will be called with the request that triggered the route * @memberOf router * */ this.state = this.route('state'); /** * Modifies the scope of the router. * * If you have many routes that share a common path prefix you can use scope to reduce repeating * that path prefix. * * You can use `scope` in two ways, firstly you can set the scope for the whole app by calling scope * before defining routes. You can also provide a function to the scope method, and the scope will * only apply to those routes defined within this function. It is also possible to nest scopes within * other scopes. * * Example * * // using scope with a function * app.scope('/foo', function () { * this.get('/bar', function (req) { * // this route will have a path of '/foo/bar' * }) * }) * * // setting a global scope for the rest of the application * app.scope('/bar') * * // using scope with a function * app.scope('/foo', function () { * this.scope('/bar', function () { * this.get('/baz', function (req) { * // this route will have a path of '/foo/bar/baz' * }) * }) * }) * * @memberOf router * @param {String} path The prefix to use as the scope * @param {Function} fn A function that will be executed with the router as its context and the path * as a prefix * */ this.scope = function (path, fn) { scopePaths.push(path) if (arguments.length == 1) return fn.call(this, this) scopePaths.pop() } /** * Transitions the app into the state identified by the passed path parameter. * * This allows the app to enter states without changing the page path through a link click or form submit. * If there are handlers registered for this state, added by the `state` method, they will be triggered. * * This method generates a request with a method of 'state', in all other ways this request is identical * to those that are generated when clicking links etc. * * States transitioned to using this method will not be able to be revisited directly with a page load as * there is no url that represents the state. * * An optional second parameter can be passed which will be available to any handlers in the requests * params object. * * Example * * app.trans('/foo/1') * * app.trans('/foo/1', { * "bar": "baz" * }) * * * @param {String} path The path that represents this state. This will not be seen in the url bar. * @param {Object} data Any additional data that should be sent with the request as params. * @memberOf router */ this.trans = function (path, data) { if (data) { var fullPath = [path, decodeURIComponent(Davis.$.param(data))].join('?') } else { var fullPath = path }; var req = new Davis.Request({ method: 'state', fullPath: fullPath, title: '' }) Davis.location.assign(req) } /*! * Generating convinience methods for creating filters using Davis.Routes and methods to * lookup filters. */ this.filter = function (filterName) { return function () { var method = /.+/; if (arguments.length == 1) { var path = /.+/; var handler = arguments[0]; } else if (arguments.length == 2) { var path = scopePaths.join('') + arguments[0]; var handler = arguments[1]; }; var route = new Davis.Route (method, path, handler) filterCollection[filterName].push(route); return route } } this.lookupFilter = function (filterType) { return function (method, path) { return Davis.utils.filter(filterCollection[filterType], function (route) { return route.match(method, path) }); } } /** * A convinience wrapper around `app.filter` for creating before filters. * * @param {String} path The optionl path for this filter. * @param {Function} handler The handler for this filter, will be called with the request that triggered the route. * @returns {Davis.Route} the route that has just been created and added to the route list. * @memberOf router */ this.before = this.filter('before') /** * A convinience wrapper around `app.filter` for creating after filters. * * @param {String} path The optionl path for this filter. * @param {Function} handler The handler for this filter, will be called with the request that triggered the route. * @returns {Davis.Route} the route that has just been created and added to the route list. * @memberOf router */ this.after = this.filter('after') /** * A convinience wrapper around `app.lookupFilter` for looking up before filters. * * @param {String} path The optionl path for this filter. * @param {Function} handler The handler for this filter, will be called with the request that triggered the route. * @returns {Davis.Route} the route that has just been created and added to the route list. * @memberOf router */ this.lookupBeforeFilter = this.lookupFilter('before') /** * A convinience wrapper around `app.lookupFilter` for looking up after filters. * * @param {String} path The optionl path for this filter. * @param {Function} handler The handler for this filter, will be called with the request that triggered the route. * @returns {Davis.Route} the route that has just been created and added to the route list. * @memberOf router */ this.lookupAfterFilter = this.lookupFilter('after') /*! * collections of routes and filters * @private */ var routeCollection = []; var filterCollection = { before: [], after: [] }; var scopePaths = [] /** * Looks for the first route that matches the method and path from a request. * Will only find and return the first matched route. * * @param {String} method the method to use when looking up a route * @param {String} path the path to use when looking up a route * @returns {Davis.Route} route * @memberOf router */ this.lookupRoute = function (method, path) { return Davis.utils.filter(routeCollection, function (route) { return route.match(method, path) })[0]; }; } /*! * Davis - history * Copyright (C) 2011 Oliver Nightingale * MIT Licensed */ /** * A module to normalize and enhance the window.pushState method and window.onpopstate event. * * Adds the ability to bind to whenever a new state is pushed onto the history stack and normalizes * both of these events into an onChange event. * * @module */ Davis.history = (function () { /*! * storage for the push state handlers * @private */ var pushStateHandlers = []; /*! * keep track of whether or not webkit like browsers have fired their initial * page load popstate * @private */ var popped = false /*! * Add a handler to the push state event. This event is not a native event but is fired * every time a call to pushState is called. * * @param {Function} handler * @private */ function onPushState(handler) { pushStateHandlers.push(handler); }; /*! * Simple wrapper for the native onpopstate event. * * @param {Function} handler * @private */ function onPopState(handler) { window.addEventListener('popstate', handler, true); }; /*! * returns a handler that wraps the native event given onpopstate. * When the page first loads or going back to a time in the history that was not added * by pushState the event.state object will be null. This generates a request for the current * location in those cases * * @param {Function} handler * @private */ function wrapped(handler) { return function (event) { if (event.state && event.state._davis) { handler(new Davis.Request(event.state._davis)) } else { if (popped) handler(Davis.Request.forPageLoad()) }; popped = true } } /*! * provide a wrapper for any data that is going to be pushed into the history stack. All * data is wrapped in a "_davis" namespace. * @private */ function wrapStateData(data) { return {"_davis": data} } /** * Bind to the history on change event. * * This is not a native event but is fired any time a new state is pushed onto the history stack, * the current history is replaced or a state is popped off the history stack. * The handler function will be called with a request param which is an instance of Davis.Request. * * @param {Function} handler a function that will be called on push and pop state. * @see Davis.Request * @memberOf history */ function onChange(handler) { onPushState(handler); onPopState(wrapped(handler)); }; /*! * returns a function for manipulating the history state and optionally calling any associated * pushStateHandlers * * @param {String} methodName the name of the method to manipulate the history state with. * @private */ function changeStateWith (methodName) { return function (request, opts) { popped = true history[methodName](wrapStateData(request.toJSON()), request.title, request.location()); if (opts && opts.silent) return Davis.utils.forEach(pushStateHandlers, function (handler) { handler(request); }); } } /** * Pushes a request onto the history stack. * * This is used internally by Davis to push a new request * resulting from either a form submit or a link click onto the history stack, it will also trigger * the onpushstate event. * * An instance of Davis.Request is expected to be passed, however any object that has a title * and a path property will also be accepted. * * @param {Davis.Request} request the location to be assinged as the current location. * @memberOf history */ var assign = changeStateWith('pushState') /** * Replace the current state on the history stack. * * This is used internally by Davis when performing a redirect. This will trigger an onpushstate event. * * An instance of Davis.Request is expected to be passed, however any object that has a title * and a path property will also be accepted. * * @param {Davis.Request} request the location to replace the current location with. * @memberOf history */ var replace = changeStateWith('replaceState') /** * Returns the current location for the application. * * Davis.location delegates to this method for getting the apps current location. * * @memberOf history */ function current() { return window.location.pathname + (window.location.search ? window.location.search : '') } /*! * Exposing the public methods of this module * @private */ return { onChange: onChange, current: current, assign: assign, replace: replace } })() /*! * Davis - location * Copyright (C) 2011 Oliver Nightingale * MIT Licensed */ /** * A module that acts as a delegator to any locationDelegate implementation. This abstracts the details of * what is being used for the apps routing away from the rest of the library. This allows any kind of routing * To be used with Davis as long as it can respond appropriatly to the given delegate methods. * * A routing module must respond to the following methods * * * __current__ : Should return the current location for the app * * __assign__ : Should set the current location of the app based on the location of the passed request. * * __replace__ : Should at least change the current location to the location of the passed request, for full compatibility it should not add any extra items in the history stack. * * __onChange__ : Should add calbacks that will be fired whenever the location is changed. * * @module * */ Davis.location = (function () { /*! * By default the Davis uses the Davis.history module for its routing, this gives HTML5 based pushState routing * which is preferrable over location.hash based routing. */ var locationDelegate = Davis.history /** * Sets the current location delegate. * * The passed delegate will be used for all Davis apps. The delegate * must respond to the following four methods `current`, `assign`, `replace` & `onChange`. * * @param {Object} the location delegate to use. * @memberOf location */ function setLocationDelegate(delegate) { locationDelegate = delegate } /** * Delegates to the locationDelegate.current method. * * This should return the current location of the app. * * @memberOf location */ function current() { return locationDelegate.current() } /*! * Creates a function which sends the location delegate the passed message name. * It handles converting a string path to an actual request * * @returns {Function} a function that calls the location delegate with the supplied method name * @memberOf location * @private */ function sendLocationDelegate (methodName) { return function (req, opts) { if (typeof req == 'string') req = new Davis.Request (req) locationDelegate[methodName](req, opts) } } /** * Delegates to the locationDelegate.assign method. * * This should set the current location for the app to that of the passed request object. * * Can take either a Davis.Request or a string representing the path of the request to assign. * * * * @param {Request} req the request to replace the current location with, either a string or a Davis.Request. * @param {Object} opts the optional options object that will be passed to the location delegate * @see Davis.Request * @memberOf location */ var assign = sendLocationDelegate('assign') /** * Delegates to the locationDelegate.replace method. * * This should replace the current location with that of the passed request. * Ideally it should not create a new entry in the browsers history. * * Can take either a Davis.Request or a string representing the path of the request to assign. * * @param {Request} req the request to replace the current location with, either a string or a Davis.Request. * @param {Object} opts the optional options object that will be passed to the location delegate * @see Davis.Request * @memberOf location */ var replace = sendLocationDelegate('replace') /** * Delegates to the locationDelegate.onChange method. * * This should add a callback that will be called any time the location changes. * The handler function will be called with a request param which is an instance of Davis.Request. * * @param {Function} handler callback function to be called on location chnage. * @see Davis.Request * @memberOf location * */ function onChange(handler) { locationDelegate.onChange(handler) } /*! * Exposing the public methods of this module * @private */ return { setLocationDelegate: setLocationDelegate, current: current, assign: assign, replace: replace, onChange: onChange } })() /*! * Davis - Request * Copyright (C) 2011 Oliver Nightingale * MIT Licensed */ Davis.Request = (function () { /** * Davis.Requests are created from click and submit events. Davis.Requests are passed to Davis.Routes * and are stored in the history stack. They are instantiated by the Davis.listener module. * * A request will have a params object which will contain all query params and form params, any named * params in a routes path will also be added to the requests params object. Also included is support * for rails style nested form params. * * By default the request method will be taken from the method attribute for forms or will be defaulted * to 'get' for links, however there is support for using a hidden field called _method in your forms * to set the correct reqeust method. * * Simple get requests can be created by just passing a path when initializing a request, to set the method * or title you have to pass in an object. * * Each request will have a timestamp property to make it easier to determine if the application is moving * forward or backward through the history stack. * * Example * * var request = new Davis.Request ("/foo/12") * * var request = new Davis.Request ("/foo/12", {title: 'foo', method: 'POST'}) * * var request = new Davis.Request({ * title: "foo", * fullPath: "/foo/12", * method: "get" * }) * * @constructor * @param {String} fullPath * @param {Object} opts An optional object with a title or method proprty * */ var Request = function (fullPath, opts) { if (typeof fullPath == 'object') { opts = fullPath fullPath = opts.fullPath delete opts.fullPath } var raw = Davis.$.extend({}, { title: "", fullPath: fullPath, method: "get", timestamp: +new Date () }, opts) raw.fullPath = raw.fullPath.replace(/\+/g, '%20') var self = this; this.raw = raw; this.params = {}; this.title = raw.title; this.queryString = raw.fullPath.split("?")[1]; this.timestamp = raw.timestamp; this._staleCallback = function () {}; if (this.queryString) { Davis.utils.forEach(this.queryString.split("&"), function (keyval) { var paramName = decodeURIComponent(keyval.split("=")[0]), paramValue = keyval.split("=")[1], nestedParamRegex = /^(\w+)\[(\w+)?\](\[\])?/, nested; if (nested = nestedParamRegex.exec(paramName)) { var paramParent = nested[1]; var paramName = nested[2]; var isArray = !!nested[3]; var parentParams = self.params[paramParent] || {}; if (isArray) { parentParams[paramName] = parentParams[paramName] || []; parentParams[paramName].push(decodeURIComponent(paramValue)); self.params[paramParent] = parentParams; } else if (!paramName && !isArray) { parentParams = self.params[paramParent] || [] parentParams.push(decodeURIComponent(paramValue)) self.params[paramParent] = parentParams } else { parentParams[paramName] = decodeURIComponent(paramValue); self.params[paramParent] = parentParams; } } else { self.params[paramName] = decodeURIComponent(paramValue); }; }); }; raw.fullPath = raw.fullPath.replace(/^https?:\/\/.+?\//, '/'); this.method = (this.params._method || raw.method).toLowerCase(); this.path = raw.fullPath .replace(/\?(.|[\r\n])+$/, "") // Remove the query string .replace(/^https?:\/\/[^\/]+/, ""); // Remove the protocol and host parts this.fullPath = raw.fullPath; this.delegateToServer = raw.delegateToServer || Davis.noop; this.isForPageLoad = raw.forPageLoad || false; if (Request.prev) Request.prev.makeStale(this); Request.prev = this; }; /** * Redirects the current request to a new location. * * Calling redirect on an instance of Davis.Request will create a new request using the path and * title of the current request. Redirected requests always have a method of 'get'. * * The request created will replace the current request in the history stack. Redirect is most * often useful inside a handler for a form submit. After succesfully handling the form the app * can redirect to another path. This means that the current form will not be re-submitted if * navigating through the history with the back or forward buttons because the request that the * submit generated has been replaced in the history stack. * * Example * * this.post('/foo', function (req) { * processFormRequest(req.params) // do something with the form request * req.redirect('/bar'); * }) * * @param {String} path The path to redirect the current request to * @param {Object} opts The optional options object that will be passed through to the location * @memberOf Request */ Request.prototype.redirect = function (path, opts) { Davis.location.replace(new Request ({ method: 'get', fullPath: path, title: this.title }), opts); }; /** * Adds a callback to be called when the request is stale. * A request becomes stale when it is no longer the current request, this normally occurs when a * new request is triggered. A request can be marked as stale manually if required. The callback * passed to whenStale will be called with the new request that is making the current request stale. * * Use the whenStale callback to 'teardown' the objects required for the current route, this gives * a chance for views to hide themselves and unbind any event handlers etc. * * Example * * this.get('/foo', function (req) { * var fooView = new FooView () * fooView.render() // display the foo view * req.whenStale(function (nextReq) { * fooView.remove() // stop displaying foo view and unbind any events * }) * }) * * @param {Function} callback A single callback that will be called when the request becomes stale. * @memberOf Request * */ Request.prototype.whenStale = function (callback) { this._staleCallback = callback; } /** * Mark the request as stale. * * This will cause the whenStale callback to be called. * * @param {Davis.Request} req The next request that has been recieved. * @memberOf Request */ Request.prototype.makeStale = function (req) { this._staleCallback.call(req, req); } /** * Returns the location or path that should be pushed onto the history stack. * * For get requests this will be the same as the path, for post, put, delete and state requests this will * be blank as no location should be pushed onto the history stack. * * @returns {String} string The location that the url bar should display and should be pushed onto the history stack for this request. * @memberOf Request */ Request.prototype.location = function () { return (this.method === 'get') ? decodeURI(this.fullPath) : '' } /** * Converts the request to a string representation of itself by combining the method and fullPath * attributes. * * @returns {String} string representation of the request * @memberOf Request */ Request.prototype.toString = function () { return [this.method.toUpperCase(), this.path].join(" ") }; /** * Converts the request to a plain object which can be converted to a JSON string. * * Used when pushing a request onto the history stack. * * @returns {Object} a plain object representation of the request. * @memberOf Request */ Request.prototype.toJSON = function () { return { title: this.raw.title, fullPath: this.raw.fullPath, method: this.raw.method, timestamp: this.raw.timestamp } } /** * Creates a new request for the page on page load. * * This is required because usually requests are generated from clicking links or submitting forms * however this doesn't happen on a page load but should still be considered a request that the * JavaScript app should handle. * * @returns {Davis.Request} A request representing the current page loading. * @memberOf Request */ Request.forPageLoad = function () { return new this ({ method: 'get', // fullPath: window.location.pathname, fullPath: Davis.location.current(), title: document.title, forPageLoad: true }); } /*! * Stores the last request * @private */ Request.prev = null return Request })() /*! * Davis - App * Copyright (C) 2011 Oliver Nightingale * MIT Licensed */ Davis.App = (function () { /** * Constructor for Davis.App * * @constructor * @returns {Davis.App} */ function App() { this.running = false; this.boundToInternalEvents = false; this.use(Davis.listener) this.use(Davis.event) this.use(Davis.router) this.use(Davis.logger) }; /** * A convinience function for changing the apps default settings. * * Should be used before starting the app to ensure any new settings * are picked up and used. * * Example: * * app.configure(function (config) { * config.linkSelector = 'a.davis' * config.formSelector = 'form.davis' * }) * * @param {Function} config This function will be executed with the context bound to the apps setting object, this will also be passed as the first argument to the function. */ App.prototype.configure = function(config) { config.call(this.settings, this.settings); }; /** * Method to include a plugin in this app. * * A plugin is just a function that will be evaluated in the context of the app. * * Example: * app.use(Davis.title) * * @param {Function} plugin The plugin to use * */ App.prototype.use = function(plugin) { plugin.apply(this, Davis.utils.toArray(arguments, 1)) }; /** * Method to add helper properties to all requests in the application. * * Helpers will be added to the Davis.Request.prototype. Care should be taken not to override any existing Davis.Request * methods. * * @param {Object} helpers An object containing helpers to mixin to the request */ App.prototype.helpers = function(helpers) { for (property in helpers) { if (helpers.hasOwnProperty(property)) Davis.Request.prototype[property] = helpers[property] } }; /** * Settings for the app. These may be overriden directly or by using the configure * convinience method. * * `linkSelector` is the jquery selector for all the links on the page that you want * Davis to respond to. These links will not trigger a normal http request. * * `formSelector` is similar to link selector but for all the forms that davis will bind to * * `throwErrors` decides whether or not any errors will be caugth by Davis. If this is set to true * errors will be thrown so that the request will not be handled by JavaScript, the server will have * to provide a response. When set to false errors in a route will be caught and the server will not * receive the request. * * `handleRouteNotFound` determines whether or not Davis should handle requests when there is no matching * route. If set to false Davis will allow the request to be passed to your server to handle if no matching * route can be found. * * `generateRequestOnPageLoad` determines whether a request should be generated for the initial page load. * by default this is set to false. A Davis.Request will not be generated with the path of the current * page. Setting this to true will cause a request to be passed to your app for the inital page load. * * @see #configure */ App.prototype.settings = { linkSelector: 'a', formSelector: 'form', throwErrors: true, handleRouteNotFound: false, generateRequestOnPageLoad: false }; /** * Starts the app's routing. * * Apps created using the convinience Davis() function are automatically started. * * Starting the app binds all links and forms, so clicks and submits * create Davis requests that will be pushed onto the browsers history stack. Browser history change * events will be picked up and the request that caused the change will be matched against the apps * routes and filters. */ App.prototype.start = function(){ var self = this; if (this.running) return if (!Davis.supported()) { this.trigger('unsupported') return }; var runFilterWith = function (request) { return function (filter) { var result = filter.run(request, request); return (typeof result === "undefined" || result); } } var beforeFiltersPass = function (request) { return Davis.utils.every( self.lookupBeforeFilter(request.method, request.path), runFilterWith(request) ) } var handleRequest = function (request) { if (beforeFiltersPass(request)) { self.trigger('lookupRoute', request) var route = self.lookupRoute(request.method, request.path); if (route) { self.trigger('runRoute', request, route); try { route.run(request) self.trigger('routeComplete', request, route) } catch (error) { self.trigger('routeError', request, route, error) } Davis.utils.every( self.lookupAfterFilter(request.method, request.path), runFilterWith(request) ); } else { self.trigger('routeNotFound', request); } } else { self.trigger('requestHalted', request) } } var bindToInternalEvents = function () { self .bind('runRoute', function (request) { self.logger.info("runRoute: " + request.toString()); }) .bind('routeNotFound', function (request) { if (!self.settings.handleRouteNotFound && !request.isForPageLoad) { self.stop() request.delegateToServer() }; self.logger.warn("routeNotFound: " + request.toString()); }) .bind('start', function () { self.logger.info("application started") }) .bind('stop', function () { self.logger.info("application stopped") }) .bind('routeError', function (request, route, error) { if (self.settings.throwErrors) throw(error) self.logger.error(error.message, error.stack) }); Davis.location.onChange(function (req) { handleRequest(req) }); self.boundToInternalEvents = true } if (!this.boundToInternalEvents) bindToInternalEvents() this.listen(); this.trigger('start') this.running = true; if (this.settings.generateRequestOnPageLoad) handleRequest(Davis.Request.forPageLoad()) }; /** * Stops the app's routing. * * Stops the app listening to clicks and submits on all forms and links found using the current * apps settings. */ App.prototype.stop = function() { this.unlisten(); this.trigger('stop') this.running = false }; return App; })()
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend( jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert(jQuery.easing.default); return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }); /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */
JavaScript
/*! jQuery.LazyJaxDavis (https://github.com/Takazudo/jQuery.LazyJaxDavis) * lastupdate: 2013-07-13 * version: 0.2.2 * author: "Takazudo" Takeshi Takatsudo * License: MIT */ (function() { var __slice = [].slice, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; (function($, window, document) { var $document, error, info, ns, wait; ns = {}; $document = $(document); wait = ns.wait = function(time) { return $.Deferred(function(defer) { return setTimeout(function() { return defer.resolve(); }, time); }); }; $.support.pushstate = $.isFunction(window.history.pushState); ns.isToId = function(path) { if ((path.charAt(0)) === '#') { return true; } else { return false; } }; ns.trimAnchor = function(str) { return str.replace(/#.*/, ''); }; ns.trimGetVals = function(path) { return path.replace(/\?.*/, ''); }; ns.tryParseAnotherPageAnchor = function(path) { var res, ret; if (ns.isToId(path)) { return false; } if ((path.indexOf('#')) === -1) { return false; } res = path.match(/^([^#]+)#(.+)/); ret = { path: res[1] }; if (res[2]) { ret.hash = "#" + res[2]; } return ret; }; ns.filterStr = function(str, expr, captureAll) { var res; if (captureAll) { res = []; str.replace(expr, function(matched, captured) { return res.push(captured); }); return res; } else { res = str.match(expr); if (res && res[1]) { return $.trim(res[1]); } else { return null; } } }; ns.logger = window.Davis ? (new Davis.logger).logger : null; ns.info = info = function(msg) { if (!ns.logger) { return; } return ns.logger.info(msg); }; ns.error = error = function(msg) { if (!ns.logger) { return; } return ns.logger.error(msg); }; ns.fetchPage = (function() { var current; current = null; return function(url, options) { var ret; ret = $.Deferred(function(defer) { var defaults; if ((current != null ? current.abort : void 0) != null) { current.abort(); } defaults = { url: url }; options = $.extend(defaults, options); current = $.ajax(options); return current.then(function(res) { current = null; return defer.resolve(res); }, function(xhr, msg) { var aborted; aborted = msg === 'abort'; return defer.reject(aborted); }); }).promise(); ret.abort = function() { return current != null ? typeof current.abort === "function" ? current.abort() : void 0 : void 0; }; return ret; }; })(); ns.Event = (function() { function Event() { this._callbacks = {}; } Event.prototype.bind = function(ev, callback) { var evs, name, _base, _i, _len; evs = ev.split(' '); for (_i = 0, _len = evs.length; _i < _len; _i++) { name = evs[_i]; (_base = this._callbacks)[name] || (_base[name] = []); this._callbacks[name].push(callback); } return this; }; Event.prototype.one = function(ev, callback) { return this.bind(ev, function() { this.unbind(ev, arguments.callee); return callback.apply(this, arguments); }); }; Event.prototype.trigger = function() { var args, callback, ev, list, _i, _len, _ref; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; ev = args.shift(); list = (_ref = this._callbacks) != null ? _ref[ev] : void 0; if (!list) { return; } for (_i = 0, _len = list.length; _i < _len; _i++) { callback = list[_i]; if (callback.apply(this, args) === false) { break; } } return this; }; Event.prototype.unbind = function(ev, callback) { var cb, i, list, _i, _len, _ref; if (!ev) { this._callbacks = {}; return this; } list = (_ref = this._callbacks) != null ? _ref[ev] : void 0; if (!list) { return this; } if (!callback) { delete this._callbacks[ev]; return this; } for (i = _i = 0, _len = list.length; _i < _len; i = ++_i) { cb = list[i]; if (!(cb === callback)) { continue; } list = list.slice(); list.splice(i, 1); this._callbacks[ev] = list; break; } return this; }; return Event; })(); ns.HistoryLogger = (function() { function HistoryLogger() { this._items = []; this._items.push(ns.trimAnchor(location.pathname)); } HistoryLogger.prototype.push = function(obj) { this._items.push(obj); return this; }; HistoryLogger.prototype.last = function() { var l; l = this._items.length; if (l) { return this._items[l - 1]; } else { return null; } }; HistoryLogger.prototype.isToSamePageRequst = function(path) { var last; path = ns.trimAnchor(path); last = ns.trimAnchor(this.last()); if (!last) { return false; } if (path === last) { return true; } else { return false; } }; HistoryLogger.prototype.size = function() { return this._items.length; }; return HistoryLogger; })(); ns.Page = (function(_super) { var eventNames; __extends(Page, _super); eventNames = ['fetchstart', 'fetchsuccess', 'fetchabort', 'fetchfail', 'pageready', 'anchorhandler']; Page.prototype.options = { ajxoptions: { dataType: 'text', cache: true }, expr: null, updatetitle: true, title: null }; Page.prototype.router = null; Page.prototype.config = null; Page.prototype._text = null; function Page(request, config, routed, router, options, hash) { var anchorhandler, _ref, _ref1, _this = this; this.request = request; this.routed = routed; this.router = router; this.hash = hash; Page.__super__.constructor.apply(this, arguments); this.config = $.extend({}, this.config, config); this.options = $.extend(true, {}, this.options, options); if (($.type(this.config.path)) === 'string') { this.path = this.config.path; } else { this.path = this.request.path; } $.each(eventNames, function(i, eventName) { return $.each(_this.config, function(key, val) { if (eventName !== key) { return true; } return _this.bind(eventName, val); }); }); anchorhandler = ((_ref = this.config) != null ? _ref.anchorhandler : void 0) || ((_ref1 = this.options) != null ? _ref1.anchorhandler : void 0); if (anchorhandler) { this._anchorhandler = anchorhandler; } this.bind('pageready', function() { if (!_this.hash) { return; } return _this._anchorhandler.call(_this, _this.hash); }); } Page.prototype._anchorhandler = function(hash) { var top; if (!hash) { return this; } top = ($document.find(hash)).offset().top; window.scrollTo(0, top); return this; }; Page.prototype.fetch = function() { var currentFetch, o, path, _ref, _ref1, _ref2, _this = this; currentFetch = null; path = this.request.path; o = ((_ref = this.options) != null ? _ref.ajaxoptions : void 0) || {}; if ((_ref1 = this.config) != null ? _ref1.method : void 0) { o.type = this.config.method; } if ((_ref2 = this.request) != null ? _ref2.params : void 0) { o.data = $.extend(true, {}, o.data, this.request.params); } this._fetchDefer = $.Deferred(function(defer) { currentFetch = ns.fetchPage(path, o); return currentFetch.then(function(text) { _this._text = text; _this.updatetitle(); return defer.resolve(); }, function(aborted) { return defer.reject({ aborted: aborted }); }).always(function() { return _this._fetchDefer = null; }); }); this._fetchDefer.abort = function() { return currentFetch.abort(); }; return this._fetchDefer; }; Page.prototype.abort = function() { var _ref; if ((_ref = this._fetchDefer) != null) { _ref.abort(); } return this; }; Page.prototype.rip = function(exprKey, captureAll) { var expr, res, _ref, _ref1; if (!this._text) { return null; } if (!exprKey) { return this._text; } expr = (_ref = this.options) != null ? (_ref1 = _ref.expr) != null ? _ref1[exprKey] : void 0 : void 0; if (!expr) { return null; } res = ns.filterStr(this._text, expr, captureAll); if (!res) { error("ripper could not find the text for key: " + exprKey); } return res; }; Page.prototype.ripAll = function(exprKey) { return this.rip(exprKey, true); }; Page.prototype.updatetitle = function() { var title; if (!this.options.updatetitle) { return this; } title = null; if (!title && this._text) { title = this.rip('title'); } if (!title) { return this; } document.title = title; return this; }; return Page; })(ns.Event); ns.Router = (function(_super) { __extends(Router, _super); Router.prototype.options = { ajaxoptions: { dataType: 'text', cache: true, type: 'GET' }, expr: { title: /<title[^>]*>([^<]*)<\/title>/, content: /<!-- LazyJaxDavis start -->([\s\S]*)<!-- LazyJaxDavis end -->/ }, davis: { linkSelector: 'a:not([href^=#]):not(.apply-nolazy)', formSelector: 'form:not(.apply-nolazy)', throwErrors: false, handleRouteNotFound: true }, minwaittime: 0, updatetitle: true, firereadyonstart: true, ignoregetvals: false }; function Router(initializer) { Router.__super__.constructor.apply(this, arguments); this.history = new ns.HistoryLogger; initializer.call(this, this); if (this.options.davis) { this._setupDavis(); } this.firePageready(!this.options.firereadyonstart); this.fireTransPageready(); } Router.prototype._createPage = function(request, config, routed, hash) { var o, res; o = { expr: this.options.expr, updatetitle: this.options.updatetitle }; if (this.options.anchorhandler) { o.anchorhandler = this.options.anchorhandler; } if (config != null ? config.ajaxoptions : void 0) { o.ajaxoptions = config.ajaxoptions; } else if (this.options.ajaxoptions) { o.ajaxoptions = this.options.ajaxoptions; } if (!hash && (request != null ? request.path : void 0)) { res = ns.tryParseAnotherPageAnchor(request.path); hash = res.hash || null; } return new ns.Page(request, config, routed, this, o, hash); }; Router.prototype._setupDavis = function() { var completePage, self, _ref; if (!$.support.pushstate) { return; } self = this; completePage = function(page) { page.bind('pageready', function() { self._findWhosePathMatches('page', page.path); self.trigger('everypageready'); return self.fireTransPageready(); }); self.history.push(page.path); return self.fetch(page); }; this.davis = new Davis(function() { var davis, _this = this; davis = this; if (self.pages) { $.each(self.pages, function(i, pageConfig) { var method; if ($.type(pageConfig.path) === 'regexp') { return; } method = (pageConfig.method || 'get').toLowerCase(); davis[method](pageConfig.path, function(request) { var page; if (self.history.isToSamePageRequst(request.path)) { return; } page = self._createPage(request, pageConfig, true); return completePage(page); }); return true; }); } if (self.options.davis.handleRouteNotFound) { davis.bind('routeNotFound', function(request) { var config, hash, page, path, res, routed; if (ns.isToId(request.path)) { self.trigger('toid', request.path); return; } res = ns.tryParseAnotherPageAnchor(request.path); hash = res.hash || null; path = res.path || request.path; if (self.history.isToSamePageRequst(path)) { return; } config = (self._findWhosePathMatches('page', path)) || null; routed = config ? true : false; page = self._createPage(request, config, routed, hash); return completePage(page); }); } return davis.configure(function(config) { return $.each(self.options.davis, function(key, val) { config[key] = val; return true; }); }); }); if ((_ref = self.davisInitializer) != null) { _ref.call(davis); } this._tweakDavis(); return this; }; Router.prototype._tweakDavis = function() { var warn, _this = this; warn = this.davis.logger.warn; info = this.davis.logger.info; this.davis.logger.warn = function() { var args; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; if ((args[0].indexOf('routeNotFound')) !== -1) { args[0] = args[0].replace(/routeNotFound/, 'unRouted'); return info.apply(_this.davis.logger, args); } else { return warn.apply(_this.davis.logger, args); } }; return this; }; Router.prototype._findWhosePathMatches = function(target, requestedPath, handleMulti) { var configs, matched, trimedPath, _this = this; if (target === 'page') { if (this.pages && this.pages.length) { configs = this.pages; } else { return null; } } else if (target === 'transRoutes') { if (this.transRoutes && this.transRoutes.length) { configs = this.transRoutes; handleMulti = true; } else { return null; } } matched = []; trimedPath = ns.trimGetVals(requestedPath); $.each(configs, function(i, config) { var path; if (_this.options.ignoregetvals || config.ignoregetvals) { path = trimedPath; } else { path = requestedPath; } if ($.type(config.path) === 'regexp') { if (config.path.test(path)) { matched.push(config); if (handleMulti) { return true; } } else { return true; } } if (config.path === path) { matched.push(config); if (handleMulti) { return true; } } return true; }); if (!handleMulti && (matched.length > 1)) { error("2 or more expr was matched about: " + requestedPath); $.each(matched, function(i, config) { return error("dumps detected page configs - path:" + config.path); }); return false; } if (handleMulti) { return matched; } else { return matched[0] || null; } }; Router.prototype.fetch = function(page) { var _this = this; return $.Deferred(function(defer) { page.trigger('fetchstart', page); _this.trigger('everyfetchstart', page); return ($.when(page.fetch(), wait(_this.options.minwaittime))).then(function() { page.trigger('fetchsuccess', page); _this.trigger('everyfetchsuccess', page); return defer.resolve(); }, function(error) { if (error.aborted) { page.trigger('fetchabort', page); return _this.trigger('everyfetchabort', page); } else { page.trigger('fetchfil', page); return _this.trigger('everyfetchfail', page); } }); }).promise(); }; Router.prototype.stop = function() { var _ref; if ((_ref = this.davis) != null) { _ref.stop(); } return this; }; Router.prototype.navigate = function(path, method) { var request; if (this.davis) { request = new Davis.Request({ method: method || 'get', fullPath: path, title: '' }); Davis.location.assign(request); } else { location.href = path; } return this; }; Router.prototype.firePageready = function(skipEvery) { var page, _ref; if ((_ref = this.pages) != null ? _ref.length : void 0) { page = this._findWhosePathMatches('page', location.pathname); if (page) { if (typeof page.pageready === "function") { page.pageready(); } } } if (skipEvery) { return this; } this.trigger('everypageready'); return this; }; Router.prototype.fireTransPageready = function() { var routings, _ref; if ((_ref = this.transRoutes) != null ? _ref.length : void 0) { routings = this._findWhosePathMatches('transRoutes', location.pathname); if (!routings.length) { return this; } $.each(routings, function(i, routing) { return typeof routing.pageready === "function" ? routing.pageready() : void 0; }); } return this; }; Router.prototype.route = function(pages) { this.pages = pages; return this; }; Router.prototype.routeTransparents = function(transRoutes) { this.transRoutes = transRoutes; return this; }; Router.prototype.routeDavis = function(initializer) { this.davisInitializer = initializer; return this; }; Router.prototype.option = function(options) { if (!options) { return this.options; } return this.options = $.extend(true, {}, this.options, options); }; return Router; })(ns.Event); $.LazyJaxDavisNs = ns; return $.LazyJaxDavis = ns.Router; })(jQuery, this, this.document); }).call(this);
JavaScript
/* * jQuery Nivo Slider v3.0.1 * http://nivo.dev7studios.com * * Copyright 2012, Dev7studios * Free to use and abuse under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ (function($) { var NivoSlider = function(element, options){ // Defaults are below var settings = $.extend({}, $.fn.nivoSlider.defaults, options); // Useful variables. Play carefully. var vars = { currentSlide: 0, currentImage: '', totalSlides: 0, running: false, paused: false, stop: false, controlNavEl: false }; // Get this slider var slider = $(element); slider.data('nivo:vars', vars).addClass('nivoSlider'); // Find our slider children var kids = slider.children(settings.selector); kids.each(function() { var child = $(this); var link = ''; if(!child.is('img')){ if(child.is('a')){ child.addClass('nivo-imageLink'); link = child; } child = child.find('img:first'); } // Get img width & height var childWidth = (childWidth === 0) ? child.attr('width') : child.width(), childHeight = (childHeight === 0) ? child.attr('height') : child.height(); if(link !== ''){ link.css('display','none'); } child.css('display','none'); vars.totalSlides++; }); // If randomStart if(settings.randomStart){ settings.startSlide = Math.floor(Math.random() * vars.totalSlides); } // Set startSlide if(settings.startSlide > 0){ if(settings.startSlide >= vars.totalSlides) { settings.startSlide = vars.totalSlides - 1; } vars.currentSlide = settings.startSlide; } // Get initial image if($(kids[vars.currentSlide]).is('img')){ vars.currentImage = $(kids[vars.currentSlide]); } else { vars.currentImage = $(kids[vars.currentSlide]).find('img:first'); } // Show initial link if($(kids[vars.currentSlide]).is('a')){ $(kids[vars.currentSlide]).css('display','block'); } // Set first background var sliderImg = $('<img class="nivo-main-image" src="#" />'); sliderImg.attr('src', vars.currentImage.attr('src')).show(); slider.append(sliderImg); // Detect Window Resize $(window).resize(function() { slider.children('img').width(slider.width()); sliderImg.attr('src', vars.currentImage.attr('src')); sliderImg.stop().height('auto'); $('.nivo-slice').remove(); $('.nivo-box').remove(); }); //Create caption slider.append($('<div class="nivo-caption"></div>')); // Process caption function var processCaption = function(settings){ var nivoCaption = $('.nivo-caption', slider); if(vars.currentImage.attr('title') != '' && vars.currentImage.attr('title') != undefined){ var title = vars.currentImage.attr('title'); if(title.substr(0,1) == '#') title = $(title).html(); if(nivoCaption.css('display') == 'block'){ setTimeout(function(){ nivoCaption.html(title); }, settings.animSpeed); } else { nivoCaption.html(title); nivoCaption.stop().fadeIn(settings.animSpeed); } } else { nivoCaption.stop().fadeOut(settings.animSpeed); } } //Process initial caption processCaption(settings); // In the words of Super Mario "let's a go!" var timer = 0; if(!settings.manualAdvance && kids.length > 1){ timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime); } // Add Direction nav if(settings.directionNav){ slider.append('<div class="nivo-directionNav"><a class="nivo-prevNav">'+ settings.prevText +'</a><a class="nivo-nextNav">'+ settings.nextText +'</a></div>'); // Hide Direction nav if(settings.directionNavHide){ $('.nivo-directionNav', slider).hide(); slider.hover(function(){ $('.nivo-directionNav', slider).show(); }, function(){ $('.nivo-directionNav', slider).hide(); }); } $('a.nivo-prevNav', slider).on('click', function(){ if(vars.running) { return false; } clearInterval(timer); timer = ''; vars.currentSlide -= 2; nivoRun(slider, kids, settings, 'prev'); }); $('a.nivo-nextNav', slider).on('click', function(){ if(vars.running) { return false; } clearInterval(timer); timer = ''; nivoRun(slider, kids, settings, 'next'); }); } // Add Control nav if(settings.controlNav){ vars.controlNavEl = $('<div class="nivo-controlNav"></div>'); slider.after(vars.controlNavEl); for(var i = 0; i < kids.length; i++){ if(settings.controlNavThumbs){ vars.controlNavEl.addClass('nivo-thumbs-enabled'); var child = kids.eq(i); if(!child.is('img')){ child = child.find('img:first'); } if(child.attr('data-thumb')) vars.controlNavEl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('data-thumb') +'" alt="" /></a>'); } else { vars.controlNavEl.append('<a class="nivo-control" rel="'+ i +'">'+ (i + 1) +'</a>'); } } //Set initial active link $('a:eq('+ vars.currentSlide +')', vars.controlNavEl).addClass('active'); $('a', vars.controlNavEl).bind('click', function(){ if(vars.running) return false; if($(this).hasClass('active')) return false; clearInterval(timer); timer = ''; sliderImg.attr('src', vars.currentImage.attr('src')); vars.currentSlide = $(this).attr('rel') - 1; nivoRun(slider, kids, settings, 'control'); }); } //For pauseOnHover setting if(settings.pauseOnHover){ slider.hover(function(){ vars.paused = true; clearInterval(timer); timer = ''; }, function(){ vars.paused = false; // Restart the timer if(timer === '' && !settings.manualAdvance){ timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime); } }); } // Event when Animation finishes slider.bind('nivo:animFinished', function(){ sliderImg.attr('src', vars.currentImage.attr('src')); vars.running = false; // Hide child links $(kids).each(function(){ if($(this).is('a')){ $(this).css('display','none'); } }); // Show current link if($(kids[vars.currentSlide]).is('a')){ $(kids[vars.currentSlide]).css('display','block'); } // Restart the timer if(timer === '' && !vars.paused && !settings.manualAdvance){ timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime); } // Trigger the afterChange callback settings.afterChange.call(this); }); // Add slices for slice animations var createSlices = function(slider, settings, vars) { if($(vars.currentImage).parent().is('a')) $(vars.currentImage).parent().css('display','block'); $('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').width(slider.width()).css('visibility', 'hidden').show(); var sliceHeight = ($('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').parent().is('a')) ? $('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').parent().height() : $('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').height(); for(var i = 0; i < settings.slices; i++){ var sliceWidth = Math.round(slider.width()/settings.slices); if(i === settings.slices-1){ slider.append( $('<div class="nivo-slice" name="'+i+'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block !important; top:0; left:-'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px;" /></div>').css({ left:(sliceWidth*i)+'px', width:(slider.width()-(sliceWidth*i))+'px', height:sliceHeight+'px', opacity:'0', overflow:'hidden' }) ); } else { slider.append( $('<div class="nivo-slice" name="'+i+'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block !important; top:0; left:-'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px;" /></div>').css({ left:(sliceWidth*i)+'px', width:sliceWidth+'px', height:sliceHeight+'px', opacity:'0', overflow:'hidden' }) ); } } $('.nivo-slice', slider).height(sliceHeight); sliderImg.stop().animate({ height: $(vars.currentImage).height() }, settings.animSpeed); }; // Add boxes for box animations var createBoxes = function(slider, settings, vars){ if($(vars.currentImage).parent().is('a')) $(vars.currentImage).parent().css('display','block'); $('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').width(slider.width()).css('visibility', 'hidden').show(); var boxWidth = Math.round(slider.width()/settings.boxCols), boxHeight = Math.round($('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').height() / settings.boxRows); for(var rows = 0; rows < settings.boxRows; rows++){ for(var cols = 0; cols < settings.boxCols; cols++){ if(cols === settings.boxCols-1){ slider.append( $('<div class="nivo-box" name="'+ cols +'" rel="'+ rows +'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block; top:-'+ (boxHeight*rows) +'px; left:-'+ (boxWidth*cols) +'px;" /></div>').css({ opacity:0, left:(boxWidth*cols)+'px', top:(boxHeight*rows)+'px', width:(slider.width()-(boxWidth*cols))+'px' }) ); $('.nivo-box[name="'+ cols +'"]', slider).height($('.nivo-box[name="'+ cols +'"] img', slider).height()+'px'); } else { slider.append( $('<div class="nivo-box" name="'+ cols +'" rel="'+ rows +'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block; top:-'+ (boxHeight*rows) +'px; left:-'+ (boxWidth*cols) +'px;" /></div>').css({ opacity:0, left:(boxWidth*cols)+'px', top:(boxHeight*rows)+'px', width:boxWidth+'px' }) ); $('.nivo-box[name="'+ cols +'"]', slider).height($('.nivo-box[name="'+ cols +'"] img', slider).height()+'px'); } } } sliderImg.stop().animate({ height: $(vars.currentImage).height() }, settings.animSpeed); }; // Private run method var nivoRun = function(slider, kids, settings, nudge){ // Get our vars var vars = slider.data('nivo:vars'); // Trigger the lastSlide callback if(vars && (vars.currentSlide === vars.totalSlides - 1)){ settings.lastSlide.call(this); } // Stop if((!vars || vars.stop) && !nudge) { return false; } // Trigger the beforeChange callback settings.beforeChange.call(this); // Set current background before change if(!nudge){ sliderImg.attr('src', vars.currentImage.attr('src')); } else { if(nudge === 'prev'){ sliderImg.attr('src', vars.currentImage.attr('src')); } if(nudge === 'next'){ sliderImg.attr('src', vars.currentImage.attr('src')); } } vars.currentSlide++; // Trigger the slideshowEnd callback if(vars.currentSlide === vars.totalSlides){ vars.currentSlide = 0; settings.slideshowEnd.call(this); } if(vars.currentSlide < 0) { vars.currentSlide = (vars.totalSlides - 1); } // Set vars.currentImage if($(kids[vars.currentSlide]).is('img')){ vars.currentImage = $(kids[vars.currentSlide]); } else { vars.currentImage = $(kids[vars.currentSlide]).find('img:first'); } // Set active links if(settings.controlNav){ $('a', vars.controlNavEl).removeClass('active'); $('a:eq('+ vars.currentSlide +')', vars.controlNavEl).addClass('active'); } // Process caption processCaption(settings); // Remove any slices from last transition $('.nivo-slice', slider).remove(); // Remove any boxes from last transition $('.nivo-box', slider).remove(); var currentEffect = settings.effect, anims = ''; // Generate random effect if(settings.effect === 'random'){ anims = new Array('sliceDownRight','sliceDownLeft','sliceUpRight','sliceUpLeft','sliceUpDown','sliceUpDownLeft','fold','fade', 'boxRandom','boxRain','boxRainReverse','boxRainGrow','boxRainGrowReverse'); currentEffect = anims[Math.floor(Math.random()*(anims.length + 1))]; if(currentEffect === undefined) { currentEffect = 'fade'; } } // Run random effect from specified set (eg: effect:'fold,fade') if(settings.effect.indexOf(',') !== -1){ anims = settings.effect.split(','); currentEffect = anims[Math.floor(Math.random()*(anims.length))]; if(currentEffect === undefined) { currentEffect = 'fade'; } } // Custom transition as defined by "data-transition" attribute if(vars.currentImage.attr('data-transition')){ currentEffect = vars.currentImage.attr('data-transition'); } // Run effects vars.running = true; var timeBuff = 0, i = 0, slices = '', firstSlice = '', totalBoxes = '', boxes = ''; if(currentEffect === 'sliceDown' || currentEffect === 'sliceDownRight' || currentEffect === 'sliceDownLeft'){ createSlices(slider, settings, vars); timeBuff = 0; i = 0; slices = $('.nivo-slice', slider); if(currentEffect === 'sliceDownLeft') { slices = $('.nivo-slice', slider)._reverse(); } slices.each(function(){ var slice = $(this); slice.css({ 'top': '0px' }); if(i === settings.slices-1){ setTimeout(function(){ slice.animate({opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + timeBuff)); } else { setTimeout(function(){ slice.animate({opacity:'1.0' }, settings.animSpeed); }, (100 + timeBuff)); } timeBuff += 50; i++; }); } else if(currentEffect === 'sliceUp' || currentEffect === 'sliceUpRight' || currentEffect === 'sliceUpLeft'){ createSlices(slider, settings, vars); timeBuff = 0; i = 0; slices = $('.nivo-slice', slider); if(currentEffect === 'sliceUpLeft') { slices = $('.nivo-slice', slider)._reverse(); } slices.each(function(){ var slice = $(this); slice.css({ 'bottom': '0px' }); if(i === settings.slices-1){ setTimeout(function(){ slice.animate({opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + timeBuff)); } else { setTimeout(function(){ slice.animate({opacity:'1.0' }, settings.animSpeed); }, (100 + timeBuff)); } timeBuff += 50; i++; }); } else if(currentEffect === 'sliceUpDown' || currentEffect === 'sliceUpDownRight' || currentEffect === 'sliceUpDownLeft'){ createSlices(slider, settings, vars); timeBuff = 0; i = 0; var v = 0; slices = $('.nivo-slice', slider); if(currentEffect === 'sliceUpDownLeft') { slices = $('.nivo-slice', slider)._reverse(); } slices.each(function(){ var slice = $(this); if(i === 0){ slice.css('top','0px'); i++; } else { slice.css('bottom','0px'); i = 0; } if(v === settings.slices-1){ setTimeout(function(){ slice.animate({opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + timeBuff)); } else { setTimeout(function(){ slice.animate({opacity:'1.0' }, settings.animSpeed); }, (100 + timeBuff)); } timeBuff += 50; v++; }); } else if(currentEffect === 'fold'){ createSlices(slider, settings, vars); timeBuff = 0; i = 0; $('.nivo-slice', slider).each(function(){ var slice = $(this); var origWidth = slice.width(); slice.css({ top:'0px', width:'0px' }); if(i === settings.slices-1){ setTimeout(function(){ slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + timeBuff)); } else { setTimeout(function(){ slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed); }, (100 + timeBuff)); } timeBuff += 50; i++; }); } else if(currentEffect === 'fade'){ createSlices(slider, settings, vars); firstSlice = $('.nivo-slice:first', slider); firstSlice.css({ 'width': slider.width() + 'px' }); firstSlice.animate({ opacity:'1.0' }, (settings.animSpeed*2), '', function(){ slider.trigger('nivo:animFinished'); }); } else if(currentEffect === 'slideInRight'){ createSlices(slider, settings, vars); firstSlice = $('.nivo-slice:first', slider); firstSlice.css({ 'width': '0px', 'opacity': '1' }); firstSlice.animate({ width: slider.width() + 'px' }, (settings.animSpeed*2), '', function(){ slider.trigger('nivo:animFinished'); }); } else if(currentEffect === 'slideInLeft'){ createSlices(slider, settings, vars); firstSlice = $('.nivo-slice:first', slider); firstSlice.css({ 'width': '0px', 'opacity': '1', 'left': '', 'right': '0px' }); firstSlice.animate({ width: slider.width() + 'px' }, (settings.animSpeed*2), '', function(){ // Reset positioning firstSlice.css({ 'left': '0px', 'right': '' }); slider.trigger('nivo:animFinished'); }); } else if(currentEffect === 'boxRandom'){ createBoxes(slider, settings, vars); totalBoxes = settings.boxCols * settings.boxRows; i = 0; timeBuff = 0; boxes = shuffle($('.nivo-box', slider)); boxes.each(function(){ var box = $(this); if(i === totalBoxes-1){ setTimeout(function(){ box.animate({ opacity:'1' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + timeBuff)); } else { setTimeout(function(){ box.animate({ opacity:'1' }, settings.animSpeed); }, (100 + timeBuff)); } timeBuff += 20; i++; }); } else if(currentEffect === 'boxRain' || currentEffect === 'boxRainReverse' || currentEffect === 'boxRainGrow' || currentEffect === 'boxRainGrowReverse'){ createBoxes(slider, settings, vars); totalBoxes = settings.boxCols * settings.boxRows; i = 0; timeBuff = 0; // Split boxes into 2D array var rowIndex = 0; var colIndex = 0; var box2Darr = []; box2Darr[rowIndex] = []; boxes = $('.nivo-box', slider); if(currentEffect === 'boxRainReverse' || currentEffect === 'boxRainGrowReverse'){ boxes = $('.nivo-box', slider)._reverse(); } boxes.each(function(){ box2Darr[rowIndex][colIndex] = $(this); colIndex++; if(colIndex === settings.boxCols){ rowIndex++; colIndex = 0; box2Darr[rowIndex] = []; } }); // Run animation for(var cols = 0; cols < (settings.boxCols * 2); cols++){ var prevCol = cols; for(var rows = 0; rows < settings.boxRows; rows++){ if(prevCol >= 0 && prevCol < settings.boxCols){ /* Due to some weird JS bug with loop vars being used in setTimeout, this is wrapped with an anonymous function call */ (function(row, col, time, i, totalBoxes) { var box = $(box2Darr[row][col]); var w = box.width(); var h = box.height(); if(currentEffect === 'boxRainGrow' || currentEffect === 'boxRainGrowReverse'){ box.width(0).height(0); } if(i === totalBoxes-1){ setTimeout(function(){ box.animate({ opacity:'1', width:w, height:h }, settings.animSpeed/1.3, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + time)); } else { setTimeout(function(){ box.animate({ opacity:'1', width:w, height:h }, settings.animSpeed/1.3); }, (100 + time)); } })(rows, prevCol, timeBuff, i, totalBoxes); i++; } prevCol--; } timeBuff += 100; } } }; // Shuffle an array var shuffle = function(arr){ for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i, 10), x = arr[--i], arr[i] = arr[j], arr[j] = x); return arr; }; // For debugging var trace = function(msg){ if(this.console && typeof console.log !== 'undefined') { console.log(msg); } }; // Start / Stop this.stop = function(){ if(!$(element).data('nivo:vars').stop){ $(element).data('nivo:vars').stop = true; trace('Stop Slider'); } }; this.start = function(){ if($(element).data('nivo:vars').stop){ $(element).data('nivo:vars').stop = false; trace('Start Slider'); } }; // Trigger the afterLoad callback settings.afterLoad.call(this); return this; }; $.fn.nivoSlider = function(options) { return this.each(function(key, value){ var element = $(this); // Return early if this element already has a plugin instance if (element.data('nivoslider')) { return element.data('nivoslider'); } // Pass options to plugin constructor var nivoslider = new NivoSlider(this, options); // Store plugin object in this element's data element.data('nivoslider', nivoslider); }); }; //Default settings $.fn.nivoSlider.defaults = { effect: 'random', slices: 15, boxCols: 8, boxRows: 4, animSpeed: 500, pauseTime: 3000, startSlide: 0, directionNav: true, directionNavHide: true, controlNav: true, controlNavThumbs: false, pauseOnHover: true, manualAdvance: false, prevText: 'Prev', nextText: 'Next', randomStart: false, beforeChange: function(){}, afterChange: function(){}, slideshowEnd: function(){}, lastSlide: function(){}, afterLoad: function(){} }; $.fn._reverse = [].reverse; })(jQuery);
JavaScript
function setTinmoiFooterBox(iframe,place_holder_id){ $(window).scroll(function(){ if(($(place_holder_id).html().length==0)&&($(document).scrollTop()>$(place_holder_id).position().top-2*348/*$(place_holder_id).height()*/)) $(place_holder_id).html(iframe); }); }
JavaScript
$(function () { $('#knw_continer').gallery({autoplay: true, interval: 5000}); $(".btn-more-pr").click(function () { $(this).parent().toggleClass("collapse"); }); $(".footer-nav-item").click(function () { $(".footer-nav-item").removeClass("active"); $(this).addClass("active"); }); $(".nav-item").click(function () { $(".nav-item").removeClass("active"); $(this).addClass("active"); }); $(".nav-search").click(function () { $(".nav-item").removeClass("active"); $(".nav-bar").addClass("collapse"); }); $(".nav-item").click(function () { if ($(".nav-bar").hasClass("expand")){ $(".nav-item").removeClass("active"); $(this).addClass("active"); } if ($(".nav-bar").hasClass("expand") && !$(this).hasClass("group")) $(".nav-bar").removeClass("expand"); else $(".nav-bar").addClass("expand"); }); $(".nav-sub-item").click(function () { $(".nav-item").removeClass("active"); $(this).parent().parent().addClass("active"); $(".nav-bar").removeClass("expand"); }); $('body').click(function (event) { if (!$(event.target).closest('.nav-search').length) { $(".nav-bar").removeClass("collapse"); } ; }); $(".pr-list-wrapper").each(function () { if ($(this).children(".pr-item").length > 0) { var w = $(this).children(".pr-item").length * 200; $(this).width(w); } }) $(".pr-list-banner-wrapper").each(function () { if ($(this).children(".pr-item-banner").length > 0) { var w = $(this).children(".pr-item-banner").length * 240; $(this).width(w); } }) var myScroll = new IScroll('#list1', { eventPassthrough: true, scrollX: true, scrollY: false }); var myScroll2 = new IScroll('#list2', { eventPassthrough: true, scrollX: true, scrollY: false }); var myScroll3 = new IScroll('#list3', { eventPassthrough: true, scrollX: true, scrollY: false, snap: true, snapSpeed: 400 }); var myScroll4 = new IScroll('#list4', { eventPassthrough: true, scrollX: true, scrollY: false, hideScrollbar: true }); initProfile(); initAccountPopup(); }); function initAccountPopup() { $("#btn-account").click(function () { showPopup("popup-account", null); switchForm("popup-login", null, null); }); $(".popup-mask").click(function () { hidePopup("popup-account", null); }); $("#btn-regis").click(function () { switchForm("popup-register-step1", "popup-login", null); }); $("#btn-submit-regis1").click(function () { switchForm("popup-register-step2", "popup-register-step1", null); }); } function showPopup(id, callback) { $(".popup").removeClass("disable").css({opacity: 0}).animate({opacity: 1}, 200); $("#" + id).stop().css({top: 0}).animate({top: 100}, 250); } function hidePopup(id, callback) { $(".popup").animate({opacity: 0}, 200, function () { $(this).addClass("disable"); }); $("#" + id).stop().animate({top: 0}, 200); } function switchForm(id, oldId, callback) { $(".popup-content").each(function () { if (!$(this).hasClass("disable")) { oldId = this.id; return; } }); $("#" + id).removeClass("disable").css({top: 390, opacity: 0}).animate({top: 0, opacity: 1}, 1000, "easeOutQuint"); if (oldId && oldId != id) $("#" + oldId).css({top: 0, opacity: 1}).animate({top: -390, opacity: 0}, 1000, "easeOutQuint", function () { $(this).addClass("disable"); }); } function initProfile() { $(".pr-profile-menu-item.edit").click(function () { showPage("profile-page-edit"); $(".pr-profile-menu-item").removeClass("active"); $(this).addClass("active"); }); $(".pr-profile-menu-item.change-pass").click(function () { showPage("profile-page-password"); $(".pr-profile-menu-item").removeClass("active"); $(this).addClass("active"); }); } function showPage(id, callback) { $(".pr-profile-page:not(#" + id + ")").css({left: 0, opacity: 1}).animate({left: 200, opacity: 0}, 1000, "easeOutQuint", function () { $(this).addClass("disable"); }); $("#" + id).removeClass("disable"); $("#" + id).stop().css({left: 200, opacity: 0}).animate({left: 0, opacity: 1}, 1000, "easeOutQuint"); }
JavaScript
(function( $, undefined ) { /* * Gallery object. */ $.Gallery = function( options, element ) { this.$el = $( element ); this._init( options ); }; $.Gallery.defaults = { current : 0, // index of current item autoplay : false,// slideshow on / off interval : 2000 // time between transitions }; $.Gallery.prototype = { _init : function( options ) { this.options = $.extend( true, {}, $.Gallery.defaults, options ); // support for 3d / 2d transforms and transitions this.support3d = Modernizr.csstransforms3d; this.support2d = Modernizr.csstransforms; this.supportTrans = Modernizr.csstransitions; this.$wrapper = this.$el.find('.dg-wrapper'); this.$items = this.$wrapper.children(); this.itemsCount = this.$items.length; this.$nav = this.$el.find('nav'); this.$navPrev = this.$nav.find('.dg-prev'); this.$navNext = this.$nav.find('.dg-next'); // minimum of 3 items if( this.itemsCount < 3 ) { this.$nav.remove(); return false; } this.current = this.options.current; this.isAnim = false; this.$items.css({ 'opacity' : 0, 'visibility': 'hidden' }); this._validate(); this._layout(); // load the events this._loadEvents(); // slideshow if( this.options.autoplay ) { this._startSlideshow(); } }, _validate : function() { if( this.options.current < 0 || this.options.current > this.itemsCount - 1 ) { this.current = 0; } }, _layout : function() { // current, left and right items this._setItems(); // current item is not changed // left and right one are rotated and translated var leftCSS, rightCSS, currentCSS; if( this.support3d && this.supportTrans ) { leftCSS = { '-webkit-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', '-moz-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', '-o-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', '-ms-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', 'transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)' }; rightCSS = { '-webkit-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', '-moz-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', '-o-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', '-ms-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', 'transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)' }; leftCSS.opacity = 1; leftCSS.visibility = 'visible'; rightCSS.opacity = 1; rightCSS.visibility = 'visible'; } else if( this.support2d && this.supportTrans ) { leftCSS = { '-webkit-transform' : 'translate(-350px) scale(0.8)', '-moz-transform' : 'translate(-350px) scale(0.8)', '-o-transform' : 'translate(-350px) scale(0.8)', '-ms-transform' : 'translate(-350px) scale(0.8)', 'transform' : 'translate(-350px) scale(0.8)' }; rightCSS = { '-webkit-transform' : 'translate(350px) scale(0.8)', '-moz-transform' : 'translate(350px) scale(0.8)', '-o-transform' : 'translate(350px) scale(0.8)', '-ms-transform' : 'translate(350px) scale(0.8)', 'transform' : 'translate(350px) scale(0.8)' }; currentCSS = { 'z-index' : 999 }; leftCSS.opacity = 1; leftCSS.visibility = 'visible'; rightCSS.opacity = 1; rightCSS.visibility = 'visible'; } this.$leftItm.css( leftCSS || {} ); this.$rightItm.css( rightCSS || {} ); this.$currentItm.css( currentCSS || {} ).css({ 'opacity' : 1, 'visibility': 'visible' }).addClass('dg-center'); }, _setItems : function() { this.$items.removeClass('dg-center'); this.$currentItm = this.$items.eq( this.current ); this.$leftItm = ( this.current === 0 ) ? this.$items.eq( this.itemsCount - 1 ) : this.$items.eq( this.current - 1 ); this.$rightItm = ( this.current === this.itemsCount - 1 ) ? this.$items.eq( 0 ) : this.$items.eq( this.current + 1 ); if( !this.support3d && this.support2d && this.supportTrans ) { this.$items.css( 'z-index', 1 ); this.$currentItm.css( 'z-index', 999 ); } // next & previous items if( this.itemsCount > 3 ) { // next item this.$nextItm = ( this.$rightItm.index() === this.itemsCount - 1 ) ? this.$items.eq( 0 ) : this.$rightItm.next(); this.$nextItm.css( this._getCoordinates('outright') ); // previous item this.$prevItm = ( this.$leftItm.index() === 0 ) ? this.$items.eq( this.itemsCount - 1 ) : this.$leftItm.prev(); this.$prevItm.css( this._getCoordinates('outleft') ); } }, _loadEvents : function() { var _self = this; this.$navPrev.on( 'click.gallery', function( event ) { if( _self.options.autoplay ) { clearTimeout( _self.slideshow ); _self.options.autoplay = false; } _self._navigate('prev'); return false; }); this.$navNext.on( 'click.gallery', function( event ) { if( _self.options.autoplay ) { clearTimeout( _self.slideshow ); _self.options.autoplay = false; } _self._navigate('next'); return false; }); this.$wrapper.on( 'webkitTransitionEnd.gallery transitionend.gallery OTransitionEnd.gallery', function( event ) { _self.$currentItm.addClass('dg-center'); _self.$items.removeClass('dg-transition'); _self.isAnim = false; }); }, _getCoordinates : function( position ) { if( this.support3d && this.supportTrans ) { switch( position ) { case 'outleft': return { '-webkit-transform' : 'translateX(-450px) translateZ(-300px) rotateY(45deg)', '-moz-transform' : 'translateX(-450px) translateZ(-300px) rotateY(45deg)', '-o-transform' : 'translateX(-450px) translateZ(-300px) rotateY(45deg)', '-ms-transform' : 'translateX(-450px) translateZ(-300px) rotateY(45deg)', 'transform' : 'translateX(-450px) translateZ(-300px) rotateY(45deg)', 'opacity' : 0, 'visibility' : 'hidden' }; break; case 'outright': return { '-webkit-transform' : 'translateX(450px) translateZ(-300px) rotateY(-45deg)', '-moz-transform' : 'translateX(450px) translateZ(-300px) rotateY(-45deg)', '-o-transform' : 'translateX(450px) translateZ(-300px) rotateY(-45deg)', '-ms-transform' : 'translateX(450px) translateZ(-300px) rotateY(-45deg)', 'transform' : 'translateX(450px) translateZ(-300px) rotateY(-45deg)', 'opacity' : 0, 'visibility' : 'hidden' }; break; case 'left': return { '-webkit-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', '-moz-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', '-o-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', '-ms-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', 'transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', 'opacity' : 1, 'visibility' : 'visible' }; break; case 'right': return { '-webkit-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', '-moz-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', '-o-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', '-ms-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', 'transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', 'opacity' : 1, 'visibility' : 'visible' }; break; case 'center': return { '-webkit-transform' : 'translateX(0px) translateZ(0px) rotateY(0deg)', '-moz-transform' : 'translateX(0px) translateZ(0px) rotateY(0deg)', '-o-transform' : 'translateX(0px) translateZ(0px) rotateY(0deg)', '-ms-transform' : 'translateX(0px) translateZ(0px) rotateY(0deg)', 'transform' : 'translateX(0px) translateZ(0px) rotateY(0deg)', 'opacity' : 1, 'visibility' : 'visible' }; break; }; } else if( this.support2d && this.supportTrans ) { switch( position ) { case 'outleft': return { '-webkit-transform' : 'translate(-450px) scale(0.7)', '-moz-transform' : 'translate(-450px) scale(0.7)', '-o-transform' : 'translate(-450px) scale(0.7)', '-ms-transform' : 'translate(-450px) scale(0.7)', 'transform' : 'translate(-450px) scale(0.7)', 'opacity' : 0, 'visibility' : 'hidden' }; break; case 'outright': return { '-webkit-transform' : 'translate(450px) scale(0.7)', '-moz-transform' : 'translate(450px) scale(0.7)', '-o-transform' : 'translate(450px) scale(0.7)', '-ms-transform' : 'translate(450px) scale(0.7)', 'transform' : 'translate(450px) scale(0.7)', 'opacity' : 0, 'visibility' : 'hidden' }; break; case 'left': return { '-webkit-transform' : 'translate(-350px) scale(0.8)', '-moz-transform' : 'translate(-350px) scale(0.8)', '-o-transform' : 'translate(-350px) scale(0.8)', '-ms-transform' : 'translate(-350px) scale(0.8)', 'transform' : 'translate(-350px) scale(0.8)', 'opacity' : 1, 'visibility' : 'visible' }; break; case 'right': return { '-webkit-transform' : 'translate(350px) scale(0.8)', '-moz-transform' : 'translate(350px) scale(0.8)', '-o-transform' : 'translate(350px) scale(0.8)', '-ms-transform' : 'translate(350px) scale(0.8)', 'transform' : 'translate(350px) scale(0.8)', 'opacity' : 1, 'visibility' : 'visible' }; break; case 'center': return { '-webkit-transform' : 'translate(0px) scale(1)', '-moz-transform' : 'translate(0px) scale(1)', '-o-transform' : 'translate(0px) scale(1)', '-ms-transform' : 'translate(0px) scale(1)', 'transform' : 'translate(0px) scale(1)', 'opacity' : 1, 'visibility' : 'visible' }; break; }; } else { switch( position ) { case 'outleft' : case 'outright' : case 'left' : case 'right' : return { 'opacity' : 0, 'visibility' : 'hidden' }; break; case 'center' : return { 'opacity' : 1, 'visibility' : 'visible' }; break; }; } }, _navigate : function( dir ) { if( this.supportTrans && this.isAnim ) return false; this.isAnim = true; switch( dir ) { case 'next' : this.current = this.$rightItm.index(); // current item moves left this.$currentItm.addClass('dg-transition').css( this._getCoordinates('left') ); // right item moves to the center this.$rightItm.addClass('dg-transition').css( this._getCoordinates('center') ); // next item moves to the right if( this.$nextItm ) { // left item moves out this.$leftItm.addClass('dg-transition').css( this._getCoordinates('outleft') ); this.$nextItm.addClass('dg-transition').css( this._getCoordinates('right') ); } else { // left item moves right this.$leftItm.addClass('dg-transition').css( this._getCoordinates('right') ); } break; case 'prev' : this.current = this.$leftItm.index(); // current item moves right this.$currentItm.addClass('dg-transition').css( this._getCoordinates('right') ); // left item moves to the center this.$leftItm.addClass('dg-transition').css( this._getCoordinates('center') ); // prev item moves to the left if( this.$prevItm ) { // right item moves out this.$rightItm.addClass('dg-transition').css( this._getCoordinates('outright') ); this.$prevItm.addClass('dg-transition').css( this._getCoordinates('left') ); } else { // right item moves left this.$rightItm.addClass('dg-transition').css( this._getCoordinates('left') ); } break; }; this._setItems(); if( !this.supportTrans ) this.$currentItm.addClass('dg-center'); }, _startSlideshow : function() { var _self = this; this.slideshow = setTimeout( function() { _self._navigate( 'next' ); if( _self.options.autoplay ) { _self._startSlideshow(); } }, this.options.interval ); }, destroy : function() { this.$navPrev.off('.gallery'); this.$navNext.off('.gallery'); this.$wrapper.off('.gallery'); } }; var logError = function( message ) { if ( this.console ) { console.error( message ); } }; $.fn.gallery = function( options ) { if ( typeof options === 'string' ) { var args = Array.prototype.slice.call( arguments, 1 ); this.each(function() { var instance = $.data( this, 'gallery' ); if ( !instance ) { logError( "cannot call methods on gallery prior to initialization; " + "attempted to call method '" + options + "'" ); return; } if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) { logError( "no such method '" + options + "' for gallery instance" ); return; } instance[ options ].apply( instance, args ); }); } else { this.each(function() { var instance = $.data( this, 'gallery' ); if ( !instance ) { $.data( this, 'gallery', new $.Gallery( options, this ) ); } }); } return this; }; })( jQuery );
JavaScript
/*! iScroll v5.0.4 ~ (c) 2008-2013 Matteo Spinelli ~ http://cubiq.org/license */ var IScroll = (function (window, document, Math) { var rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }; var utils = (function () { var me = {}; var _elementStyle = document.createElement('div').style; var _vendor = (function () { var vendors = ['t', 'webkitT', 'MozT', 'msT', 'OT'], transform, i = 0, l = vendors.length; for ( ; i < l; i++ ) { transform = vendors[i] + 'ransform'; if ( transform in _elementStyle ) return vendors[i].substr(0, vendors[i].length-1); } return false; })(); function _prefixStyle (style) { if ( _vendor === false ) return false; if ( _vendor === '' ) return style; return _vendor + style.charAt(0).toUpperCase() + style.substr(1); } me.getTime = Date.now || function getTime () { return new Date().getTime(); }; me.extend = function (target, obj) { for ( var i in obj ) { target[i] = obj[i]; } }; me.addEvent = function (el, type, fn, capture) { el.addEventListener(type, fn, !!capture); }; me.removeEvent = function (el, type, fn, capture) { el.removeEventListener(type, fn, !!capture); }; me.momentum = function (current, start, time, lowerMargin, wrapperSize) { var distance = current - start, speed = Math.abs(distance) / time, destination, duration, deceleration = 0.0006; destination = current + ( speed * speed ) / ( 2 * deceleration ) * ( distance < 0 ? -1 : 1 ); duration = speed / deceleration; if ( destination < lowerMargin ) { destination = wrapperSize ? lowerMargin - ( wrapperSize / 2.5 * ( speed / 8 ) ) : lowerMargin; distance = Math.abs(destination - current); duration = distance / speed; } else if ( destination > 0 ) { destination = wrapperSize ? wrapperSize / 2.5 * ( speed / 8 ) : 0; distance = Math.abs(current) + destination; duration = distance / speed; } return { destination: Math.round(destination), duration: duration }; }; var _transform = _prefixStyle('transform'); me.extend(me, { hasTransform: _transform !== false, hasPerspective: _prefixStyle('perspective') in _elementStyle, hasTouch: 'ontouchstart' in window, hasPointer: navigator.msPointerEnabled, hasTransition: _prefixStyle('transition') in _elementStyle }); me.isAndroidBrowser = /Android/.test(window.navigator.appVersion) && /Version\/\d/.test(window.navigator.appVersion); me.extend(me.style = {}, { transform: _transform, transitionTimingFunction: _prefixStyle('transitionTimingFunction'), transitionDuration: _prefixStyle('transitionDuration'), transformOrigin: _prefixStyle('transformOrigin') }); me.hasClass = function (e, c) { var re = new RegExp("(^|\\s)" + c + "(\\s|$)"); return re.test(e.className); }; me.addClass = function (e, c) { if ( me.hasClass(e, c) ) { return; } var newclass = e.className.split(' '); newclass.push(c); e.className = newclass.join(' '); }; me.removeClass = function (e, c) { if ( !me.hasClass(e, c) ) { return; } var re = new RegExp("(^|\\s)" + c + "(\\s|$)", 'g'); e.className = e.className.replace(re, ''); }; me.offset = function (el) { var left = -el.offsetLeft, top = -el.offsetTop; // jshint -W084 while (el = el.offsetParent) { left -= el.offsetLeft; top -= el.offsetTop; } // jshint +W084 return { left: left, top: top }; }; me.extend(me.eventType = {}, { touchstart: 1, touchmove: 1, touchend: 1, mousedown: 2, mousemove: 2, mouseup: 2, MSPointerDown: 3, MSPointerMove: 3, MSPointerUp: 3 }); me.extend(me.ease = {}, { quadratic: { style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)', fn: function (k) { return k * ( 2 - k ); } }, circular: { style: 'cubic-bezier(0.1, 0.57, 0.1, 1)', // Not properly "circular" but this looks better, it should be (0.075, 0.82, 0.165, 1) fn: function (k) { return Math.sqrt( 1 - ( --k * k ) ); } }, back: { style: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)', fn: function (k) { var b = 4; return ( k = k - 1 ) * k * ( ( b + 1 ) * k + b ) + 1; } }, bounce: { style: '', fn: function (k) { if ( ( k /= 1 ) < ( 1 / 2.75 ) ) { return 7.5625 * k * k; } else if ( k < ( 2 / 2.75 ) ) { return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; } else if ( k < ( 2.5 / 2.75 ) ) { return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; } else { return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; } } }, elastic: { style: '', fn: function (k) { var f = 0.22, e = 0.4; if ( k === 0 ) { return 0; } if ( k == 1 ) { return 1; } return ( e * Math.pow( 2, - 10 * k ) * Math.sin( ( k - f / 4 ) * ( 2 * Math.PI ) / f ) + 1 ); } } }); me.tap = function (e, eventName) { var ev = document.createEvent('Event'); ev.initEvent(eventName, true, true); ev.pageX = e.pageX; ev.pageY = e.pageY; e.target.dispatchEvent(ev); }; me.click = function (e) { var target = e.target, ev; if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') { ev = document.createEvent('MouseEvents'); ev.initMouseEvent('click', true, true, e.view, 1, target.screenX, target.screenY, target.clientX, target.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, 0, null); ev._constructed = true; target.dispatchEvent(ev); } }; return me; })(); function IScroll (el, options) { this.wrapper = typeof el == 'string' ? document.querySelector(el) : el; this.scroller = this.wrapper.children[0]; this.scrollerStyle = this.scroller.style; // cache style for better performance this.options = { resizeIndicator: true, mouseWheelSpeed: 20, snapThreshold: 0.334, // INSERT POINT: OPTIONS startX: 0, startY: 0, scrollY: true, directionLockThreshold: 5, momentum: true, bounce: true, bounceTime: 600, bounceEasing: '', preventDefault: true, HWCompositing: true, useTransition: true, useTransform: true }; for ( var i in options ) { this.options[i] = options[i]; } // Normalize options this.translateZ = this.options.HWCompositing && utils.hasPerspective ? ' translateZ(0)' : ''; this.options.useTransition = utils.hasTransition && this.options.useTransition; this.options.useTransform = utils.hasTransform && this.options.useTransform; this.options.eventPassthrough = this.options.eventPassthrough === true ? 'vertical' : this.options.eventPassthrough; this.options.preventDefault = !this.options.eventPassthrough && this.options.preventDefault; // If you want eventPassthrough I have to lock one of the axes this.options.scrollY = this.options.eventPassthrough == 'vertical' ? false : this.options.scrollY; this.options.scrollX = this.options.eventPassthrough == 'horizontal' ? false : this.options.scrollX; // With eventPassthrough we also need lockDirection mechanism this.options.freeScroll = this.options.freeScroll && !this.options.eventPassthrough; this.options.directionLockThreshold = this.options.eventPassthrough ? 0 : this.options.directionLockThreshold; this.options.bounceEasing = typeof this.options.bounceEasing == 'string' ? utils.ease[this.options.bounceEasing] || utils.ease.circular : this.options.bounceEasing; this.options.resizePolling = this.options.resizePolling === undefined ? 60 : this.options.resizePolling; if ( this.options.tap === true ) { this.options.tap = 'tap'; } this.options.invertWheelDirection = this.options.invertWheelDirection ? -1 : 1; // INSERT POINT: NORMALIZATION // Some defaults this.x = 0; this.y = 0; this.directionX = 0; this.directionY = 0; this._events = {}; // INSERT POINT: DEFAULTS this._init(); this.refresh(); this.scrollTo(this.options.startX, this.options.startY); this.enable(); } IScroll.prototype = { version: '5.0.4', _init: function () { this._initEvents(); if ( this.options.scrollbars || this.options.indicators ) { this._initIndicators(); } if ( this.options.mouseWheel ) { this._initWheel(); } if ( this.options.snap ) { this._initSnap(); } if ( this.options.keyBindings ) { this._initKeys(); } // INSERT POINT: _init }, destroy: function () { this._initEvents(true); this._execEvent('destroy'); }, _transitionEnd: function (e) { if ( e.target != this.scroller ) { return; } this._transitionTime(0); if ( !this.resetPosition(this.options.bounceTime) ) { this._execEvent('scrollEnd'); } }, _start: function (e) { // React to left mouse button only if ( utils.eventType[e.type] != 1 ) { if ( e.button !== 0 ) { return; } } if ( !this.enabled || (this.initiated && utils.eventType[e.type] !== this.initiated) ) { return; } if ( this.options.preventDefault && !utils.isAndroidBrowser ) { e.preventDefault(); // This seems to break default Android browser } var point = e.touches ? e.touches[0] : e, pos; this.initiated = utils.eventType[e.type]; this.moved = false; this.distX = 0; this.distY = 0; this.directionX = 0; this.directionY = 0; this.directionLocked = 0; this._transitionTime(); this.isAnimating = false; this.startTime = utils.getTime(); if ( this.options.useTransition && this.isInTransition ) { pos = this.getComputedPosition(); this._translate(Math.round(pos.x), Math.round(pos.y)); this.isInTransition = false; } this.startX = this.x; this.startY = this.y; this.absStartX = this.x; this.absStartY = this.y; this.pointX = point.pageX; this.pointY = point.pageY; this._execEvent('scrollStart'); }, _move: function (e) { if ( !this.enabled || utils.eventType[e.type] !== this.initiated ) { return; } if ( this.options.preventDefault ) { // increases performance on Android? TODO: check! e.preventDefault(); } var point = e.touches ? e.touches[0] : e, deltaX = this.hasHorizontalScroll ? point.pageX - this.pointX : 0, deltaY = this.hasVerticalScroll ? point.pageY - this.pointY : 0, timestamp = utils.getTime(), newX, newY, absDistX, absDistY; this.pointX = point.pageX; this.pointY = point.pageY; this.distX += deltaX; this.distY += deltaY; absDistX = Math.abs(this.distX); absDistY = Math.abs(this.distY); // We need to move at least 10 pixels for the scrolling to initiate if ( timestamp - this.endTime > 300 && (absDistX < 10 && absDistY < 10) ) { return; } // If you are scrolling in one direction lock the other if ( !this.directionLocked && !this.options.freeScroll ) { if ( absDistX > absDistY + this.options.directionLockThreshold ) { this.directionLocked = 'h'; // lock horizontally } else if ( absDistY >= absDistX + this.options.directionLockThreshold ) { this.directionLocked = 'v'; // lock vertically } else { this.directionLocked = 'n'; // no lock } } if ( this.directionLocked == 'h' ) { if ( this.options.eventPassthrough == 'vertical' ) { e.preventDefault(); } else if ( this.options.eventPassthrough == 'horizontal' ) { this.initiated = false; return; } deltaY = 0; } else if ( this.directionLocked == 'v' ) { if ( this.options.eventPassthrough == 'horizontal' ) { e.preventDefault(); } else if ( this.options.eventPassthrough == 'vertical' ) { this.initiated = false; return; } deltaX = 0; } newX = this.x + deltaX; newY = this.y + deltaY; // Slow down if outside of the boundaries if ( newX > 0 || newX < this.maxScrollX ) { newX = this.options.bounce ? this.x + deltaX / 3 : newX > 0 ? 0 : this.maxScrollX; } if ( newY > 0 || newY < this.maxScrollY ) { newY = this.options.bounce ? this.y + deltaY / 3 : newY > 0 ? 0 : this.maxScrollY; } this.directionX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0; this.directionY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0; this.moved = true; this._translate(newX, newY); /* REPLACE START: _move */ if ( timestamp - this.startTime > 300 ) { this.startTime = timestamp; this.startX = this.x; this.startY = this.y; } /* REPLACE END: _move */ }, _end: function (e) { if ( !this.enabled || utils.eventType[e.type] !== this.initiated ) { return; } if ( this.options.preventDefault ) { e.preventDefault(); // TODO: check if needed } var point = e.changedTouches ? e.changedTouches[0] : e, momentumX, momentumY, duration = utils.getTime() - this.startTime, newX = Math.round(this.x), newY = Math.round(this.y), distanceX = Math.abs(newX - this.startX), distanceY = Math.abs(newY - this.startY), time = 0, easing = ''; this.scrollTo(newX, newY); // ensures that the last position is rounded this.isInTransition = 0; this.initiated = 0; this.endTime = utils.getTime(); // reset if we are outside of the boundaries if ( this.resetPosition(this.options.bounceTime) ) { return; } // we scrolled less than 10 pixels if ( !this.moved ) { if ( this.options.tap ) { utils.tap(e, this.options.tap); } if ( this.options.click ) { utils.click(e); } return; } if ( this._events.flick && duration < 200 && distanceX < 100 && distanceY < 100 ) { this._execEvent('flick'); return; } // start momentum animation if needed if ( this.options.momentum && duration < 300 ) { momentumX = this.hasHorizontalScroll ? utils.momentum(this.x, this.startX, duration, this.maxScrollX, this.options.bounce ? this.wrapperWidth : 0) : { destination: newX, duration: 0 }; momentumY = this.hasVerticalScroll ? utils.momentum(this.y, this.startY, duration, this.maxScrollY, this.options.bounce ? this.wrapperHeight : 0) : { destination: newY, duration: 0 }; newX = momentumX.destination; newY = momentumY.destination; time = Math.max(momentumX.duration, momentumY.duration); this.isInTransition = 1; } if ( this.options.snap ) { var snap = this._nearestSnap(newX, newY); this.currentPage = snap; newX = snap.x; newY = snap.y; time = this.options.snapSpeed || Math.max( Math.max( Math.min(distanceX, 1000), Math.min(distanceX, 1000) ), 300); this.directionX = 0; this.directionY = 0; easing = this.options.bounceEasing; } if ( newX != this.x || newY != this.y ) { // change easing function when scroller goes out of the boundaries if ( newX > 0 || newX < this.maxScrollX || newY > 0 || newY < this.maxScrollY ) { easing = utils.ease.quadratic; } this.scrollTo(newX, newY, time, easing); return; } this._execEvent('scrollEnd'); }, _resize: function () { var that = this; clearTimeout(this.resizeTimeout); this.resizeTimeout = setTimeout(function () { that.refresh(); }, this.options.resizePolling); }, resetPosition: function (time) { var x = this.x, y = this.y; time = time || 0; if ( !this.hasHorizontalScroll || this.x > 0 ) { x = 0; } else if ( this.x < this.maxScrollX ) { x = this.maxScrollX; } if ( !this.hasVerticalScroll || this.y > 0 ) { y = 0; } else if ( this.y < this.maxScrollY ) { y = this.maxScrollY; } if ( x == this.x && y == this.y ) { return false; } this.scrollTo(x, y, time, this.options.bounceEasing); return true; }, disable: function () { this.enabled = false; }, enable: function () { this.enabled = true; }, refresh: function () { var rf = this.wrapper.offsetHeight; // Force reflow this.wrapperWidth = this.wrapper.clientWidth; this.wrapperHeight = this.wrapper.clientHeight; /* REPLACE START: refresh */ this.scrollerWidth = this.scroller.offsetWidth; this.scrollerHeight = this.scroller.offsetHeight; /* REPLACE END: refresh */ this.maxScrollX = this.wrapperWidth - this.scrollerWidth; this.maxScrollY = this.wrapperHeight - this.scrollerHeight; this.hasHorizontalScroll = this.options.scrollX && this.maxScrollX < 0; this.hasVerticalScroll = this.options.scrollY && this.maxScrollY < 0; if ( !this.hasHorizontalScroll ) { this.maxScrollX = 0; this.scrollerWidth = this.wrapperWidth; } if ( !this.hasVerticalScroll ) { this.maxScrollY = 0; this.scrollerHeight = this.wrapperHeight; } this.endTime = 0; this.directionX = 0; this.directionY = 0; this.wrapperOffset = utils.offset(this.wrapper); this._execEvent('refresh'); this.resetPosition(); if ( this.options.snap ) { var snap = this._nearestSnap(this.x, this.y); if ( this.x == snap.x && this.y == snap.y ) { return; } this.currentPage = snap; this.scrollTo(snap.x, snap.y); } }, on: function (type, fn) { if ( !this._events[type] ) { this._events[type] = []; } this._events[type].push(fn); }, _execEvent: function (type) { if ( !this._events[type] ) { return; } var i = 0, l = this._events[type].length; if ( !l ) { return; } for ( ; i < l; i++ ) { this._events[type][i].call(this); } }, scrollBy: function (x, y, time, easing) { x = this.x + x; y = this.y + y; time = time || 0; this.scrollTo(x, y, time, easing); }, scrollTo: function (x, y, time, easing) { easing = easing || utils.ease.circular; if ( !time || (this.options.useTransition && easing.style) ) { this._transitionTimingFunction(easing.style); this._transitionTime(time); this._translate(x, y); } else { this._animate(x, y, time, easing.fn); } }, scrollToElement: function (el, time, offsetX, offsetY, easing) { el = el.nodeType ? el : this.scroller.querySelector(el); if ( !el ) { return; } var pos = utils.offset(el); pos.left -= this.wrapperOffset.left; pos.top -= this.wrapperOffset.top; // if offsetX/Y are true we center the element to the screen if ( offsetX === true ) { offsetX = Math.round(el.offsetWidth / 2 - this.wrapper.offsetWidth / 2); } if ( offsetY === true ) { offsetY = Math.round(el.offsetHeight / 2 - this.wrapper.offsetHeight / 2); } pos.left -= offsetX || 0; pos.top -= offsetY || 0; pos.left = pos.left > 0 ? 0 : pos.left < this.maxScrollX ? this.maxScrollX : pos.left; pos.top = pos.top > 0 ? 0 : pos.top < this.maxScrollY ? this.maxScrollY : pos.top; time = time === undefined || time === null || time === 'auto' ? Math.max(Math.abs(pos.left)*2, Math.abs(pos.top)*2) : time; this.scrollTo(pos.left, pos.top, time, easing); }, _transitionTime: function (time) { time = time || 0; this.scrollerStyle[utils.style.transitionDuration] = time + 'ms'; if ( this.indicator1 ) { this.indicator1.transitionTime(time); } if ( this.indicator2 ) { this.indicator2.transitionTime(time); } // INSERT POINT: _transitionTime }, _transitionTimingFunction: function (easing) { this.scrollerStyle[utils.style.transitionTimingFunction] = easing; if ( this.indicator1 ) { this.indicator1.transitionTimingFunction(easing); } if ( this.indicator2 ) { this.indicator2.transitionTimingFunction(easing); } // INSERT POINT: _transitionTimingFunction }, _translate: function (x, y) { if ( this.options.useTransform ) { /* REPLACE START: _translate */ this.scrollerStyle[utils.style.transform] = 'translate(' + x + 'px,' + y + 'px)' + this.translateZ; /* REPLACE END: _translate */ } else { x = Math.round(x); y = Math.round(y); this.scrollerStyle.left = x + 'px'; this.scrollerStyle.top = y + 'px'; } this.x = x; this.y = y; if ( this.indicator1 ) { // usually the vertical this.indicator1.updatePosition(); } if ( this.indicator2 ) { this.indicator2.updatePosition(); } // INSERT POINT: _translate }, _initEvents: function (remove) { var eventType = remove ? utils.removeEvent : utils.addEvent, target = this.options.bindToWrapper ? this.wrapper : window; eventType(window, 'orientationchange', this); eventType(window, 'resize', this); eventType(this.wrapper, 'mousedown', this); eventType(target, 'mousemove', this); eventType(target, 'mousecancel', this); eventType(target, 'mouseup', this); if ( utils.hasPointer ) { eventType(this.wrapper, 'MSPointerDown', this); eventType(target, 'MSPointerMove', this); eventType(target, 'MSPointerCancel', this); eventType(target, 'MSPointerUp', this); } if ( utils.hasTouch ) { eventType(this.wrapper, 'touchstart', this); eventType(target, 'touchmove', this); eventType(target, 'touchcancel', this); eventType(target, 'touchend', this); } eventType(this.scroller, 'transitionend', this); eventType(this.scroller, 'webkitTransitionEnd', this); eventType(this.scroller, 'oTransitionEnd', this); eventType(this.scroller, 'MSTransitionEnd', this); }, getComputedPosition: function () { var matrix = window.getComputedStyle(this.scroller, null), x, y; if ( this.options.useTransform ) { matrix = matrix[utils.style.transform].split(')')[0].split(', '); x = +(matrix[12] || matrix[4]); y = +(matrix[13] || matrix[5]); } else { x = +matrix.left.replace(/[^-\d]/g, ''); y = +matrix.top.replace(/[^-\d]/g, ''); } return { x: x, y: y }; }, _initIndicators: function () { var interactive = this.options.interactiveScrollbars, defaultScrollbars = typeof this.options.scrollbars != 'object', customStyle = typeof this.options.scrollbars != 'string', indicator1, indicator2; if ( this.options.scrollbars ) { // Vertical scrollbar if ( this.options.scrollY ) { indicator1 = { el: createDefaultScrollbar('v', interactive, this.options.scrollbars), interactive: interactive, defaultScrollbars: true, customStyle: customStyle, resize: this.options.resizeIndicator, listenX: false }; this.wrapper.appendChild(indicator1.el); } // Horizontal scrollbar if ( this.options.scrollX ) { indicator2 = { el: createDefaultScrollbar('h', interactive, this.options.scrollbars), interactive: interactive, defaultScrollbars: true, customStyle: customStyle, resize: this.options.resizeIndicator, listenY: false }; this.wrapper.appendChild(indicator2.el); } } else { indicator1 = this.options.indicators.length ? this.options.indicators[0] : this.options.indicators; indicator2 = this.options.indicators[1] && this.options.indicators[1]; } if ( indicator1 ) { this.indicator1 = new Indicator(this, indicator1); } if ( indicator2 ) { this.indicator2 = new Indicator(this, indicator2); } this.on('refresh', function () { if ( this.indicator1 ) { this.indicator1.refresh(); } if ( this.indicator2 ) { this.indicator2.refresh(); } }); this.on('destroy', function () { if ( this.indicator1 ) { this.indicator1.destroy(); this.indicator1 = null; } if ( this.indicator2 ) { this.indicator2.destroy(); this.indicator2 = null; } }); }, _initWheel: function () { utils.addEvent(this.wrapper, 'mousewheel', this); utils.addEvent(this.wrapper, 'DOMMouseScroll', this); this.on('destroy', function () { utils.removeEvent(this.wrapper, 'mousewheel', this); utils.removeEvent(this.wrapper, 'DOMMouseScroll', this); }); }, _wheel: function (e) { if ( !this.enabled ) { return; } var wheelDeltaX, wheelDeltaY, newX, newY, that = this; // Execute the scrollEnd event after 400ms the wheel stopped scrolling clearTimeout(this.wheelTimeout); this.wheelTimeout = setTimeout(function () { that._execEvent('scrollEnd'); }, 400); e.preventDefault(); if ( 'wheelDeltaX' in e ) { wheelDeltaX = e.wheelDeltaX / 120; wheelDeltaY = e.wheelDeltaY / 120; } else if ( 'wheelDelta' in e ) { wheelDeltaX = wheelDeltaY = e.wheelDelta / 120; } else if ( 'detail' in e ) { wheelDeltaX = wheelDeltaY = -e.detail / 3; } else { return; } wheelDeltaX *= this.options.mouseWheelSpeed; wheelDeltaY *= this.options.mouseWheelSpeed; if ( !this.hasVerticalScroll ) { wheelDeltaX = wheelDeltaY; } newX = this.x + (this.hasHorizontalScroll ? wheelDeltaX * this.options.invertWheelDirection : 0); newY = this.y + (this.hasVerticalScroll ? wheelDeltaY * this.options.invertWheelDirection : 0); if ( newX > 0 ) { newX = 0; } else if ( newX < this.maxScrollX ) { newX = this.maxScrollX; } if ( newY > 0 ) { newY = 0; } else if ( newY < this.maxScrollY ) { newY = this.maxScrollY; } this.scrollTo(newX, newY, 0); // INSERT POINT: _wheel }, _initSnap: function () { this.currentPage = {}; if ( typeof this.options.snap == 'string' ) { this.options.snap = this.scroller.querySelectorAll(this.options.snap); } this.on('refresh', function () { var i = 0, l, m = 0, n, cx, cy, x = 0, y, stepX = this.options.snapStepX || this.wrapperWidth, stepY = this.options.snapStepY || this.wrapperHeight, el; this.pages = []; if ( this.options.snap === true ) { cx = Math.round( stepX / 2 ); cy = Math.round( stepY / 2 ); while ( x > -this.scrollerWidth ) { this.pages[i] = []; l = 0; y = 0; while ( y > -this.scrollerHeight ) { this.pages[i][l] = { x: Math.max(x, this.maxScrollX), y: Math.max(y, this.maxScrollY), width: stepX, height: stepY, cx: x - cx, cy: y - cy }; y -= stepY; l++; } x -= stepX; i++; } } else { el = this.options.snap; l = el.length; n = -1; for ( ; i < l; i++ ) { if ( i === 0 || el[i].offsetLeft <= el[i-1].offsetLeft ) { m = 0; n++; } if ( !this.pages[m] ) { this.pages[m] = []; } x = Math.max(-el[i].offsetLeft, this.maxScrollX); y = Math.max(-el[i].offsetTop, this.maxScrollY); cx = x - Math.round(el[i].offsetWidth / 2); cy = y - Math.round(el[i].offsetHeight / 2); this.pages[m][n] = { x: x, y: y, width: el[i].offsetWidth, height: el[i].offsetHeight, cx: cx, cy: cy }; if ( x > this.maxScrollX ) { m++; } } } this.goToPage(this.currentPage.pageX || 0, this.currentPage.pageY || 0, 0); // Update snap threshold if needed if ( this.options.snapThreshold % 1 === 0 ) { this.snapThresholdX = this.options.snapThreshold; this.snapThresholdY = this.options.snapThreshold; } else { this.snapThresholdX = Math.round(this.pages[this.currentPage.pageX][this.currentPage.pageY].width * this.options.snapThreshold); this.snapThresholdY = Math.round(this.pages[this.currentPage.pageX][this.currentPage.pageY].height * this.options.snapThreshold); } }); this.on('flick', function () { var time = this.options.snapSpeed || Math.max( Math.max( Math.min(Math.abs(this.x - this.startX), 1000), Math.min(Math.abs(this.y - this.startY), 1000) ), 300); this.goToPage( this.currentPage.pageX + this.directionX, this.currentPage.pageY + this.directionY, time ); }); }, _nearestSnap: function (x, y) { var i = 0, l = this.pages.length, m = 0; // Check if we exceeded the snap threshold if ( Math.abs(x - this.absStartX) < this.snapThresholdX && Math.abs(y - this.absStartY) < this.snapThresholdY ) { return this.currentPage; } if ( x > 0 ) { x = 0; } else if ( x < this.maxScrollX ) { x = this.maxScrollX; } if ( y > 0 ) { y = 0; } else if ( y < this.maxScrollY ) { y = this.maxScrollY; } for ( ; i < l; i++ ) { if ( x >= this.pages[i][0].cx ) { x = this.pages[i][0].x; break; } } l = this.pages[i].length; for ( ; m < l; m++ ) { if ( y >= this.pages[0][m].cy ) { y = this.pages[0][m].y; break; } } if ( i == this.currentPage.pageX ) { i += this.directionX; if ( i < 0 ) { i = 0; } else if ( i >= this.pages.length ) { i = this.pages.length - 1; } x = this.pages[i][0].x; } if ( m == this.currentPage.pageY ) { m += this.directionY; if ( m < 0 ) { m = 0; } else if ( m >= this.pages[0].length ) { m = this.pages[0].length - 1; } y = this.pages[0][m].y; } return { x: x, y: y, pageX: i, pageY: m }; }, goToPage: function (x, y, time, easing) { easing = easing || this.options.bounceEasing; if ( x >= this.pages.length ) { x = this.pages.length - 1; } else if ( x < 0 ) { x = 0; } if ( y >= this.pages[0].length ) { y = this.pages[0].length - 1; } else if ( y < 0 ) { y = 0; } var posX = this.pages[x][y].x, posY = this.pages[x][y].y; time = time === undefined ? this.options.snapSpeed || Math.max( Math.max( Math.min(Math.abs(posX - this.x), 1000), Math.min(Math.abs(posY - this.y), 1000) ), 300) : time; this.currentPage = { x: posX, y: posY, pageX: x, pageY: y }; this.scrollTo(posX, posY, time, easing); }, next: function (time, easing) { var x = this.currentPage.pageX, y = this.currentPage.pageY; x++; if ( x >= this.pages.length && this.hasVerticalScroll ) { x = 0; y++; } this.goToPage(x, y, time, easing); }, prev: function (time, easing) { var x = this.currentPage.pageX, y = this.currentPage.pageY; x--; if ( x < 0 && this.hasVerticalScroll ) { x = 0; y--; } this.goToPage(x, y, time, easing); }, _initKeys: function (e) { // default key bindings var keys = { pageUp: 33, pageDown: 34, end: 35, home: 36, left: 37, up: 38, right: 39, down: 40 }; var i; // if you give me characters I give you keycode if ( typeof this.options.keyBindings == 'object' ) { for ( i in this.options.keyBindings ) { if ( typeof this.options.keyBindings[i] == 'string' ) { this.options.keyBindings[i] = this.options.keyBindings[i].toUpperCase().charCodeAt(0); } } } else { this.options.keyBindings = {}; } for ( i in keys ) { this.options.keyBindings[i] = this.options.keyBindings[i] || keys[i]; } utils.addEvent(window, 'keydown', this); this.on('destroy', function () { utils.removeEvent(window, 'keydown', this); }); }, _key: function (e) { if ( !this.enabled ) { return; } var snap = this.options.snap, // we are using this alot, better to cache it newX = snap ? this.currentPage.pageX : this.x, newY = snap ? this.currentPage.pageY : this.y, now = utils.getTime(), prevTime = this.keyTime || 0, acceleration = 0.250, pos; if ( this.options.useTransition && this.isInTransition ) { pos = this.getComputedPosition(); this._translate(Math.round(pos.x), Math.round(pos.y)); this.isInTransition = false; } this.keyAcceleration = now - prevTime < 200 ? Math.min(this.keyAcceleration + acceleration, 50) : 0; switch ( e.keyCode ) { case this.options.keyBindings.pageUp: if ( this.hasHorizontalScroll && !this.hasVerticalScroll ) { newX += snap ? 1 : this.wrapperWidth; } else { newY += snap ? 1 : this.wrapperHeight; } break; case this.options.keyBindings.pageDown: if ( this.hasHorizontalScroll && !this.hasVerticalScroll ) { newX -= snap ? 1 : this.wrapperWidth; } else { newY -= snap ? 1 : this.wrapperHeight; } break; case this.options.keyBindings.end: newX = snap ? this.pages.length-1 : this.maxScrollX; newY = snap ? this.pages[0].length-1 : this.maxScrollY; break; case this.options.keyBindings.home: newX = 0; newY = 0; break; case this.options.keyBindings.left: newX += snap ? -1 : 5 + this.keyAcceleration>>0; break; case this.options.keyBindings.up: newY += snap ? 1 : 5 + this.keyAcceleration>>0; break; case this.options.keyBindings.right: newX -= snap ? -1 : 5 + this.keyAcceleration>>0; break; case this.options.keyBindings.down: newY -= snap ? 1 : 5 + this.keyAcceleration>>0; break; } if ( snap ) { this.goToPage(newX, newY); return; } if ( newX > 0 ) { newX = 0; this.keyAcceleration = 0; } else if ( newX < this.maxScrollX ) { newX = this.maxScrollX; this.keyAcceleration = 0; } if ( newY > 0 ) { newY = 0; this.keyAcceleration = 0; } else if ( newY < this.maxScrollY ) { newY = this.maxScrollY; this.keyAcceleration = 0; } this.scrollTo(newX, newY, 0); this.keyTime = now; }, _animate: function (destX, destY, duration, easingFn) { var that = this, startX = this.x, startY = this.y, startTime = utils.getTime(), destTime = startTime + duration; function step () { var now = utils.getTime(), newX, newY, easing; if ( now >= destTime ) { that.isAnimating = false; that._translate(destX, destY); if ( !that.resetPosition(that.options.bounceTime) ) { that._execEvent('scrollEnd'); } return; } now = ( now - startTime ) / duration; easing = easingFn(now); newX = ( destX - startX ) * easing + startX; newY = ( destY - startY ) * easing + startY; that._translate(newX, newY); if ( that.isAnimating ) { rAF(step); } } this.isAnimating = true; step(); }, handleEvent: function (e) { switch ( e.type ) { case 'touchstart': case 'MSPointerDown': case 'mousedown': this._start(e); break; case 'touchmove': case 'MSPointerMove': case 'mousemove': this._move(e); break; case 'touchend': case 'MSPointerUp': case 'mouseup': case 'touchcancel': case 'MSPointerCancel': case 'mousecancel': this._end(e); break; case 'orientationchange': case 'resize': this._resize(); break; case 'transitionend': case 'webkitTransitionEnd': case 'oTransitionEnd': case 'MSTransitionEnd': this._transitionEnd(e); break; case 'DOMMouseScroll': case 'mousewheel': this._wheel(e); break; case 'keydown': this._key(e); break; } } }; function createDefaultScrollbar (direction, interactive, type) { var scrollbar = document.createElement('div'), indicator = document.createElement('div'); if ( type === true ) { scrollbar.style.cssText = 'position:absolute;z-index:9999'; indicator.style.cssText = '-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);border-radius:3px'; } indicator.className = 'iScrollIndicator'; if ( direction == 'h' ) { if ( type === true ) { scrollbar.style.cssText += ';height:7px;left:2px;right:2px;bottom:0'; indicator.style.height = '100%'; } scrollbar.className = 'iScrollHorizontalScrollbar'; } else { if ( type === true ) { scrollbar.style.cssText += ';width:7px;bottom:2px;top:2px;right:1px'; indicator.style.width = '100%'; } scrollbar.className = 'iScrollVerticalScrollbar'; } if ( !interactive ) { scrollbar.style.pointerEvents = 'none'; } scrollbar.appendChild(indicator); return scrollbar; } function Indicator (scroller, options) { this.wrapper = typeof options.el == 'string' ? document.querySelector(options.el) : options.el; this.indicator = this.wrapper.children[0]; this.indicatorStyle = this.indicator.style; this.scroller = scroller; this.options = { listenX: true, listenY: true, interactive: false, resize: true, defaultScrollbars: false, speedRatioX: 0, speedRatioY: 0 }; for ( var i in options ) { this.options[i] = options[i]; } this.sizeRatioX = 1; this.sizeRatioY = 1; this.maxPosX = 0; this.maxPosY = 0; if ( this.options.interactive ) { utils.addEvent(this.indicator, 'touchstart', this); utils.addEvent(this.indicator, 'MSPointerDown', this); utils.addEvent(this.indicator, 'mousedown', this); utils.addEvent(window, 'touchend', this); utils.addEvent(window, 'MSPointerUp', this); utils.addEvent(window, 'mouseup', this); } } Indicator.prototype = { handleEvent: function (e) { switch ( e.type ) { case 'touchstart': case 'MSPointerDown': case 'mousedown': this._start(e); break; case 'touchmove': case 'MSPointerMove': case 'mousemove': this._move(e); break; case 'touchend': case 'MSPointerUp': case 'mouseup': case 'touchcancel': case 'MSPointerCancel': case 'mousecancel': this._end(e); break; } }, destroy: function () { if ( this.options.interactive ) { utils.removeEvent(this.indicator, 'touchstart', this); utils.removeEvent(this.indicator, 'MSPointerDown', this); utils.removeEvent(this.indicator, 'mousedown', this); utils.removeEvent(window, 'touchmove', this); utils.removeEvent(window, 'MSPointerMove', this); utils.removeEvent(window, 'mousemove', this); utils.removeEvent(window, 'touchend', this); utils.removeEvent(window, 'MSPointerUp', this); utils.removeEvent(window, 'mouseup', this); } if ( this.options.defaultScrollbars ) { this.wrapper.parentNode.removeChild(this.wrapper); } }, _start: function (e) { var point = e.touches ? e.touches[0] : e; e.preventDefault(); e.stopPropagation(); this.transitionTime(0); this.initiated = true; this.moved = false; this.lastPointX = point.pageX; this.lastPointY = point.pageY; this.startTime = utils.getTime(); utils.addEvent(window, 'touchmove', this); utils.addEvent(window, 'MSPointerMove', this); utils.addEvent(window, 'mousemove', this); this.scroller._execEvent('scrollStart'); }, _move: function (e) { var point = e.touches ? e.touches[0] : e, deltaX, deltaY, newX, newY, timestamp = utils.getTime(); this.moved = true; deltaX = point.pageX - this.lastPointX; this.lastPointX = point.pageX; deltaY = point.pageY - this.lastPointY; this.lastPointY = point.pageY; newX = this.x + deltaX; newY = this.y + deltaY; this._pos(newX, newY); e.preventDefault(); e.stopPropagation(); }, _end: function (e) { if ( !this.initiated ) { return; } this.initiated = false; e.preventDefault(); e.stopPropagation(); utils.removeEvent(window, 'touchmove', this); utils.removeEvent(window, 'MSPointerMove', this); utils.removeEvent(window, 'mousemove', this); if ( this.moved ) { this.scroller._execEvent('scrollEnd'); } }, transitionTime: function (time) { time = time || 0; this.indicatorStyle[utils.style.transitionDuration] = time + 'ms'; }, transitionTimingFunction: function (easing) { this.indicatorStyle[utils.style.transitionTimingFunction] = easing; }, refresh: function () { this.transitionTime(0); if ( this.options.listenX && !this.options.listenY ) { this.indicatorStyle.display = this.scroller.hasHorizontalScroll ? 'block' : 'none'; } else if ( this.options.listenY && !this.options.listenX ) { this.indicatorStyle.display = this.scroller.hasVerticalScroll ? 'block' : 'none'; } else { this.indicatorStyle.display = this.scroller.hasHorizontalScroll || this.scroller.hasVerticalScroll ? 'block' : 'none'; } if ( this.scroller.hasHorizontalScroll && this.scroller.hasVerticalScroll ) { utils.addClass(this.wrapper, 'iScrollBothScrollbars'); utils.removeClass(this.wrapper, 'iScrollLoneScrollbar'); if ( this.options.defaultScrollbars && this.options.customStyle ) { if ( this.options.listenX ) { this.wrapper.style.right = '8px'; } else { this.wrapper.style.bottom = '8px'; } } } else { utils.removeClass(this.wrapper, 'iScrollBothScrollbars'); utils.addClass(this.wrapper, 'iScrollLoneScrollbar'); if ( this.options.defaultScrollbars && this.options.customStyle ) { if ( this.options.listenX ) { this.wrapper.style.right = '2px'; } else { this.wrapper.style.bottom = '2px'; } } } var r = this.wrapper.offsetHeight; // force refresh if ( this.options.listenX ) { this.wrapperWidth = this.wrapper.clientWidth; if ( this.options.resize ) { this.indicatorWidth = Math.max(Math.round(this.wrapperWidth * this.wrapperWidth / this.scroller.scrollerWidth), 8); this.indicatorStyle.width = this.indicatorWidth + 'px'; } else { this.indicatorWidth = this.indicator.clientWidth; } this.maxPosX = this.wrapperWidth - this.indicatorWidth; this.sizeRatioX = this.options.speedRatioX || (this.scroller.maxScrollX && (this.maxPosX / this.scroller.maxScrollX)); } if ( this.options.listenY ) { this.wrapperHeight = this.wrapper.clientHeight; if ( this.options.resize ) { this.indicatorHeight = Math.max(Math.round(this.wrapperHeight * this.wrapperHeight / this.scroller.scrollerHeight), 8); this.indicatorStyle.height = this.indicatorHeight + 'px'; } else { this.indicatorHeight = this.indicator.clientHeight; } this.maxPosY = this.wrapperHeight - this.indicatorHeight; this.sizeRatioY = this.options.speedRatioY || (this.scroller.maxScrollY && (this.maxPosY / this.scroller.maxScrollY)); } this.updatePosition(); }, updatePosition: function () { var x = Math.round(this.sizeRatioX * this.scroller.x) || 0, y = Math.round(this.sizeRatioY * this.scroller.y) || 0; if ( !this.options.ignoreBoundaries ) { if ( x < 0 ) { x = 0; } else if ( x > this.maxPosX ) { x = this.maxPosX; } if ( y < 0 ) { y = 0; } else if ( y > this.maxPosY ) { y = this.maxPosY; } } this.x = x; this.y = y; if ( this.scroller.options.useTransform ) { this.indicatorStyle[utils.style.transform] = 'translate(' + x + 'px,' + y + 'px)' + this.scroller.translateZ; } else { this.indicatorStyle.left = x + 'px'; this.indicatorStyle.top = y + 'px'; } }, _pos: function (x, y) { if ( x < 0 ) { x = 0; } else if ( x > this.maxPosX ) { x = this.maxPosX; } if ( y < 0 ) { y = 0; } else if ( y > this.maxPosY ) { y = this.maxPosY; } x = this.options.listenX ? Math.round(x / this.sizeRatioX) : this.scroller.x; y = this.options.listenY ? Math.round(y / this.sizeRatioY) : this.scroller.y; this.scroller.scrollTo(x, y); } }; IScroll.ease = utils.ease; return IScroll; })(window, document, Math);
JavaScript
$(function () { $('#knw_continer').gallery({autoplay: true, interval: 5000}); $(".btn-more-pr").click(function () { $(this).parent().toggleClass("collapse"); }) initProfile(); initAccountPopup(); }); function initAccountPopup() { $("#btn-account").click(function () { showPopup("popup-account", null); switchForm("popup-login", null, null) }); $(".popup-mask").click(function () { hidePopup("popup-account", null); }); $("#btn-regis").click(function () { switchForm("popup-register-step1", "popup-login", null) }); $("#btn-submit-regis1").click(function () { switchForm("popup-register-step2", "popup-register-step1", null) }); } function showPopup(id, callback) { $(".popup").removeClass("disable").css({opacity: 0}).animate({opacity: 1}, 200); $("#" + id).stop().css({top: 0}).animate({top: 100}, 250); } function hidePopup(id, callback) { $(".popup").animate({opacity: 0}, 200, function () { $(this).addClass("disable"); }); $("#" + id).stop().animate({top: 0}, 200); } function switchForm(id, oldId, callback) { $(".popup-content").each(function () { if (!$(this).hasClass("disable")) { oldId = this.id; return; } }); $("#" + id).removeClass("disable").css({top: 390, opacity: 0}).animate({top: 0, opacity: 1}, 1000, "easeOutQuint"); if (oldId && oldId != id) $("#" + oldId).css({top: 0, opacity: 1}).animate({top: -390, opacity: 0}, 1000, "easeOutQuint", function () { $(this).addClass("disable"); }); } function initProfile() { $(".pr-profile-menu-item.edit").click(function () { showPage("profile-page-edit"); $(".pr-profile-menu-item").removeClass("active"); $(this).addClass("active"); }); $(".pr-profile-menu-item.change-pass").click(function () { showPage("profile-page-password"); $(".pr-profile-menu-item").removeClass("active"); $(this).addClass("active"); }); } function showPage(id, callback) { $(".pr-profile-page:not(#" + id + ")").css({left: 0, opacity: 1}).animate({left: 200, opacity: 0}, 1000, "easeOutQuint", function () { $(this).addClass("disable"); }); $("#" + id).removeClass("disable"); $("#" + id).stop().css({left: 200, opacity: 0}).animate({left: 0, opacity: 1}, 1000, "easeOutQuint"); }
JavaScript
(function( $, undefined ) { /* * Gallery object. */ $.Gallery = function( options, element ) { this.$el = $( element ); this._init( options ); }; $.Gallery.defaults = { current : 0, // index of current item autoplay : false,// slideshow on / off interval : 2000 // time between transitions }; $.Gallery.prototype = { _init : function( options ) { this.options = $.extend( true, {}, $.Gallery.defaults, options ); // support for 3d / 2d transforms and transitions this.support3d = Modernizr.csstransforms3d; this.support2d = Modernizr.csstransforms; this.supportTrans = Modernizr.csstransitions; this.$wrapper = this.$el.find('.dg-wrapper'); this.$items = this.$wrapper.children(); this.itemsCount = this.$items.length; this.$nav = this.$el.find('nav'); this.$navPrev = this.$nav.find('.dg-prev'); this.$navNext = this.$nav.find('.dg-next'); // minimum of 3 items if( this.itemsCount < 3 ) { this.$nav.remove(); return false; } this.current = this.options.current; this.isAnim = false; this.$items.css({ 'opacity' : 0, 'visibility': 'hidden' }); this._validate(); this._layout(); // load the events this._loadEvents(); // slideshow if( this.options.autoplay ) { this._startSlideshow(); } }, _validate : function() { if( this.options.current < 0 || this.options.current > this.itemsCount - 1 ) { this.current = 0; } }, _layout : function() { // current, left and right items this._setItems(); // current item is not changed // left and right one are rotated and translated var leftCSS, rightCSS, currentCSS; if( this.support3d && this.supportTrans ) { leftCSS = { '-webkit-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', '-moz-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', '-o-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', '-ms-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', 'transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)' }; rightCSS = { '-webkit-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', '-moz-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', '-o-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', '-ms-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', 'transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)' }; leftCSS.opacity = 1; leftCSS.visibility = 'visible'; rightCSS.opacity = 1; rightCSS.visibility = 'visible'; } else if( this.support2d && this.supportTrans ) { leftCSS = { '-webkit-transform' : 'translate(-350px) scale(0.8)', '-moz-transform' : 'translate(-350px) scale(0.8)', '-o-transform' : 'translate(-350px) scale(0.8)', '-ms-transform' : 'translate(-350px) scale(0.8)', 'transform' : 'translate(-350px) scale(0.8)' }; rightCSS = { '-webkit-transform' : 'translate(350px) scale(0.8)', '-moz-transform' : 'translate(350px) scale(0.8)', '-o-transform' : 'translate(350px) scale(0.8)', '-ms-transform' : 'translate(350px) scale(0.8)', 'transform' : 'translate(350px) scale(0.8)' }; currentCSS = { 'z-index' : 999 }; leftCSS.opacity = 1; leftCSS.visibility = 'visible'; rightCSS.opacity = 1; rightCSS.visibility = 'visible'; } this.$leftItm.css( leftCSS || {} ); this.$rightItm.css( rightCSS || {} ); this.$currentItm.css( currentCSS || {} ).css({ 'opacity' : 1, 'visibility': 'visible' }).addClass('dg-center'); }, _setItems : function() { this.$items.removeClass('dg-center'); this.$currentItm = this.$items.eq( this.current ); this.$leftItm = ( this.current === 0 ) ? this.$items.eq( this.itemsCount - 1 ) : this.$items.eq( this.current - 1 ); this.$rightItm = ( this.current === this.itemsCount - 1 ) ? this.$items.eq( 0 ) : this.$items.eq( this.current + 1 ); if( !this.support3d && this.support2d && this.supportTrans ) { this.$items.css( 'z-index', 1 ); this.$currentItm.css( 'z-index', 999 ); } // next & previous items if( this.itemsCount > 3 ) { // next item this.$nextItm = ( this.$rightItm.index() === this.itemsCount - 1 ) ? this.$items.eq( 0 ) : this.$rightItm.next(); this.$nextItm.css( this._getCoordinates('outright') ); // previous item this.$prevItm = ( this.$leftItm.index() === 0 ) ? this.$items.eq( this.itemsCount - 1 ) : this.$leftItm.prev(); this.$prevItm.css( this._getCoordinates('outleft') ); } }, _loadEvents : function() { var _self = this; this.$navPrev.on( 'click.gallery', function( event ) { if( _self.options.autoplay ) { clearTimeout( _self.slideshow ); _self.options.autoplay = false; } _self._navigate('prev'); return false; }); this.$navNext.on( 'click.gallery', function( event ) { if( _self.options.autoplay ) { clearTimeout( _self.slideshow ); _self.options.autoplay = false; } _self._navigate('next'); return false; }); this.$wrapper.on( 'webkitTransitionEnd.gallery transitionend.gallery OTransitionEnd.gallery', function( event ) { _self.$currentItm.addClass('dg-center'); _self.$items.removeClass('dg-transition'); _self.isAnim = false; }); }, _getCoordinates : function( position ) { if( this.support3d && this.supportTrans ) { switch( position ) { case 'outleft': return { '-webkit-transform' : 'translateX(-450px) translateZ(-300px) rotateY(45deg)', '-moz-transform' : 'translateX(-450px) translateZ(-300px) rotateY(45deg)', '-o-transform' : 'translateX(-450px) translateZ(-300px) rotateY(45deg)', '-ms-transform' : 'translateX(-450px) translateZ(-300px) rotateY(45deg)', 'transform' : 'translateX(-450px) translateZ(-300px) rotateY(45deg)', 'opacity' : 0, 'visibility' : 'hidden' }; break; case 'outright': return { '-webkit-transform' : 'translateX(450px) translateZ(-300px) rotateY(-45deg)', '-moz-transform' : 'translateX(450px) translateZ(-300px) rotateY(-45deg)', '-o-transform' : 'translateX(450px) translateZ(-300px) rotateY(-45deg)', '-ms-transform' : 'translateX(450px) translateZ(-300px) rotateY(-45deg)', 'transform' : 'translateX(450px) translateZ(-300px) rotateY(-45deg)', 'opacity' : 0, 'visibility' : 'hidden' }; break; case 'left': return { '-webkit-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', '-moz-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', '-o-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', '-ms-transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', 'transform' : 'translateX(-350px) translateZ(-200px) rotateY(45deg)', 'opacity' : 1, 'visibility' : 'visible' }; break; case 'right': return { '-webkit-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', '-moz-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', '-o-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', '-ms-transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', 'transform' : 'translateX(350px) translateZ(-200px) rotateY(-45deg)', 'opacity' : 1, 'visibility' : 'visible' }; break; case 'center': return { '-webkit-transform' : 'translateX(0px) translateZ(0px) rotateY(0deg)', '-moz-transform' : 'translateX(0px) translateZ(0px) rotateY(0deg)', '-o-transform' : 'translateX(0px) translateZ(0px) rotateY(0deg)', '-ms-transform' : 'translateX(0px) translateZ(0px) rotateY(0deg)', 'transform' : 'translateX(0px) translateZ(0px) rotateY(0deg)', 'opacity' : 1, 'visibility' : 'visible' }; break; }; } else if( this.support2d && this.supportTrans ) { switch( position ) { case 'outleft': return { '-webkit-transform' : 'translate(-450px) scale(0.7)', '-moz-transform' : 'translate(-450px) scale(0.7)', '-o-transform' : 'translate(-450px) scale(0.7)', '-ms-transform' : 'translate(-450px) scale(0.7)', 'transform' : 'translate(-450px) scale(0.7)', 'opacity' : 0, 'visibility' : 'hidden' }; break; case 'outright': return { '-webkit-transform' : 'translate(450px) scale(0.7)', '-moz-transform' : 'translate(450px) scale(0.7)', '-o-transform' : 'translate(450px) scale(0.7)', '-ms-transform' : 'translate(450px) scale(0.7)', 'transform' : 'translate(450px) scale(0.7)', 'opacity' : 0, 'visibility' : 'hidden' }; break; case 'left': return { '-webkit-transform' : 'translate(-350px) scale(0.8)', '-moz-transform' : 'translate(-350px) scale(0.8)', '-o-transform' : 'translate(-350px) scale(0.8)', '-ms-transform' : 'translate(-350px) scale(0.8)', 'transform' : 'translate(-350px) scale(0.8)', 'opacity' : 1, 'visibility' : 'visible' }; break; case 'right': return { '-webkit-transform' : 'translate(350px) scale(0.8)', '-moz-transform' : 'translate(350px) scale(0.8)', '-o-transform' : 'translate(350px) scale(0.8)', '-ms-transform' : 'translate(350px) scale(0.8)', 'transform' : 'translate(350px) scale(0.8)', 'opacity' : 1, 'visibility' : 'visible' }; break; case 'center': return { '-webkit-transform' : 'translate(0px) scale(1)', '-moz-transform' : 'translate(0px) scale(1)', '-o-transform' : 'translate(0px) scale(1)', '-ms-transform' : 'translate(0px) scale(1)', 'transform' : 'translate(0px) scale(1)', 'opacity' : 1, 'visibility' : 'visible' }; break; }; } else { switch( position ) { case 'outleft' : case 'outright' : case 'left' : case 'right' : return { 'opacity' : 0, 'visibility' : 'hidden' }; break; case 'center' : return { 'opacity' : 1, 'visibility' : 'visible' }; break; }; } }, _navigate : function( dir ) { if( this.supportTrans && this.isAnim ) return false; this.isAnim = true; switch( dir ) { case 'next' : this.current = this.$rightItm.index(); // current item moves left this.$currentItm.addClass('dg-transition').css( this._getCoordinates('left') ); // right item moves to the center this.$rightItm.addClass('dg-transition').css( this._getCoordinates('center') ); // next item moves to the right if( this.$nextItm ) { // left item moves out this.$leftItm.addClass('dg-transition').css( this._getCoordinates('outleft') ); this.$nextItm.addClass('dg-transition').css( this._getCoordinates('right') ); } else { // left item moves right this.$leftItm.addClass('dg-transition').css( this._getCoordinates('right') ); } break; case 'prev' : this.current = this.$leftItm.index(); // current item moves right this.$currentItm.addClass('dg-transition').css( this._getCoordinates('right') ); // left item moves to the center this.$leftItm.addClass('dg-transition').css( this._getCoordinates('center') ); // prev item moves to the left if( this.$prevItm ) { // right item moves out this.$rightItm.addClass('dg-transition').css( this._getCoordinates('outright') ); this.$prevItm.addClass('dg-transition').css( this._getCoordinates('left') ); } else { // right item moves left this.$rightItm.addClass('dg-transition').css( this._getCoordinates('left') ); } break; }; this._setItems(); if( !this.supportTrans ) this.$currentItm.addClass('dg-center'); }, _startSlideshow : function() { var _self = this; this.slideshow = setTimeout( function() { _self._navigate( 'next' ); if( _self.options.autoplay ) { _self._startSlideshow(); } }, this.options.interval ); }, destroy : function() { this.$navPrev.off('.gallery'); this.$navNext.off('.gallery'); this.$wrapper.off('.gallery'); } }; var logError = function( message ) { if ( this.console ) { console.error( message ); } }; $.fn.gallery = function( options ) { if ( typeof options === 'string' ) { var args = Array.prototype.slice.call( arguments, 1 ); this.each(function() { var instance = $.data( this, 'gallery' ); if ( !instance ) { logError( "cannot call methods on gallery prior to initialization; " + "attempted to call method '" + options + "'" ); return; } if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) { logError( "no such method '" + options + "' for gallery instance" ); return; } instance[ options ].apply( instance, args ); }); } else { this.each(function() { var instance = $.data( this, 'gallery' ); if ( !instance ) { $.data( this, 'gallery', new $.Gallery( options, this ) ); } }); } return this; }; })( jQuery );
JavaScript
/* * jQuery UI 1.7.1 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI */ ;jQuery.ui || (function($) { var _remove = $.fn.remove, isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9); //Helper functions and ui object $.ui = { version: "1.7.1", // $.ui.plugin is deprecated. Use the proxy pattern instead. plugin: { add: function(module, option, set) { var proto = $.ui[module].prototype; for(var i in set) { proto.plugins[i] = proto.plugins[i] || []; proto.plugins[i].push([option, set[i]]); } }, call: function(instance, name, args) { var set = instance.plugins[name]; if(!set || !instance.element[0].parentNode) { return; } for (var i = 0; i < set.length; i++) { if (instance.options[set[i][0]]) { set[i][1].apply(instance.element, args); } } } }, contains: function(a, b) { return document.compareDocumentPosition ? a.compareDocumentPosition(b) & 16 : a !== b && a.contains(b); }, hasScroll: function(el, a) { //If overflow is hidden, the element might have extra content, but the user wants to hide it if ($(el).css('overflow') == 'hidden') { return false; } var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop', has = false; if (el[scroll] > 0) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[scroll] = 1; has = (el[scroll] > 0); el[scroll] = 0; return has; }, isOverAxis: function(x, reference, size) { //Determines when x coordinate is over "b" element axis return (x > reference) && (x < (reference + size)); }, isOver: function(y, x, top, left, height, width) { //Determines when x, y coordinates is over "b" element return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width); }, keyCode: { BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38 } }; // WAI-ARIA normalization if (isFF2) { var attr = $.attr, removeAttr = $.fn.removeAttr, ariaNS = "http://www.w3.org/2005/07/aaa", ariaState = /^aria-/, ariaRole = /^wairole:/; $.attr = function(elem, name, value) { var set = value !== undefined; return (name == 'role' ? (set ? attr.call(this, elem, name, "wairole:" + value) : (attr.apply(this, arguments) || "").replace(ariaRole, "")) : (ariaState.test(name) ? (set ? elem.setAttributeNS(ariaNS, name.replace(ariaState, "aaa:"), value) : attr.call(this, elem, name.replace(ariaState, "aaa:"))) : attr.apply(this, arguments))); }; $.fn.removeAttr = function(name) { return (ariaState.test(name) ? this.each(function() { this.removeAttributeNS(ariaNS, name.replace(ariaState, "")); }) : removeAttr.call(this, name)); }; } //jQuery plugins $.fn.extend({ remove: function() { // Safari has a native remove event which actually removes DOM elements, // so we have to use triggerHandler instead of trigger (#3037). $("*", this).add(this).each(function() { $(this).triggerHandler("remove"); }); return _remove.apply(this, arguments ); }, enableSelection: function() { return this .attr('unselectable', 'off') .css('MozUserSelect', '') .unbind('selectstart.ui'); }, disableSelection: function() { return this .attr('unselectable', 'on') .css('MozUserSelect', 'none') .bind('selectstart.ui', function() { return false; }); }, scrollParent: function() { var scrollParent; if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); }).eq(0); } return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent; } }); //Additional selectors $.extend($.expr[':'], { data: function(elem, i, match) { return !!$.data(elem, match[3]); }, focusable: function(element) { var nodeName = element.nodeName.toLowerCase(), tabIndex = $.attr(element, 'tabindex'); return (/input|select|textarea|button|object/.test(nodeName) ? !element.disabled : 'a' == nodeName || 'area' == nodeName ? element.href || !isNaN(tabIndex) : !isNaN(tabIndex)) // the element and all of its ancestors must be visible // the browser may report that the area is hidden && !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length; }, tabbable: function(element) { var tabIndex = $.attr(element, 'tabindex'); return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable'); } }); // $.widget is a factory to create jQuery plugins // taking some boilerplate code out of the plugin code function getter(namespace, plugin, method, args) { function getMethods(type) { var methods = $[namespace][plugin][type] || []; return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods); } var methods = getMethods('getter'); if (args.length == 1 && typeof args[0] == 'string') { methods = methods.concat(getMethods('getterSetter')); } return ($.inArray(method, methods) != -1); } $.widget = function(name, prototype) { var namespace = name.split(".")[0]; name = name.split(".")[1]; // create plugin method $.fn[name] = function(options) { var isMethodCall = (typeof options == 'string'), args = Array.prototype.slice.call(arguments, 1); // prevent calls to internal methods if (isMethodCall && options.substring(0, 1) == '_') { return this; } // handle getter methods if (isMethodCall && getter(namespace, name, options, args)) { var instance = $.data(this[0], name); return (instance ? instance[options].apply(instance, args) : undefined); } // handle initialization and non-getter methods return this.each(function() { var instance = $.data(this, name); // constructor (!instance && !isMethodCall && $.data(this, name, new $[namespace][name](this, options))._init()); // method call (instance && isMethodCall && $.isFunction(instance[options]) && instance[options].apply(instance, args)); }); }; // create widget constructor $[namespace] = $[namespace] || {}; $[namespace][name] = function(element, options) { var self = this; this.namespace = namespace; this.widgetName = name; this.widgetEventPrefix = $[namespace][name].eventPrefix || name; this.widgetBaseClass = namespace + '-' + name; this.options = $.extend({}, $.widget.defaults, $[namespace][name].defaults, $.metadata && $.metadata.get(element)[name], options); this.element = $(element) .bind('setData.' + name, function(event, key, value) { if (event.target == element) { return self._setData(key, value); } }) .bind('getData.' + name, function(event, key) { if (event.target == element) { return self._getData(key); } }) .bind('remove', function() { return self.destroy(); }); }; // add widget prototype $[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype); // TODO: merge getter and getterSetter properties from widget prototype // and plugin prototype $[namespace][name].getterSetter = 'option'; }; $.widget.prototype = { _init: function() {}, destroy: function() { this.element.removeData(this.widgetName) .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .removeAttr('aria-disabled'); }, option: function(key, value) { var options = key, self = this; if (typeof key == "string") { if (value === undefined) { return this._getData(key); } options = {}; options[key] = value; } $.each(options, function(key, value) { self._setData(key, value); }); }, _getData: function(key) { return this.options[key]; }, _setData: function(key, value) { this.options[key] = value; if (key == 'disabled') { this.element [value ? 'addClass' : 'removeClass']( this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .attr("aria-disabled", value); } }, enable: function() { this._setData('disabled', false); }, disable: function() { this._setData('disabled', true); }, _trigger: function(type, event, data) { var callback = this.options[type], eventName = (type == this.widgetEventPrefix ? type : this.widgetEventPrefix + type); event = $.Event(event); event.type = eventName; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if (event.originalEvent) { for (var i = $.event.props.length, prop; i;) { prop = $.event.props[--i]; event[prop] = event.originalEvent[prop]; } } this.element.trigger(event, data); return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false || event.isDefaultPrevented()); } }; $.widget.defaults = { disabled: false }; /** Mouse Interaction Plugin **/ $.ui.mouse = { _mouseInit: function() { var self = this; this.element .bind('mousedown.'+this.widgetName, function(event) { return self._mouseDown(event); }) .bind('click.'+this.widgetName, function(event) { if(self._preventClickEvent) { self._preventClickEvent = false; event.stopImmediatePropagation(); return false; } }); // Prevent text selection in IE if ($.browser.msie) { this._mouseUnselectable = this.element.attr('unselectable'); this.element.attr('unselectable', 'on'); } this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind('.'+this.widgetName); // Restore text selection in IE ($.browser.msie && this.element.attr('unselectable', this._mouseUnselectable)); }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart // TODO: figure out why we have to use originalEvent event.originalEvent = event.originalEvent || {}; if (event.originalEvent.mouseHandled) { return; } // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var self = this, btnIsLeft = (event.which == 1), elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { self.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return self._mouseMove(event); }; this._mouseUpDelegate = function(event) { return self._mouseUp(event); }; $(document) .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .bind('mouseup.'+this.widgetName, this._mouseUpDelegate); // preventDefault() is used to prevent the selection of text here - // however, in Safari, this causes select boxes not to be selectable // anymore, so this fix is needed ($.browser.safari || event.preventDefault()); event.originalEvent.mouseHandled = true; return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.browser.msie && !event.button) { return this._mouseUp(event); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { $(document) .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); if (this._mouseStarted) { this._mouseStarted = false; this._preventClickEvent = (event.target == this._mouseDownEvent.target); this._mouseStop(event); } return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(event) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(event) {}, _mouseDrag: function(event) {}, _mouseStop: function(event) {}, _mouseCapture: function(event) { return true; } }; $.ui.mouse.defaults = { cancel: null, distance: 1, delay: 0 }; })(jQuery);
JavaScript
/* * Style File - jQuery plugin for styling file input elements * * Copyright (c) 2007-2008 Mika Tuupola * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Based on work by Shaun Inman * http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom * * Revision: $Id: jquery.filestyle.js 303 2008-01-30 13:53:24Z tuupola $ * */ (function($) { $.fn.filestyle = function(options) { /* TODO: This should not override CSS. */ var settings = { width : 250 }; if(options) { $.extend(settings, options); }; return this.each(function() { var self = this; var wrapper = $("<div>") .css({ "width": settings.imagewidth + "px", "height": settings.imageheight + "px", "background": "url(" + settings.image + ") 0 0 no-repeat", "background-position": "right", "display": "inline", "position": "absolute", "overflow": "hidden" }); var filename = $('<input class="file">') .addClass($(self).attr("class")) .css({ "display": "inline", "width": settings.width + "px" }); $(self).before(filename); $(self).wrap(wrapper); $(self).css({ "position": "relative", "height": settings.imageheight + "px", "width": settings.width + "px", "display": "inline", "cursor": "pointer", "opacity": "0.0" }); if ($.browser.mozilla) { if (/Win/.test(navigator.platform)) { $(self).css("margin-left", "-142px"); } else { $(self).css("margin-left", "-168px"); }; } else { $(self).css("margin-left", settings.imagewidth - settings.width + "px"); }; $(self).bind("change", function() { filename.val($(self).val()); }); }); }; })(jQuery);
JavaScript
/** * @author trixta */ (function($){ $.bind = function(object, method){ var args = Array.prototype.slice.call(arguments, 2); if(args.length){ return function() { var args2 = [this].concat(args, $.makeArray( arguments )); return method.apply(object, args2); }; } else { return function() { var args2 = [this].concat($.makeArray( arguments )); return method.apply(object, args2); }; } }; })(jQuery);
JavaScript
/** * Copyright (c) 2008 Kelvin Luck (http://www.kelvinluck.com/) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * . * $Id: jquery.datePicker.js 94 2010-01-25 02:25:27Z kelvin.luck $ **/ (function($){ $.fn.extend({ /** * Render a calendar table into any matched elements. * * @param Object s (optional) Customize your calendars. * @option Number month The month to render (NOTE that months are zero based). Default is today's month. * @option Number year The year to render. Default is today's year. * @option Function renderCallback A reference to a function that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Default is no callback. * @option Number showHeader Whether or not to show the header row, possible values are: $.dpConst.SHOW_HEADER_NONE (no header), $.dpConst.SHOW_HEADER_SHORT (first letter of each day) and $.dpConst.SHOW_HEADER_LONG (full name of each day). Default is $.dpConst.SHOW_HEADER_SHORT. * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class. * @type jQuery * @name renderCalendar * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * * @example $('#calendar-me').renderCalendar({month:0, year:2007}); * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me. * * @example * var testCallback = function($td, thisDate, month, year) * { * if ($td.is('.current-month') && thisDate.getDay() == 4) { * var d = thisDate.getDate(); * $td.bind( * 'click', * function() * { * alert('You clicked on ' + d + '/' + (Number(month)+1) + '/' + year); * } * ).addClass('thursday'); * } else if (thisDate.getDay() == 5) { * $td.html('Friday the ' + $td.html() + 'th'); * } * } * $('#calendar-me').renderCalendar({month:0, year:2007, renderCallback:testCallback}); * * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me. Every Thursday in the current month has a class of "thursday" applied to it, is clickable and shows an alert when clicked. Every Friday on the calendar has the number inside replaced with text. **/ renderCalendar : function(s) { var dc = function(a) { return document.createElement(a); }; s = $.extend({}, $.fn.datePicker.defaults, s); if (s.showHeader != $.dpConst.SHOW_HEADER_NONE) { var headRow = $(dc('tr')); for (var i=Date.firstDayOfWeek; i<Date.firstDayOfWeek+7; i++) { var weekday = i%7; var day = Date.dayNames[weekday]; headRow.append( jQuery(dc('th')).attr({'scope':'col', 'abbr':day, 'title':day, 'class':(weekday == 0 || weekday == 6 ? 'weekend' : 'weekday')}).html(s.showHeader == $.dpConst.SHOW_HEADER_SHORT ? day.substr(0, 1) : day) ); } }; var calendarTable = $(dc('table')) .attr( { 'cellspacing':2 } ) .addClass('jCalendar') .append( (s.showHeader != $.dpConst.SHOW_HEADER_NONE ? $(dc('thead')) .append(headRow) : dc('thead') ) ); var tbody = $(dc('tbody')); var today = (new Date()).zeroTime(); today.setHours(12); var month = s.month == undefined ? today.getMonth() : s.month; var year = s.year || today.getFullYear(); var currentDate = (new Date(year, month, 1, 12, 0, 0)); var firstDayOffset = Date.firstDayOfWeek - currentDate.getDay() + 1; if (firstDayOffset > 1) firstDayOffset -= 7; var weeksToDraw = Math.ceil(( (-1*firstDayOffset+1) + currentDate.getDaysInMonth() ) /7); currentDate.addDays(firstDayOffset-1); var doHover = function(firstDayInBounds) { return function() { if (s.hoverClass) { var $this = $(this); if (!s.selectWeek) { $this.addClass(s.hoverClass); } else if (firstDayInBounds && !$this.is('.disabled')) { $this.parent().addClass('activeWeekHover'); } } } }; var unHover = function() { if (s.hoverClass) { var $this = $(this); $this.removeClass(s.hoverClass); $this.parent().removeClass('activeWeekHover'); } }; var w = 0; while (w++<weeksToDraw) { var r = jQuery(dc('tr')); var firstDayInBounds = s.dpController ? currentDate > s.dpController.startDate : false; for (var i=0; i<7; i++) { var thisMonth = currentDate.getMonth() == month; var d = $(dc('td')) .text(currentDate.getDate() + '') .addClass((thisMonth ? 'current-month ' : 'other-month ') + (currentDate.isWeekend() ? 'weekend ' : 'weekday ') + (thisMonth && currentDate.getTime() == today.getTime() ? 'today ' : '') ) .data('datePickerDate', currentDate.asString()) .hover(doHover(firstDayInBounds), unHover) ; r.append(d); if (s.renderCallback) { s.renderCallback(d, currentDate, month, year); } // addDays(1) fails in some locales due to daylight savings. See issue 39. //currentDate.addDays(1); // set the time to midday to avoid any weird timezone issues?? currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()+1, 12, 0, 0); } tbody.append(r); } calendarTable.append(tbody); return this.each( function() { $(this).empty().append(calendarTable); } ); }, /** * Create a datePicker associated with each of the matched elements. * * The matched element will receive a few custom events with the following signatures: * * dateSelected(event, date, $td, status) * Triggered when a date is selected. event is a reference to the event, date is the Date selected, $td is a jquery object wrapped around the TD that was clicked on and status is whether the date was selected (true) or deselected (false) * * dpClosed(event, selected) * Triggered when the date picker is closed. event is a reference to the event and selected is an Array containing Date objects. * * dpMonthChanged(event, displayedMonth, displayedYear) * Triggered when the month of the popped up calendar is changed. event is a reference to the event, displayedMonth is the number of the month now displayed (zero based) and displayedYear is the year of the month. * * dpDisplayed(event, $datePickerDiv) * Triggered when the date picker is created. $datePickerDiv is the div containing the date picker. Use this event to add custom content/ listeners to the popped up date picker. * * @param Object s (optional) Customize your date pickers. * @option Number month The month to render when the date picker is opened (NOTE that months are zero based). Default is today's month. * @option Number year The year to render when the date picker is opened. Default is today's year. * @option String startDate The first date date can be selected. * @option String endDate The last date that can be selected. * @option Boolean inline Whether to create the datePicker as inline (e.g. always on the page) or as a model popup. Default is false (== modal popup) * @option Boolean createButton Whether to create a .dp-choose-date anchor directly after the matched element which when clicked will trigger the showing of the date picker. Default is true. * @option Boolean showYearNavigation Whether to display buttons which allow the user to navigate through the months a year at a time. Default is true. * @option Boolean closeOnSelect Whether to close the date picker when a date is selected. Default is true. * @option Boolean displayClose Whether to create a "Close" button within the date picker popup. Default is false. * @option Boolean selectMultiple Whether a user should be able to select multiple dates with this date picker. Default is false. * @option Number numSelectable The maximum number of dates that can be selected where selectMultiple is true. Default is a very high number. * @option Boolean clickInput If the matched element is an input type="text" and this option is true then clicking on the input will cause the date picker to appear. * @option Boolean rememberViewedMonth Whether the datePicker should remember the last viewed month and open on it. If false then the date picker will always open with the month for the first selected date visible. * @option Boolean selectWeek Whether to select a complete week at a time... * @option Number verticalPosition The vertical alignment of the popped up date picker to the matched element. One of $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM. Default is $.dpConst.POS_TOP. * @option Number horizontalPosition The horizontal alignment of the popped up date picker to the matched element. One of $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT. * @option Number verticalOffset The number of pixels offset from the defined verticalPosition of this date picker that it should pop up in. Default in 0. * @option Number horizontalOffset The number of pixels offset from the defined horizontalPosition of this date picker that it should pop up in. Default in 0. * @option (Function|Array) renderCallback A reference to a function (or an array of seperate functions) that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Each callback function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year. Default is no callback. * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class. * @type jQuery * @name datePicker * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * * @example $('input.date-picker').datePicker(); * @desc Creates a date picker button next to all matched input elements. When the button is clicked on the value of the selected date will be placed in the corresponding input (formatted according to Date.format). * * @example demo/index.html * @desc See the projects homepage for many more complex examples... **/ datePicker : function(s) { if (!$.event._dpCache) $.event._dpCache = []; // initialise the date picker controller with the relevant settings... s = $.extend({}, $.fn.datePicker.defaults, s); return this.each( function() { var $this = $(this); var alreadyExists = true; if (!this._dpId) { this._dpId = $.event.guid++; $.event._dpCache[this._dpId] = new DatePicker(this); alreadyExists = false; } if (s.inline) { s.createButton = false; s.displayClose = false; s.closeOnSelect = false; $this.empty(); } var controller = $.event._dpCache[this._dpId]; controller.init(s); if (!alreadyExists && s.createButton) { // create it! controller.button = $('<a href="#" class="dp-choose-date" title="' + $.dpText.TEXT_CHOOSE_DATE + '">' + $.dpText.TEXT_CHOOSE_DATE + '</a>') .bind( 'click', function() { $this.dpDisplay(this); this.blur(); return false; } ); $this.after(controller.button); } if (!alreadyExists && $this.is(':text')) { $this .bind( 'dateSelected', function(e, selectedDate, $td) { this.value = selectedDate.asString(); } ).bind( 'change', function() { if (this.value == '') { controller.clearSelected(); } else { var d = Date.fromString(this.value); if (d) { controller.setSelected(d, true, true); } } } ); if (s.clickInput) { $this.bind( 'click', function() { // The change event doesn't happen until the input loses focus so we need to manually trigger it... $this.trigger('change'); $this.dpDisplay(); } ); } var d = Date.fromString(this.value); if (this.value != '' && d) { controller.setSelected(d, true, true); } } $this.addClass('dp-applied'); } ) }, /** * Disables or enables this date picker * * @param Boolean s Whether to disable (true) or enable (false) this datePicker * @type jQuery * @name dpSetDisabled * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * * @example $('.date-picker').datePicker(); * $('.date-picker').dpSetDisabled(true); * @desc Prevents this date picker from displaying and adds a class of dp-disabled to it (and it's associated button if it has one) for styling purposes. If the matched element is an input field then it will also set the disabled attribute to stop people directly editing the field. **/ dpSetDisabled : function(s) { return _w.call(this, 'setDisabled', s); }, /** * Updates the first selectable date for any date pickers on any matched elements. * * @param String d A string representing the first selectable date (formatted according to Date.format). * @type jQuery * @name dpSetStartDate * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * * @example $('.date-picker').datePicker(); * $('.date-picker').dpSetStartDate('01/01/2000'); * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the first selectable date for each of these to the first day of the millenium. **/ dpSetStartDate : function(d) { return _w.call(this, 'setStartDate', d); }, /** * Updates the last selectable date for any date pickers on any matched elements. * * @param String d A string representing the last selectable date (formatted according to Date.format). * @type jQuery * @name dpSetEndDate * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * * @example $('.date-picker').datePicker(); * $('.date-picker').dpSetEndDate('01/01/2010'); * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the last selectable date for each of these to the first Janurary 2010. **/ dpSetEndDate : function(d) { return _w.call(this, 'setEndDate', d); }, /** * Gets a list of Dates currently selected by this datePicker. This will be an empty array if no dates are currently selected or NULL if there is no datePicker associated with the matched element. * * @type Array * @name dpGetSelected * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * * @example $('.date-picker').datePicker(); * alert($('.date-picker').dpGetSelected()); * @desc Will alert an empty array (as nothing is selected yet) **/ dpGetSelected : function() { var c = _getController(this[0]); if (c) { return c.getSelected(); } return null; }, /** * Selects or deselects a date on any matched element's date pickers. Deselcting is only useful on date pickers where selectMultiple==true. Selecting will only work if the passed date is within the startDate and endDate boundries for a given date picker. * * @param String d A string representing the date you want to select (formatted according to Date.format). * @param Boolean v Whether you want to select (true) or deselect (false) this date. Optional - default = true. * @param Boolean m Whether you want the date picker to open up on the month of this date when it is next opened. Optional - default = true. * @param Boolean e Whether you want the date picker to dispatch events related to this change of selection. Optional - default = true. * @type jQuery * @name dpSetSelected * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * * @example $('.date-picker').datePicker(); * $('.date-picker').dpSetSelected('01/01/2010'); * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010. **/ dpSetSelected : function(d, v, m, e) { if (v == undefined) v=true; if (m == undefined) m=true; if (e == undefined) e=true; return _w.call(this, 'setSelected', Date.fromString(d), v, m, e); }, /** * Sets the month that will be displayed when the date picker is next opened. If the passed month is before startDate then the month containing startDate will be displayed instead. If the passed month is after endDate then the month containing the endDate will be displayed instead. * * @param Number m The month you want the date picker to display. Optional - defaults to the currently displayed month. * @param Number y The year you want the date picker to display. Optional - defaults to the currently displayed year. * @type jQuery * @name dpSetDisplayedMonth * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * * @example $('.date-picker').datePicker(); * $('.date-picker').dpSetDisplayedMonth(10, 2008); * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010. **/ dpSetDisplayedMonth : function(m, y) { return _w.call(this, 'setDisplayedMonth', Number(m), Number(y), true); }, /** * Displays the date picker associated with the matched elements. Since only one date picker can be displayed at once then the date picker associated with the last matched element will be the one that is displayed. * * @param HTMLElement e An element that you want the date picker to pop up relative in position to. Optional - default behaviour is to pop up next to the element associated with this date picker. * @type jQuery * @name dpDisplay * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * * @example $('#date-picker').datePicker(); * $('#date-picker').dpDisplay(); * @desc Creates a date picker associated with the element with an id of date-picker and then causes it to pop up. **/ dpDisplay : function(e) { return _w.call(this, 'display', e); }, /** * Sets a function or array of functions that is called when each TD of the date picker popup is rendered to the page * * @param (Function|Array) a A function or an array of functions that are called when each td is rendered. Each function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year. * @type jQuery * @name dpSetRenderCallback * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * * @example $('#date-picker').datePicker(); * $('#date-picker').dpSetRenderCallback(function($td, thisDate, month, year) * { * // do stuff as each td is rendered dependant on the date in the td and the displayed month and year * }); * @desc Creates a date picker associated with the element with an id of date-picker and then creates a function which is called as each td is rendered when this date picker is displayed. **/ dpSetRenderCallback : function(a) { return _w.call(this, 'setRenderCallback', a); }, /** * Sets the position that the datePicker will pop up (relative to it's associated element) * * @param Number v The vertical alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM * @param Number h The horizontal alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT * @type jQuery * @name dpSetPosition * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * * @example $('#date-picker').datePicker(); * $('#date-picker').dpSetPosition($.dpConst.POS_BOTTOM, $.dpConst.POS_RIGHT); * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be bottom and right aligned to the #date-picker element. **/ dpSetPosition : function(v, h) { return _w.call(this, 'setPosition', v, h); }, /** * Sets the offset that the popped up date picker will have from it's default position relative to it's associated element (as set by dpSetPosition) * * @param Number v The vertical offset of the created date picker. * @param Number h The horizontal offset of the created date picker. * @type jQuery * @name dpSetOffset * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * * @example $('#date-picker').datePicker(); * $('#date-picker').dpSetOffset(-20, 200); * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be 20 pixels above and 200 pixels to the right of it's default position. **/ dpSetOffset : function(v, h) { return _w.call(this, 'setOffset', v, h); }, /** * Closes the open date picker associated with this element. * * @type jQuery * @name dpClose * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * * @example $('.date-pick') * .datePicker() * .bind( * 'focus', * function() * { * $(this).dpDisplay(); * } * ).bind( * 'blur', * function() * { * $(this).dpClose(); * } * ); **/ dpClose : function() { return _w.call(this, '_closeCalendar', false, this[0]); }, /** * Rerenders the date picker's current month (for use with inline calendars and renderCallbacks). * * @type jQuery * @name dpRerenderCalendar * @cat plugins/datePicker * @author Kelvin Luck (http://www.kelvinluck.com/) * **/ dpRerenderCalendar : function() { return _w.call(this, '_rerenderCalendar'); }, // private function called on unload to clean up any expandos etc and prevent memory links... _dpDestroy : function() { // TODO - implement this? } }); // private internal function to cut down on the amount of code needed where we forward // dp* methods on the jQuery object on to the relevant DatePicker controllers... var _w = function(f, a1, a2, a3, a4) { return this.each( function() { var c = _getController(this); if (c) { c[f](a1, a2, a3, a4); } } ); }; function DatePicker(ele) { this.ele = ele; // initial values... this.displayedMonth = null; this.displayedYear = null; this.startDate = null; this.endDate = null; this.showYearNavigation = null; this.closeOnSelect = null; this.displayClose = null; this.rememberViewedMonth= null; this.selectMultiple = null; this.numSelectable = null; this.numSelected = null; this.verticalPosition = null; this.horizontalPosition = null; this.verticalOffset = null; this.horizontalOffset = null; this.button = null; this.renderCallback = []; this.selectedDates = {}; this.inline = null; this.context = '#dp-popup'; this.settings = {}; }; $.extend( DatePicker.prototype, { init : function(s) { this.setStartDate(s.startDate); this.setEndDate(s.endDate); this.setDisplayedMonth(Number(s.month), Number(s.year)); this.setRenderCallback(s.renderCallback); this.showYearNavigation = s.showYearNavigation; this.closeOnSelect = s.closeOnSelect; this.displayClose = s.displayClose; this.rememberViewedMonth = s.rememberViewedMonth; this.selectMultiple = s.selectMultiple; this.numSelectable = s.selectMultiple ? s.numSelectable : 1; this.numSelected = 0; this.verticalPosition = s.verticalPosition; this.horizontalPosition = s.horizontalPosition; this.hoverClass = s.hoverClass; this.setOffset(s.verticalOffset, s.horizontalOffset); this.inline = s.inline; this.settings = s; if (this.inline) { this.context = this.ele; this.display(); } }, setStartDate : function(d) { if (d) { this.startDate = Date.fromString(d); } if (!this.startDate) { this.startDate = (new Date()).zeroTime(); } this.setDisplayedMonth(this.displayedMonth, this.displayedYear); }, setEndDate : function(d) { if (d) { this.endDate = Date.fromString(d); } if (!this.endDate) { this.endDate = (new Date('12/31/2999')); // using the JS Date.parse function which expects mm/dd/yyyy } if (this.endDate.getTime() < this.startDate.getTime()) { this.endDate = this.startDate; } this.setDisplayedMonth(this.displayedMonth, this.displayedYear); }, setPosition : function(v, h) { this.verticalPosition = v; this.horizontalPosition = h; }, setOffset : function(v, h) { this.verticalOffset = parseInt(v) || -10; this.horizontalOffset = parseInt(h) || 30; }, setDisabled : function(s) { $e = $(this.ele); $e[s ? 'addClass' : 'removeClass']('dp-disabled'); if (this.button) { $but = $(this.button); $but[s ? 'addClass' : 'removeClass']('dp-disabled'); $but.attr('title', s ? '' : $.dpText.TEXT_CHOOSE_DATE); } if ($e.is(':text')) { $e.attr('disabled', s ? 'disabled' : ''); } }, setDisplayedMonth : function(m, y, rerender) { if (this.startDate == undefined || this.endDate == undefined) { return; } var s = new Date(this.startDate.getTime()); s.setDate(1); var e = new Date(this.endDate.getTime()); e.setDate(1); var t; if ((!m && !y) || (isNaN(m) && isNaN(y))) { // no month or year passed - default to current month t = new Date().zeroTime(); t.setDate(1); } else if (isNaN(m)) { // just year passed in - presume we want the displayedMonth t = new Date(y, this.displayedMonth, 1); } else if (isNaN(y)) { // just month passed in - presume we want the displayedYear t = new Date(this.displayedYear, m, 1); } else { // year and month passed in - that's the date we want! t = new Date(y, m, 1) } // check if the desired date is within the range of our defined startDate and endDate if (t.getTime() < s.getTime()) { t = s; } else if (t.getTime() > e.getTime()) { t = e; } var oldMonth = this.displayedMonth; var oldYear = this.displayedYear; this.displayedMonth = t.getMonth(); this.displayedYear = t.getFullYear(); if (rerender && (this.displayedMonth != oldMonth || this.displayedYear != oldYear)) { this._rerenderCalendar(); $(this.ele).trigger('dpMonthChanged', [this.displayedMonth, this.displayedYear]); } }, setSelected : function(d, v, moveToMonth, dispatchEvents) { if (d < this.startDate || d > this.endDate) { // Don't allow people to select dates outside range... return; } var s = this.settings; if (s.selectWeek) { d = d.addDays(- (d.getDay() - Date.firstDayOfWeek + 7) % 7); if (d < this.startDate) // The first day of this week is before the start date so is unselectable... { return; } } if (v == this.isSelected(d)) // this date is already un/selected { return; } if (this.selectMultiple == false) { this.clearSelected(); } else if (v && this.numSelected == this.numSelectable) { // can't select any more dates... return; } if (moveToMonth && (this.displayedMonth != d.getMonth() || this.displayedYear != d.getFullYear())) { this.setDisplayedMonth(d.getMonth(), d.getFullYear(), true); } this.selectedDates[d.asString()] = v; this.numSelected += v ? 1 : -1; var selectorString = 'td.' + (d.getMonth() == this.displayedMonth ? 'current-month' : 'other-month'); var $td; $(selectorString, this.context).each( function() { if ($(this).data('datePickerDate') == d.asString()) { $td = $(this); if (s.selectWeek) { $td.parent()[v ? 'addClass' : 'removeClass']('selectedWeek'); } $td[v ? 'addClass' : 'removeClass']('selected'); } } ); $('td', this.context).not('.selected')[this.selectMultiple && this.numSelected == this.numSelectable ? 'addClass' : 'removeClass']('unselectable'); if (dispatchEvents) { var s = this.isSelected(d); $e = $(this.ele); var dClone = Date.fromString(d.asString()); $e.trigger('dateSelected', [dClone, $td, s]); $e.trigger('change'); } }, isSelected : function(d) { return this.selectedDates[d.asString()]; }, getSelected : function() { var r = []; for(s in this.selectedDates) { if (this.selectedDates[s] == true) { r.push(Date.fromString(s)); } } return r; }, clearSelected : function() { this.selectedDates = {}; this.numSelected = 0; $('td.selected', this.context).removeClass('selected').parent().removeClass('selectedWeek'); }, display : function(eleAlignTo) { if ($(this.ele).is('.dp-disabled')) return; eleAlignTo = eleAlignTo || this.ele; var c = this; var $ele = $(eleAlignTo); var eleOffset = $ele.offset(); var $createIn; var attrs; var attrsCalendarHolder; var cssRules; if (c.inline) { $createIn = $(this.ele); attrs = { 'id' : 'calendar-' + this.ele._dpId, 'class' : 'dp-popup dp-popup-inline' }; $('.dp-popup', $createIn).remove(); cssRules = { }; } else { $createIn = $('body'); attrs = { 'id' : 'dp-popup', 'class' : 'dp-popup' }; cssRules = { 'top' : eleOffset.top + c.verticalOffset, 'left' : eleOffset.left + c.horizontalOffset }; var _checkMouse = function(e) { var el = e.target; var cal = $('#dp-popup')[0]; while (true){ if (el == cal) { return true; } else if (el == document) { c._closeCalendar(); return false; } else { el = $(el).parent()[0]; } } }; this._checkMouse = _checkMouse; c._closeCalendar(true); $(document).bind( 'keydown.datepicker', function(event) { if (event.keyCode == 27) { c._closeCalendar(); } } ); } if (!c.rememberViewedMonth) { var selectedDate = this.getSelected()[0]; if (selectedDate) { selectedDate = new Date(selectedDate); this.setDisplayedMonth(selectedDate.getMonth(), selectedDate.getFullYear(), false); } } $createIn .append( $('<div></div>') .attr(attrs) .css(cssRules) .append( // $('<a href="#" class="selecteee">aaa</a>'), $('<h2></h2>'), $('<div class="dp-nav-prev"></div>') .append( $('<a class="dp-nav-prev-year" href="#" title="' + $.dpText.TEXT_PREV_YEAR + '">&lt;&lt;</a>') .bind( 'click', function() { return c._displayNewMonth.call(c, this, 0, -1); } ), $('<a class="dp-nav-prev-month" href="#" title="' + $.dpText.TEXT_PREV_MONTH + '">&lt;</a>') .bind( 'click', function() { return c._displayNewMonth.call(c, this, -1, 0); } ) ), $('<div class="dp-nav-next"></div>') .append( $('<a class="dp-nav-next-year" href="#" title="' + $.dpText.TEXT_NEXT_YEAR + '">&gt;&gt;</a>') .bind( 'click', function() { return c._displayNewMonth.call(c, this, 0, 1); } ), $('<a class="dp-nav-next-month" href="#" title="' + $.dpText.TEXT_NEXT_MONTH + '">&gt;</a>') .bind( 'click', function() { return c._displayNewMonth.call(c, this, 1, 0); } ) ), $('<div class="dp-calendar"></div>') ) .bgIframe() ); var $pop = this.inline ? $('.dp-popup', this.context) : $('#dp-popup'); if (this.showYearNavigation == false) { $('.dp-nav-prev-year, .dp-nav-next-year', c.context).css('display', 'none'); } if (this.displayClose) { $pop.append( $('<a href="#" id="dp-close">' + $.dpText.TEXT_CLOSE + '</a>') .bind( 'click', function() { c._closeCalendar(); return false; } ) ); } c._renderCalendar(); $(this.ele).trigger('dpDisplayed', $pop); if (!c.inline) { if (this.verticalPosition == $.dpConst.POS_BOTTOM) { $pop.css('top', eleOffset.top + $ele.height() - $pop.height() + c.verticalOffset); } if (this.horizontalPosition == $.dpConst.POS_RIGHT) { $pop.css('left', eleOffset.left + $ele.width() - $pop.width() + c.horizontalOffset); } // $('.selectee', this.context).focus(); $(document).bind('mousedown.datepicker', this._checkMouse); } }, setRenderCallback : function(a) { if (a == null) return; if (a && typeof(a) == 'function') { a = [a]; } this.renderCallback = this.renderCallback.concat(a); }, cellRender : function ($td, thisDate, month, year) { var c = this.dpController; var d = new Date(thisDate.getTime()); // add our click handlers to deal with it when the days are clicked... $td.bind( 'click', function() { var $this = $(this); if (!$this.is('.disabled')) { c.setSelected(d, !$this.is('.selected') || !c.selectMultiple, false, true); if (c.closeOnSelect) { c._closeCalendar(); } // TODO: Instead of this which doesn't work in IE anyway we should find the next focusable element in the document // and pass the focus onto that. That would allow the user to continue on the form as expected... if (!$.browser.msie) { $(c.ele).trigger('focus', [$.dpConst.DP_INTERNAL_FOCUS]); } } } ); if (c.isSelected(d)) { $td.addClass('selected'); if (c.settings.selectWeek) { $td.parent().addClass('selectedWeek'); } } else if (c.selectMultiple && c.numSelected == c.numSelectable) { $td.addClass('unselectable'); } }, _applyRenderCallbacks : function() { var c = this; $('td', this.context).each( function() { for (var i=0; i<c.renderCallback.length; i++) { $td = $(this); c.renderCallback[i].apply(this, [$td, Date.fromString($td.data('datePickerDate')), c.displayedMonth, c.displayedYear]); } } ); return; }, // ele is the clicked button - only proceed if it doesn't have the class disabled... // m and y are -1, 0 or 1 depending which direction we want to go in... _displayNewMonth : function(ele, m, y) { if (!$(ele).is('.disabled')) { this.setDisplayedMonth(this.displayedMonth + m, this.displayedYear + y, true); } ele.blur(); return false; }, _rerenderCalendar : function() { this._clearCalendar(); this._renderCalendar(); }, _renderCalendar : function() { // set the title... $('h2', this.context).html((new Date(this.displayedYear, this.displayedMonth, 1)).asString($.dpText.HEADER_FORMAT)); // render the calendar... $('.dp-calendar', this.context).renderCalendar( $.extend( {}, this.settings, { month : this.displayedMonth, year : this.displayedYear, renderCallback : this.cellRender, dpController : this, hoverClass : this.hoverClass }) ); // update the status of the control buttons and disable dates before startDate or after endDate... // TODO: When should the year buttons be disabled? When you can't go forward a whole year from where you are or is that annoying? if (this.displayedYear == this.startDate.getFullYear() && this.displayedMonth == this.startDate.getMonth()) { $('.dp-nav-prev-year', this.context).addClass('disabled'); $('.dp-nav-prev-month', this.context).addClass('disabled'); $('.dp-calendar td.other-month', this.context).each( function() { var $this = $(this); if (Number($this.text()) > 20) { $this.addClass('disabled'); } } ); var d = this.startDate.getDate(); $('.dp-calendar td.current-month', this.context).each( function() { var $this = $(this); if (Number($this.text()) < d) { $this.addClass('disabled'); } } ); } else { $('.dp-nav-prev-year', this.context).removeClass('disabled'); $('.dp-nav-prev-month', this.context).removeClass('disabled'); var d = this.startDate.getDate(); if (d > 20) { // check if the startDate is last month as we might need to add some disabled classes... var st = this.startDate.getTime(); var sd = new Date(st); sd.addMonths(1); if (this.displayedYear == sd.getFullYear() && this.displayedMonth == sd.getMonth()) { $('.dp-calendar td.other-month', this.context).each( function() { var $this = $(this); if (Date.fromString($this.data('datePickerDate')).getTime() < st) { $this.addClass('disabled'); } } ); } } } if (this.displayedYear == this.endDate.getFullYear() && this.displayedMonth == this.endDate.getMonth()) { $('.dp-nav-next-year', this.context).addClass('disabled'); $('.dp-nav-next-month', this.context).addClass('disabled'); $('.dp-calendar td.other-month', this.context).each( function() { var $this = $(this); if (Number($this.text()) < 14) { $this.addClass('disabled'); } } ); var d = this.endDate.getDate(); $('.dp-calendar td.current-month', this.context).each( function() { var $this = $(this); if (Number($this.text()) > d) { $this.addClass('disabled'); } } ); } else { $('.dp-nav-next-year', this.context).removeClass('disabled'); $('.dp-nav-next-month', this.context).removeClass('disabled'); var d = this.endDate.getDate(); if (d < 13) { // check if the endDate is next month as we might need to add some disabled classes... var ed = new Date(this.endDate.getTime()); ed.addMonths(-1); if (this.displayedYear == ed.getFullYear() && this.displayedMonth == ed.getMonth()) { $('.dp-calendar td.other-month', this.context).each( function() { var $this = $(this); var cellDay = Number($this.text()); if (cellDay < 13 && cellDay > d) { $this.addClass('disabled'); } } ); } } } this._applyRenderCallbacks(); }, _closeCalendar : function(programatic, ele) { if (!ele || ele == this.ele) { $(document).unbind('mousedown.datepicker'); $(document).unbind('keydown.datepicker'); this._clearCalendar(); $('#dp-popup a').unbind(); $('#dp-popup').empty().remove(); if (!programatic) { $(this.ele).trigger('dpClosed', [this.getSelected()]); } } }, // empties the current dp-calendar div and makes sure that all events are unbound // and expandos removed to avoid memory leaks... _clearCalendar : function() { // TODO. $('.dp-calendar td', this.context).unbind(); $('.dp-calendar', this.context).empty(); } } ); // static constants $.dpConst = { SHOW_HEADER_NONE : 0, SHOW_HEADER_SHORT : 1, SHOW_HEADER_LONG : 2, POS_TOP : 0, POS_BOTTOM : 1, POS_LEFT : 0, POS_RIGHT : 1, DP_INTERNAL_FOCUS : 'dpInternalFocusTrigger' }; // localisable text $.dpText = { TEXT_PREV_YEAR : 'Previous year', TEXT_PREV_MONTH : 'Previous month', TEXT_NEXT_YEAR : 'Next year', TEXT_NEXT_MONTH : 'Next month', TEXT_CLOSE : 'Close', TEXT_CHOOSE_DATE : 'Choose date', HEADER_FORMAT : 'mmmm yyyy' }; // version $.dpVersion = '$Id: jquery.datePicker.js 94 2010-01-25 02:25:27Z kelvin.luck $'; $.fn.datePicker.defaults = { month : undefined, year : undefined, showHeader : $.dpConst.SHOW_HEADER_SHORT, startDate : undefined, endDate : undefined, inline : false, renderCallback : null, createButton : true, showYearNavigation : true, closeOnSelect : true, displayClose : false, selectMultiple : false, numSelectable : Number.MAX_VALUE, clickInput : false, rememberViewedMonth : true, selectWeek : false, verticalPosition : $.dpConst.POS_TOP, horizontalPosition : $.dpConst.POS_LEFT, verticalOffset : 0, horizontalOffset : 0, hoverClass : 'dp-hover' }; function _getController(ele) { if (ele._dpId) return $.event._dpCache[ele._dpId]; return false; }; // make it so that no error is thrown if bgIframe plugin isn't included (allows you to use conditional // comments to only include bgIframe where it is needed in IE without breaking this plugin). if ($.fn.bgIframe == undefined) { $.fn.bgIframe = function() {return this; }; }; // clean-up $(window) .bind('unload', function() { var els = $.event._dpCache || []; for (var i in els) { $(els[i].ele)._dpDestroy(); } }); })(jQuery);
JavaScript
/* * Date prototype extensions. Doesn't depend on any * other code. Doens't overwrite existing methods. * * Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear, * isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear, * setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods * * Copyright (c) 2006 Jörn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net) * * Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString - * I've added my name to these methods so you know who to blame if they are broken! * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * An Array of day names starting with Sunday. * * @example dayNames[0] * @result 'Sunday' * * @name dayNames * @type Array * @cat Plugins/Methods/Date */ Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; /** * An Array of abbreviated day names starting with Sun. * * @example abbrDayNames[0] * @result 'Sun' * * @name abbrDayNames * @type Array * @cat Plugins/Methods/Date */ Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; /** * An Array of month names starting with Janurary. * * @example monthNames[0] * @result 'January' * * @name monthNames * @type Array * @cat Plugins/Methods/Date */ Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; /** * An Array of abbreviated month names starting with Jan. * * @example abbrMonthNames[0] * @result 'Jan' * * @name monthNames * @type Array * @cat Plugins/Methods/Date */ Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; /** * The first day of the week for this locale. * * @name firstDayOfWeek * @type Number * @cat Plugins/Methods/Date * @author Kelvin Luck */ Date.firstDayOfWeek = 1; /** * The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc). * * @name format * @type String * @cat Plugins/Methods/Date * @author Kelvin Luck */ Date.format = 'dd/mm/yyyy'; //Date.format = 'mm/dd/yyyy'; //Date.format = 'yyyy-mm-dd'; //Date.format = 'dd mmm yy'; /** * The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear * only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes. * * @name format * @type String * @cat Plugins/Methods/Date * @author Kelvin Luck */ Date.fullYearStart = '20'; (function() { /** * Adds a given method under the given name * to the Date prototype if it doesn't * currently exist. * * @private */ function add(name, method) { if( !Date.prototype[name] ) { Date.prototype[name] = method; } }; /** * Checks if the year is a leap year. * * @example var dtm = new Date("01/12/2008"); * dtm.isLeapYear(); * @result true * * @name isLeapYear * @type Boolean * @cat Plugins/Methods/Date */ add("isLeapYear", function() { var y = this.getFullYear(); return (y%4==0 && y%100!=0) || y%400==0; }); /** * Checks if the day is a weekend day (Sat or Sun). * * @example var dtm = new Date("01/12/2008"); * dtm.isWeekend(); * @result false * * @name isWeekend * @type Boolean * @cat Plugins/Methods/Date */ add("isWeekend", function() { return this.getDay()==0 || this.getDay()==6; }); /** * Check if the day is a day of the week (Mon-Fri) * * @example var dtm = new Date("01/12/2008"); * dtm.isWeekDay(); * @result false * * @name isWeekDay * @type Boolean * @cat Plugins/Methods/Date */ add("isWeekDay", function() { return !this.isWeekend(); }); /** * Gets the number of days in the month. * * @example var dtm = new Date("01/12/2008"); * dtm.getDaysInMonth(); * @result 31 * * @name getDaysInMonth * @type Number * @cat Plugins/Methods/Date */ add("getDaysInMonth", function() { return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()]; }); /** * Gets the name of the day. * * @example var dtm = new Date("01/12/2008"); * dtm.getDayName(); * @result 'Saturday' * * @example var dtm = new Date("01/12/2008"); * dtm.getDayName(true); * @result 'Sat' * * @param abbreviated Boolean When set to true the name will be abbreviated. * @name getDayName * @type String * @cat Plugins/Methods/Date */ add("getDayName", function(abbreviated) { return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()]; }); /** * Gets the name of the month. * * @example var dtm = new Date("01/12/2008"); * dtm.getMonthName(); * @result 'Janurary' * * @example var dtm = new Date("01/12/2008"); * dtm.getMonthName(true); * @result 'Jan' * * @param abbreviated Boolean When set to true the name will be abbreviated. * @name getDayName * @type String * @cat Plugins/Methods/Date */ add("getMonthName", function(abbreviated) { return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()]; }); /** * Get the number of the day of the year. * * @example var dtm = new Date("01/12/2008"); * dtm.getDayOfYear(); * @result 11 * * @name getDayOfYear * @type Number * @cat Plugins/Methods/Date */ add("getDayOfYear", function() { var tmpdtm = new Date("1/1/" + this.getFullYear()); return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000); }); /** * Get the number of the week of the year. * * @example var dtm = new Date("01/12/2008"); * dtm.getWeekOfYear(); * @result 2 * * @name getWeekOfYear * @type Number * @cat Plugins/Methods/Date */ add("getWeekOfYear", function() { return Math.ceil(this.getDayOfYear() / 7); }); /** * Set the day of the year. * * @example var dtm = new Date("01/12/2008"); * dtm.setDayOfYear(1); * dtm.toString(); * @result 'Tue Jan 01 2008 00:00:00' * * @name setDayOfYear * @type Date * @cat Plugins/Methods/Date */ add("setDayOfYear", function(day) { this.setMonth(0); this.setDate(day); return this; }); /** * Add a number of years to the date object. * * @example var dtm = new Date("01/12/2008"); * dtm.addYears(1); * dtm.toString(); * @result 'Mon Jan 12 2009 00:00:00' * * @name addYears * @type Date * @cat Plugins/Methods/Date */ add("addYears", function(num) { this.setFullYear(this.getFullYear() + num); return this; }); /** * Add a number of months to the date object. * * @example var dtm = new Date("01/12/2008"); * dtm.addMonths(1); * dtm.toString(); * @result 'Tue Feb 12 2008 00:00:00' * * @name addMonths * @type Date * @cat Plugins/Methods/Date */ add("addMonths", function(num) { var tmpdtm = this.getDate(); this.setMonth(this.getMonth() + num); if (tmpdtm > this.getDate()) this.addDays(-this.getDate()); return this; }); /** * Add a number of days to the date object. * * @example var dtm = new Date("01/12/2008"); * dtm.addDays(1); * dtm.toString(); * @result 'Sun Jan 13 2008 00:00:00' * * @name addDays * @type Date * @cat Plugins/Methods/Date */ add("addDays", function(num) { //this.setDate(this.getDate() + num); this.setTime(this.getTime() + (num*86400000) ); return this; }); /** * Add a number of hours to the date object. * * @example var dtm = new Date("01/12/2008"); * dtm.addHours(24); * dtm.toString(); * @result 'Sun Jan 13 2008 00:00:00' * * @name addHours * @type Date * @cat Plugins/Methods/Date */ add("addHours", function(num) { this.setHours(this.getHours() + num); return this; }); /** * Add a number of minutes to the date object. * * @example var dtm = new Date("01/12/2008"); * dtm.addMinutes(60); * dtm.toString(); * @result 'Sat Jan 12 2008 01:00:00' * * @name addMinutes * @type Date * @cat Plugins/Methods/Date */ add("addMinutes", function(num) { this.setMinutes(this.getMinutes() + num); return this; }); /** * Add a number of seconds to the date object. * * @example var dtm = new Date("01/12/2008"); * dtm.addSeconds(60); * dtm.toString(); * @result 'Sat Jan 12 2008 00:01:00' * * @name addSeconds * @type Date * @cat Plugins/Methods/Date */ add("addSeconds", function(num) { this.setSeconds(this.getSeconds() + num); return this; }); /** * Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant. * * @example var dtm = new Date(); * dtm.zeroTime(); * dtm.toString(); * @result 'Sat Jan 12 2008 00:01:00' * * @name zeroTime * @type Date * @cat Plugins/Methods/Date * @author Kelvin Luck */ add("zeroTime", function() { this.setMilliseconds(0); this.setSeconds(0); this.setMinutes(0); this.setHours(0); return this; }); /** * Returns a string representation of the date object according to Date.format. * (Date.toString may be used in other places so I purposefully didn't overwrite it) * * @example var dtm = new Date("01/12/2008"); * dtm.asString(); * @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy' * * @name asString * @type Date * @cat Plugins/Methods/Date * @author Kelvin Luck */ add("asString", function(format) { var r = format || Date.format; if (r.split('mm').length>1) { // ugly workaround to make sure we don't replace the m's in e.g. noveMber r = r.split('mmmm').join(this.getMonthName(false)) .split('mmm').join(this.getMonthName(true)) .split('mm').join(_zeroPad(this.getMonth()+1)) } else { r = r.split('m').join(this.getMonth()+1); } r = r.split('yyyy').join(this.getFullYear()) .split('yy').join((this.getFullYear() + '').substring(2)) .split('dd').join(_zeroPad(this.getDate())) .split('d').join(this.getDate()); return r; }); /** * Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object * (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere) * * @example var dtm = Date.fromString("12/01/2008"); * dtm.toString(); * @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy' * * @name fromString * @type Date * @cat Plugins/Methods/Date * @author Kelvin Luck */ Date.fromString = function(s) { var f = Date.format; var d = new Date('01/01/1970'); if (s == '') return d; s = s.toLowerCase(); var matcher = ''; var order = []; var r = /(dd?d?|mm?m?|yy?yy?)+([^(m|d|y)])?/g; var results; while ((results = r.exec(f)) != null) { switch (results[1]) { case 'd': case 'dd': case 'm': case 'mm': case 'yy': case 'yyyy': matcher += '(\\d+\\d?\\d?\\d?)+'; order.push(results[1].substr(0, 1)); break; case 'mmm': matcher += '([a-z]{3})'; order.push('M'); break; } if (results[2]) { matcher += results[2]; } } var dm = new RegExp(matcher); var result = s.match(dm); for (var i=0; i<order.length; i++) { var res = result[i+1]; switch(order[i]) { case 'd': d.setDate(res); break; case 'm': d.setMonth(Number(res)-1); break; case 'M': for (var j=0; j<Date.abbrMonthNames.length; j++) { if (Date.abbrMonthNames[j].toLowerCase() == res) break; } d.setMonth(j); break; case 'y': d.setYear(res); break; } } return d; }; // utility method var _zeroPad = function(num) { var s = '0'+num; return s.substring(s.length-2) //return ('0'+num).substring(-2); // doesn't work on IE :( }; })();
JavaScript
/** * @author alexander.farkas * @version 1.3 */ (function($){ $.widget('ui.checkBox', { _init: function(){ var that = this, opts = this.options, toggleHover = function(e){ if(this.disabledStatus){ return false; } that.hover = (e.type == 'focus' || e.type == 'mouseenter'); that._changeStateClassChain(); }; if(!this.element.is(':radio,:checkbox')){ return false; } this.labels = $([]); this.checkedStatus = false; this.disabledStatus = false; this.hoverStatus = false; this.radio = (this.element.is(':radio')); this.visualElement = $('<span />') .addClass(this.radio ? 'ui-radio' : 'ui-checkbox') .bind('mouseenter.checkBox mouseleave.checkBox', toggleHover) .bind('click.checkBox', function(e){ that.element[0].click(); //that.element.trigger('click'); return false; }); if (opts.replaceInput) { this.element .addClass('ui-helper-hidden-accessible') .after(this.visualElement[0]) .bind('usermode', function(e){ (e.enabled && that.destroy.call(that, true)); }); } this.element .bind('click.checkBox', $.bind(this, this.reflectUI)) .bind('focus.checkBox blur.checkBox', toggleHover); if(opts.addLabel){ //ToDo: Add Closest Ancestor this.labels = $('label[for=' + this.element.attr('id') + ']') .bind('mouseenter.checkBox mouseleave.checkBox', toggleHover); } this.reflectUI({type: 'initialReflect'}); }, _changeStateClassChain: function(){ var stateClass = (this.checkedStatus) ? '-checked' : '', baseClass = 'ui-'+((this.radio) ? 'radio' : 'checkbox')+'-state'; stateClass += (this.disabledStatus) ? '-disabled' : ''; stateClass += (this.hover) ? '-hover' : ''; if(stateClass){ stateClass = baseClass + stateClass; } function switchStateClass(){ var classes = this.className.split(' '), found = false; $.each(classes, function(i, classN){ if(classN.indexOf(baseClass) === 0){ found = true; classes[i] = stateClass; return false; } }); if(!found){ classes.push(stateClass); } this.className = classes.join(' '); } this.labels.each(switchStateClass); this.visualElement.each(switchStateClass); }, destroy: function(onlyCss){ this.element.removeClass('ui-helper-hidden-accessible'); this.visualElement.addClass('ui-helper-hidden'); if (!onlyCss) { var o = this.options; this.element.unbind('.checkBox'); this.visualElement.remove(); this.labels .unbind('.checkBox') .removeClass('ui-state-hover ui-state-checked ui-state-disabled'); } }, disable: function(){ this.element[0].disabled = true; this.reflectUI({type: 'manuallyDisabled'}); }, enable: function(){ this.element[0].disabled = false; this.reflectUI({type: 'manuallyenabled'}); }, toggle: function(e){ this.changeCheckStatus((this.element.is(':checked')) ? false : true, e); }, changeCheckStatus: function(status, e){ if(e && e.type == 'click' && this.element[0].disabled){ return false; } this.element.attr({'checked': status}); this.reflectUI(e || { type: 'changeCheckStatus' }); }, propagate: function(n, e, _noGroupReflect){ if(!e || e.type != 'initialReflect'){ if (this.radio && !_noGroupReflect) { //dynamic $(document.getElementsByName(this.element.attr('name'))) .checkBox('reflectUI', e, true); } return this._trigger(n, e, { options: this.options, checked: this.checkedStatus, labels: this.labels, disabled: this.disabledStatus }); } }, reflectUI: function(elm, e){ var oldChecked = this.checkedStatus, oldDisabledStatus = this.disabledStatus; e = e || elm; this.disabledStatus = this.element.is(':disabled'); this.checkedStatus = this.element.is(':checked'); if (this.disabledStatus != oldDisabledStatus || this.checkedStatus !== oldChecked) { this._changeStateClassChain(); (this.disabledStatus != oldDisabledStatus && this.propagate('disabledChange', e)); (this.checkedStatus !== oldChecked && this.propagate('change', e)); } } }); $.ui.checkBox.defaults = { replaceInput: true, addLabel: true }; })(jQuery);
JavaScript
/* * jQuery selectbox plugin * * Copyright (c) 2007 Sadri Sahraoui (brainfault.com) * Licensed under the GPL license and MIT: * http://www.opensource.org/licenses/GPL-license.php * http://www.opensource.org/licenses/mit-license.php * * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete) * * Revision: $Id$ * Version: 0.5 * * Changelog : * Version 0.5 * - separate css style for current selected element and hover element which solve the highlight issue * Version 0.4 * - Fix width when the select is in a hidden div @Pawel Maziarz * - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz */ jQuery.fn.extend({ selectbox: function(options) { return this.each(function() { new jQuery.SelectBox(this, options); }); } }); /* pawel maziarz: work around for ie logging */ if (!window.console) { var console = { log: function(msg) { } } } /* */ jQuery.SelectBox = function(selectobj, options) { var opt = options || {}; opt.inputClass = opt.inputClass || "selectbox2"; opt.containerClass = opt.containerClass || "selectbox-wrapper2"; opt.hoverClass = opt.hoverClass || "current2"; opt.currentClass = opt.selectedClass || "selected2" opt.debug = opt.debug || false; var elm_id = selectobj.id; var active = -1; var inFocus = false; var hasfocus = 0; //jquery object for select element var $select = $(selectobj); // jquery container object var $container = setupContainer(opt); //jquery input object var $input = setupInput(opt); // hide select and append newly created elements $select.hide().before($input).before($container); init(); $input .click(function(){ if (!inFocus) { $container.toggle(); } }) .focus(function(){ if ($container.not(':visible')) { inFocus = true; $container.show(); } }) .keydown(function(event) { switch(event.keyCode) { case 38: // up event.preventDefault(); moveSelect(-1); break; case 40: // down event.preventDefault(); moveSelect(1); break; //case 9: // tab case 13: // return event.preventDefault(); // seems not working in mac ! $('li.'+opt.hoverClass).trigger('click'); break; case 27: //escape hideMe(); break; } }) .blur(function() { if ($container.is(':visible') && hasfocus > 0 ) { if(opt.debug) console.log('container visible and has focus') } else { hideMe(); } }); function hideMe() { hasfocus = 0; $container.hide(); } function init() { $container.append(getSelectOptions($input.attr('id'))).hide(); var width = $input.css('width'); $container.width(width); } function setupContainer(options) { var container = document.createElement("div"); $container = $(container); $container.attr('id', elm_id+'_container'); $container.addClass(options.containerClass); return $container; } function setupInput(options) { var input = document.createElement("input"); var $input = $(input); $input.attr("id", elm_id+"_input"); $input.attr("type", "text"); $input.addClass(options.inputClass); $input.attr("autocomplete", "off"); $input.attr("readonly", "readonly"); $input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie return $input; } function moveSelect(step) { var lis = $("li", $container); if (!lis) return; active += step; if (active < 0) { active = 0; } else if (active >= lis.size()) { active = lis.size() - 1; } lis.removeClass(opt.hoverClass); $(lis[active]).addClass(opt.hoverClass); } function setCurrent() { var li = $("li."+opt.currentClass, $container).get(0); var ar = (''+li.id).split('_'); var el = ar[ar.length-1]; $select.val(el); $input.val($(li).html()); return true; } // select value function getCurrentSelected() { return $select.val(); } // input value function getCurrentValue() { return $input.val(); } function getSelectOptions(parentid) { var select_options = new Array(); var ul = document.createElement('ul'); $select.children('option').each(function() { var li = document.createElement('li'); li.setAttribute('id', parentid + '_' + $(this).val()); li.innerHTML = $(this).html(); if ($(this).is(':selected')) { $input.val($(this).html()); $(li).addClass(opt.currentClass); } ul.appendChild(li); $(li) .mouseover(function(event) { hasfocus = 1; if (opt.debug) console.log('over on : '+this.id); jQuery(event.target, $container).addClass(opt.hoverClass); }) .mouseout(function(event) { hasfocus = -1; if (opt.debug) console.log('out on : '+this.id); jQuery(event.target, $container).removeClass(opt.hoverClass); }) .click(function(event) { var fl = $('li.'+opt.hoverClass, $container).get(0); if (opt.debug) console.log('click on :'+this.id); $('li.'+opt.currentClass).removeClass(opt.currentClass); $(this).addClass(opt.currentClass); setCurrent(); hideMe(); }); }); return ul; } };
JavaScript
/** * syncHeight - jQuery plugin to automagically Snyc the heights of columns * Made to seemlessly work with the CCS-Framework YAML (yaml.de) * @requires jQuery v1.0.3 * * http://blog.ginader.de/dev/syncheight/ * * Copyright (c) 2007-2009 * Dirk Ginader (ginader.de) * Dirk Jesse (yaml.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Version: 1.1 * * Usage: $(document).ready(function(){ $('p').syncHeight(); }); */ (function($) { $.fn.syncHeight = function(config) { var defaults = { updateOnResize: false // re-sync element heights after a browser resize event (useful in flexible layouts) }; var options = $.extend(defaults, config); var e = this; var max = 0; var browser_id = 0; var property = [ // To avoid content overflow in synchronised boxes on font scaling, we // use 'min-height' property for modern browsers ... ['min-height','0px'], // and 'height' property for Internet Explorer. ['height','1%'] ]; // check for IE6 ... if($.browser.msie && $.browser.version < 7){ browser_id = 1; } // get maximum element height ... $(this).each(function() { // fallback to auto height before height check ... $(this).css(property[browser_id][0],property[browser_id][1]); var val=$(this).height(); if(val > max){ max = val; } }); // set synchronized element height ... $(this).each(function() { $(this).css(property[browser_id][0],max+'px'); }); // optional sync refresh on resize event ... if (options.updateOnResize == true) { $(window).resize(function(){ $(e).syncHeight(); }); } return this; }; })(jQuery);
JavaScript
/** * Accessible Tabs - jQuery plugin for accessible, unobtrusive tabs * Build to seemlessly work with the CCS-Framework YAML (yaml.de) not depending on YAML though * @requires jQuery v1.0.3 * * english article: http://blog.ginader.de/archives/2009/02/07/jQuery-Accessible-Tabs-How-to-make-tabs-REALLY-accessible.php * german article: http://blog.ginader.de/archives/2009/02/07/jQuery-Accessible-Tabs-Wie-man-Tabs-WIRKLICH-zugaenglich-macht.php * * code: http://github.com/ginader/Accessible-Tabs * please report issues at: http://github.com/ginader/Accessible-Tabs/issues * * Copyright (c) 2007 Dirk Ginader (ginader.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Version: 1.5 * * History: * * 1.0 initial release * * 1.1 added a lot of Accessibility enhancements * * * rewrite to use "fn.extend" structure * * * added check for existing ids on the content containers to use to proper anchors in the tabs * * 1.1.1 changed the headline markup. thanks to Mike Davies for the hint. * * 1.5 thanks to Dirk Jesse, Ansgar Hein, David Maciejewski and Mike West for commiting patches to this release * * * new option syncheights that syncs the heights of the tab contents when the SyncHeight plugin * * is available http://blog.ginader.de/dev/jquery/syncheight/index.php * * * fixed the hardcoded current class * * * new option tabsListClass to be applied to the generated list of tabs above the content so lists * * inside the tabscontent can be styled differently * * * added clearfix and tabcounter that adds a class in the schema "tabamount{number amount of tabs}" * * to the ul containg the tabs so one can style the tabs to fit 100% into the width * * * new option "syncHeightMethodName" fixed issue: http://github.com/ginader/Accessible-Tabs/issues/2/find * * * new Method showAccessibleTab({index number of the tab to show starting with 0}) fixed issue: http://github.com/ginader/Accessible-Tabs/issues/3/find * * * added support for the Cursor Keys to come closer to the WAI ARIA Tab Panel Best Practices http://github.com/ginader/Accessible-Tabs/issues/1/find */ (function($) { var debugMode = false; $.fn.extend({ getUniqueId: function(p){ return p + new Date().getTime(); }, accessibleTabs: function(config) { var defaults = { wrapperClass: 'content', // Classname to apply to the div that is wrapped around the original Markup currentClass: 'current', // Classname to apply to the LI of the selected Tab tabhead: 'h3', // Tag or valid Query Selector of the Elements to Transform the Tabs-Navigation from (originals are removed) tabbody: '.tabbody', // Tag or valid Query Selector of the Elements to be treated as the Tab Body fx:'show', // can be "fadeIn", "slideDown", "show" fxspeed: 'normal', // speed (String|Number): "slow", "normal", or "fast") or the number of milliseconds to run the animation currentInfoText: 'current tab: ', // text to indicate for screenreaders which tab is the current one currentInfoPosition: 'prepend', // Definition where to insert the Info Text. Can be either "prepend" or "append" currentInfoClass: 'current-info', // Class to apply to the span wrapping the CurrentInfoText tabsListClass:'tabs-list', // Class to apply to the generated list of tabs above the content syncheights:false, // syncs the heights of the tab contents when the SyncHeight plugin is available http://blog.ginader.de/dev/jquery/syncheight/index.php syncHeightMethodName:'syncHeight' // set the Method name of the plugin you want to use to sync the tab contents. Defaults to the SyncHeight plugin: http://github.com/ginader/syncHeight }; // cursor key codes /* backspace 8 tab 9 enter 13 shift 16 ctrl 17 alt 18 pause/break 19 caps lock 20 escape 27 page up 33 page down 34 end 35 home 36 left arrow 37 up arrow 38 right arrow 39 down arrow 40 insert 45 delete 46 */ var keyCodes = { 37 : -1, //LEFT 38 : -1, //UP 39 : +1, //RIGHT 40 : +1 //DOWN }; this.options = $.extend(defaults, config); var o = this; return this.each(function() { var el = $(this); var list = ''; var tabCount = 0; var contentAnchor = o.getUniqueId('accessibletabscontent'); var tabsAnchor = o.getUniqueId('accessibletabs'); $(el).wrapInner('<div class="'+o.options.wrapperClass+'"></div>'); $(el).find(o.options.tabhead).each(function(i){ var id = ''; if(i === 0){ id =' id="'+tabsAnchor+'"'; } list += '<li><a'+id+' href="#'+contentAnchor+'">'+$(this).text()+'</a></li>'; $(this).remove(); tabCount++; }); $(el).prepend('<ul class="clearfix '+o.options.tabsListClass+' tabamount'+tabCount+'">'+list+'</ul>'); $(el).find(o.options.tabbody).hide(); $(el).find(o.options.tabbody+':first').show().before('<'+o.options.tabhead+'><a tabindex="0" class="accessibletabsanchor" name="'+contentAnchor+'" id="'+contentAnchor+'">'+$(el).find("ul>li:first").text()+'</a></'+o.options.tabhead+'>'); $(el).find("ul>li:first").addClass(o.options.currentClass) .find('a')[o.options.currentInfoPosition]('<span class="'+o.options.currentInfoClass+'">'+o.options.currentInfoText+'</span>'); if (o.options.syncheights && $.fn[o.options.syncHeightMethodName]) { $(el).find(o.options.tabbody)[o.options.syncHeightMethodName](); $(window).resize(function(){ $(el).find(o.options.tabbody)[o.options.syncHeightMethodName](); }); } $(el).find('ul.'+o.options.tabsListClass+'>li>a').each(function(i){ $(this).click(function(event){ event.preventDefault(); $(el).find('ul>li.'+o.options.currentClass).removeClass(o.options.currentClass) .find("span."+o.options.currentInfoClass).remove(); $(this).blur(); $(el).find(o.options.tabbody+':visible').hide(); $(el).find(o.options.tabbody).eq(i)[o.options.fx](o.options.fxspeed); $( '#'+contentAnchor ).text( $(this).text() ).focus().keyup(function(event){ if(keyCodes[event.keyCode]){ o.showAccessibleTab(i+keyCodes[event.keyCode]); debug(i); $(this).unbind( "keyup" ); } }); $(this)[o.options.currentInfoPosition]('<span class="'+o.options.currentInfoClass+'">'+o.options.currentInfoText+'</span>') .parent().addClass(o.options.currentClass); // $(el).find('.accessibletabsanchor').keyup(function(event){ // if(keyCodes[event.keyCode]){ // o.showAccessibleTab(i+keyCodes[event.keyCode]); // } // }); }); $(this).focus(function(event){ debug($(this)); $(document).keyup(function(event){ if(keyCodes[event.keyCode]){ o.showAccessibleTab(i+keyCodes[event.keyCode]); } }); }); $(this).blur(function(event){ $(document).unbind( "keyup" ); }); }); }); }, showAccessibleTab: function(index){ debug('showAccessibleTab'); debug(index); var o = this; return this.each(function() { var el = $(this); var links = el.find('ul.'+o.options.tabsListClass+'>li>a'); debug(links); links.eq(index).click(); }); } }); // private Methods function debug(msg){ if(debugMode && window.console && window.console.log){ window.console.log(msg); } } })(jQuery);
JavaScript
/** * "Yet Another Multicolumn Layout" - (X)HTML/CSS Framework * * (en) Workaround for IE8 und Webkit browsers to fix focus problems when using skiplinks * (de) Workaround für IE8 und Webkit browser, um den Focus zu korrigieren, bei Verwendung von Skiplinks * * @note inspired by Paul Ratcliffe's article * http://www.communis.co.uk/blog/2009-06-02-skip-links-chrome-safari-and-added-wai-aria * Many thanks to Mathias Schäfer (http://molily.de/) for his code improvements * * @copyright Copyright 2005-2010, Dirk Jesse * @license CC-A 2.0 (http://creativecommons.org/licenses/by/2.0/), * YAML-C (http://www.yaml.de/en/license/license-conditions.html) * @link http://www.yaml.de * @package yaml * @version 3.3 * @revision $Revision: 466 $ * @lastmodified $Date: 2010-09-14 21:19:30 +0200 (Di, 14 Sep 2010) $ */ (function () { var YAML_focusFix = { skipClass : 'skip', init : function () { var userAgent = navigator.userAgent.toLowerCase(); var is_webkit = userAgent.indexOf('webkit') > -1; var is_ie = userAgent.indexOf('msie') > -1; if (is_webkit || is_ie) { var body = document.body, handler = YAML_focusFix.click; if (body.addEventListener) { body.addEventListener('click', handler, false); } else if (body.attachEvent) { body.attachEvent('onclick', handler); } } }, click : function (e) { e = e || window.event; var target = e.target || e.srcElement; if (target.className.indexOf(YAML_focusFix.skipClass) > -1) { YAML_focusFix.focus(target); } }, focus : function (link) { var href = link.href, id = href.substr(href.indexOf('#') + 1), target = document.getElementById(id); if (target) { target.setAttribute("tabindex", "-1"); target.focus(); } } }; YAML_focusFix.init(); })();
JavaScript
// minmax.js: make IE5+/Win support CSS min/max-width/height // version 1.0, 08-Aug-2003 // written by Andrew Clover <and@doxdesk.com>, use freely /*@cc_on @if (@_win32 && @_jscript_version>4) var minmax_elements; minmax_props= new Array( new Array('min-width', 'minWidth'), new Array('max-width', 'maxWidth'), new Array('min-height','minHeight'), new Array('max-height','maxHeight') ); // Binding. Called on all new elements. If <body>, initialise; check all // elements for minmax properties function minmax_bind(el) { var i, em, ms; var st= el.style, cs= el.currentStyle; if (minmax_elements==window.undefined) { // initialise when body element has turned up, but only on IE if (!document.body || !document.body.currentStyle) return; minmax_elements= new Array(); window.attachEvent('onresize', minmax_delayout); // make font size listener em= document.createElement('div'); em.setAttribute('id', 'minmax_em'); em.style.position= 'absolute'; em.style.visibility= 'hidden'; em.style.fontSize= 'xx-large'; em.style.height= '5em'; em.style.top='-5em'; em.style.left= '0'; if (em.style.setExpression) { em.style.setExpression('width', 'minmax_checkFont()'); document.body.insertBefore(em, document.body.firstChild); } } // transform hyphenated properties the browser has not caught to camelCase for (i= minmax_props.length; i-->0;) if (cs[minmax_props[i][0]]) st[minmax_props[i][1]]= cs[minmax_props[i][0]]; // add element with properties to list, store optimal size values for (i= minmax_props.length; i-->0;) { ms= cs[minmax_props[i][1]]; if (ms && ms!='auto' && ms!='none' && ms!='0' && ms!='') { st.minmaxWidth= cs.width; st.minmaxHeight= cs.height; minmax_elements[minmax_elements.length]= el; // will need a layout later minmax_delayout(); break; } } } // check for font size changes var minmax_fontsize= 0; function minmax_checkFont() { var fs= document.getElementById('minmax_em').offsetHeight; if (minmax_fontsize!=fs && minmax_fontsize!=0) minmax_delayout(); minmax_fontsize= fs; return '5em'; } // Layout. Called after window and font size-change. Go through elements we // picked out earlier and set their size to the minimum, maximum and optimum, // choosing whichever is appropriate // Request re-layout at next available moment var minmax_delaying= false; function minmax_delayout() { if (minmax_delaying) return; minmax_delaying= true; window.setTimeout(minmax_layout, 0); } function minmax_stopdelaying() { minmax_delaying= false; } function minmax_layout() { window.setTimeout(minmax_stopdelaying, 100); var i, el, st, cs, optimal, inrange; for (i= minmax_elements.length; i-->0;) { el= minmax_elements[i]; st= el.style; cs= el.currentStyle; // horizontal size bounding st.width= st.minmaxWidth; optimal= el.offsetWidth; inrange= true; if (inrange && cs.minWidth && cs.minWidth!='0' && cs.minWidth!='auto' && cs.minWidth!='') { st.width= cs.minWidth; inrange= (el.offsetWidth<optimal); } if (inrange && cs.maxWidth && cs.maxWidth!='none' && cs.maxWidth!='auto' && cs.maxWidth!='') { st.width= cs.maxWidth; inrange= (el.offsetWidth>optimal); } if (inrange) st.width= st.minmaxWidth; // vertical size bounding st.height= st.minmaxHeight; optimal= el.offsetHeight; inrange= true; if (inrange && cs.minHeight && cs.minHeight!='0' && cs.minHeight!='auto' && cs.minHeight!='') { st.height= cs.minHeight; inrange= (el.offsetHeight<optimal); } if (inrange && cs.maxHeight && cs.maxHeight!='none' && cs.maxHeight!='auto' && cs.maxHeight!='') { st.height= cs.maxHeight; inrange= (el.offsetHeight>optimal); } if (inrange) st.height= st.minmaxHeight; } } // Scanning. Check document every so often until it has finished loading. Do // nothing until <body> arrives, then call main init. Pass any new elements // found on each scan to be bound var minmax_SCANDELAY= 500; function minmax_scan() { var el; for (var i= 0; i<document.all.length; i++) { el= document.all[i]; if (!el.minmax_bound) { el.minmax_bound= true; minmax_bind(el); } } } var minmax_scanner; function minmax_stop() { window.clearInterval(minmax_scanner); minmax_scan(); } minmax_scan(); minmax_scanner= window.setInterval(minmax_scan, minmax_SCANDELAY); window.attachEvent('onload', minmax_stop); @end @*/
JavaScript
//filler text on demand // http://web-graphics.com/mtarchive/001667.php var words=new Array('lorem','ipsum','dolor','sit','amet','consectetuer','adipiscing','elit','suspendisse','eget','diam','quis','diam','consequat','interdum'); function AddFillerLink(){ if(!document.getElementById || !document.createElement) return; var i,l; for(i=0;i<arguments.length;i++){ if (document.getElementById(arguments[i])) { /* Check elements exists - add Reinhard Hiebl */ l=document.createElement("a"); l.href="#"; l.appendChild(document.createTextNode("Add Text")); l.onclick=function(){AddText(this);return(false)}; document.getElementById(arguments[i]).appendChild(l); b=document.createTextNode(" | "); document.getElementById(arguments[i]).appendChild(b); r=document.createElement("a"); r.href="#"; r.appendChild(document.createTextNode("Remove Text")); r.onclick=function(){RemoveText(this);return(false)}; document.getElementById(arguments[i]).appendChild(r); } } } function AddText(el){ var s="",n,i; n=RandomNumber(20,80); for(i=0;i<n;i++) s+=words[RandomNumber(0,words.length-1)]+" "; var t=document.createElement("p"); t.setAttribute('class','added'); t.appendChild(document.createTextNode(s)); el.parentNode.insertBefore(t,el); } function RemoveText(el){ var parent = el.parentNode; for(var i=0;i<parent.childNodes.length;i++) { var para = parent.childNodes[i]; if(para.nodeName == "P" && para.getAttribute('class')=='added') { parent.removeChild(para); break; } } } function RandomNumber(n1,n2){ return(Math.floor(Math.random()*(n2-n1))+n1); }
JavaScript
/*** P R O C E S S I N G . J S - 1.4.1 a port of the Processing visualization language Processing.js is licensed under the MIT License, see LICENSE. For a list of copyright holders, please refer to AUTHORS. http://processingjs.org ***/ (function(window, document, Math, undef) { var nop = function() {}; var debug = function() { if ("console" in window) return function(msg) { window.console.log("Processing.js: " + msg) }; return nop }(); var ajax = function(url) { var xhr = new XMLHttpRequest; xhr.open("GET", url, false); if (xhr.overrideMimeType) xhr.overrideMimeType("text/plain"); xhr.setRequestHeader("If-Modified-Since", "Fri, 01 Jan 1960 00:00:00 GMT"); xhr.send(null); if (xhr.status !== 200 && xhr.status !== 0) throw "XMLHttpRequest failed, status code " + xhr.status; return xhr.responseText }; var isDOMPresent = "document" in this && !("fake" in this.document); document.head = document.head || document.getElementsByTagName("head")[0]; function setupTypedArray(name, fallback) { if (name in window) return window[name]; if (typeof window[fallback] === "function") return window[fallback]; return function(obj) { if (obj instanceof Array) return obj; if (typeof obj === "number") { var arr = []; arr.length = obj; return arr } } } if (document.documentMode >= 9 && !document.doctype) throw "The doctype directive is missing. The recommended doctype in Internet Explorer is the HTML5 doctype: <!DOCTYPE html>"; var Float32Array = setupTypedArray("Float32Array", "WebGLFloatArray"), Int32Array = setupTypedArray("Int32Array", "WebGLIntArray"), Uint16Array = setupTypedArray("Uint16Array", "WebGLUnsignedShortArray"), Uint8Array = setupTypedArray("Uint8Array", "WebGLUnsignedByteArray"); var PConstants = { X: 0, Y: 1, Z: 2, R: 3, G: 4, B: 5, A: 6, U: 7, V: 8, NX: 9, NY: 10, NZ: 11, EDGE: 12, SR: 13, SG: 14, SB: 15, SA: 16, SW: 17, TX: 18, TY: 19, TZ: 20, VX: 21, VY: 22, VZ: 23, VW: 24, AR: 25, AG: 26, AB: 27, DR: 3, DG: 4, DB: 5, DA: 6, SPR: 28, SPG: 29, SPB: 30, SHINE: 31, ER: 32, EG: 33, EB: 34, BEEN_LIT: 35, VERTEX_FIELD_COUNT: 36, P2D: 1, JAVA2D: 1, WEBGL: 2, P3D: 2, OPENGL: 2, PDF: 0, DXF: 0, OTHER: 0, WINDOWS: 1, MAXOSX: 2, LINUX: 3, EPSILON: 1.0E-4, MAX_FLOAT: 3.4028235E38, MIN_FLOAT: -3.4028235E38, MAX_INT: 2147483647, MIN_INT: -2147483648, PI: Math.PI, TWO_PI: 2 * Math.PI, HALF_PI: Math.PI / 2, THIRD_PI: Math.PI / 3, QUARTER_PI: Math.PI / 4, DEG_TO_RAD: Math.PI / 180, RAD_TO_DEG: 180 / Math.PI, WHITESPACE: " \t\n\r\u000c\u00a0", RGB: 1, ARGB: 2, HSB: 3, ALPHA: 4, CMYK: 5, TIFF: 0, TARGA: 1, JPEG: 2, GIF: 3, BLUR: 11, GRAY: 12, INVERT: 13, OPAQUE: 14, POSTERIZE: 15, THRESHOLD: 16, ERODE: 17, DILATE: 18, REPLACE: 0, BLEND: 1 << 0, ADD: 1 << 1, SUBTRACT: 1 << 2, LIGHTEST: 1 << 3, DARKEST: 1 << 4, DIFFERENCE: 1 << 5, EXCLUSION: 1 << 6, MULTIPLY: 1 << 7, SCREEN: 1 << 8, OVERLAY: 1 << 9, HARD_LIGHT: 1 << 10, SOFT_LIGHT: 1 << 11, DODGE: 1 << 12, BURN: 1 << 13, ALPHA_MASK: 4278190080, RED_MASK: 16711680, GREEN_MASK: 65280, BLUE_MASK: 255, CUSTOM: 0, ORTHOGRAPHIC: 2, PERSPECTIVE: 3, POINT: 2, POINTS: 2, LINE: 4, LINES: 4, TRIANGLE: 8, TRIANGLES: 9, TRIANGLE_STRIP: 10, TRIANGLE_FAN: 11, QUAD: 16, QUADS: 16, QUAD_STRIP: 17, POLYGON: 20, PATH: 21, RECT: 30, ELLIPSE: 31, ARC: 32, SPHERE: 40, BOX: 41, GROUP: 0, PRIMITIVE: 1, GEOMETRY: 3, VERTEX: 0, BEZIER_VERTEX: 1, CURVE_VERTEX: 2, BREAK: 3, CLOSESHAPE: 4, OPEN: 1, CLOSE: 2, CORNER: 0, CORNERS: 1, RADIUS: 2, CENTER_RADIUS: 2, CENTER: 3, DIAMETER: 3, CENTER_DIAMETER: 3, BASELINE: 0, TOP: 101, BOTTOM: 102, NORMAL: 1, NORMALIZED: 1, IMAGE: 2, MODEL: 4, SHAPE: 5, SQUARE: "butt", ROUND: "round", PROJECT: "square", MITER: "miter", BEVEL: "bevel", AMBIENT: 0, DIRECTIONAL: 1, SPOT: 3, BACKSPACE: 8, TAB: 9, ENTER: 10, RETURN: 13, ESC: 27, DELETE: 127, CODED: 65535, SHIFT: 16, CONTROL: 17, ALT: 18, CAPSLK: 20, PGUP: 33, PGDN: 34, END: 35, HOME: 36, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123, NUMLK: 144, META: 157, INSERT: 155, ARROW: "default", CROSS: "crosshair", HAND: "pointer", MOVE: "move", TEXT: "text", WAIT: "wait", NOCURSOR: "url('data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='), auto", DISABLE_OPENGL_2X_SMOOTH: 1, ENABLE_OPENGL_2X_SMOOTH: -1, ENABLE_OPENGL_4X_SMOOTH: 2, ENABLE_NATIVE_FONTS: 3, DISABLE_DEPTH_TEST: 4, ENABLE_DEPTH_TEST: -4, ENABLE_DEPTH_SORT: 5, DISABLE_DEPTH_SORT: -5, DISABLE_OPENGL_ERROR_REPORT: 6, ENABLE_OPENGL_ERROR_REPORT: -6, ENABLE_ACCURATE_TEXTURES: 7, DISABLE_ACCURATE_TEXTURES: -7, HINT_COUNT: 10, SINCOS_LENGTH: 720, PRECISIONB: 15, PRECISIONF: 1 << 15, PREC_MAXVAL: (1 << 15) - 1, PREC_ALPHA_SHIFT: 24 - 15, PREC_RED_SHIFT: 16 - 15, NORMAL_MODE_AUTO: 0, NORMAL_MODE_SHAPE: 1, NORMAL_MODE_VERTEX: 2, MAX_LIGHTS: 8 }; function virtHashCode(obj) { if (typeof obj === "string") { var hash = 0; for (var i = 0; i < obj.length; ++i) hash = hash * 31 + obj.charCodeAt(i) & 4294967295; return hash } if (typeof obj !== "object") return obj & 4294967295; if (obj.hashCode instanceof Function) return obj.hashCode(); if (obj.$id === undef) obj.$id = Math.floor(Math.random() * 65536) - 32768 << 16 | Math.floor(Math.random() * 65536); return obj.$id } function virtEquals(obj, other) { if (obj === null || other === null) return obj === null && other === null; if (typeof obj === "string") return obj === other; if (typeof obj !== "object") return obj === other; if (obj.equals instanceof Function) return obj.equals(other); return obj === other } var ObjectIterator = function(obj) { if (obj.iterator instanceof Function) return obj.iterator(); if (obj instanceof Array) { var index = -1; this.hasNext = function() { return ++index < obj.length }; this.next = function() { return obj[index] } } else throw "Unable to iterate: " + obj; }; var ArrayList = function() { function Iterator(array) { var index = 0; this.hasNext = function() { return index < array.length }; this.next = function() { return array[index++] }; this.remove = function() { array.splice(index, 1) } } function ArrayList(a) { var array; if (a instanceof ArrayList) array = a.toArray(); else { array = []; if (typeof a === "number") array.length = a > 0 ? a : 0 } this.get = function(i) { return array[i] }; this.contains = function(item) { return this.indexOf(item) > -1 }; this.indexOf = function(item) { for (var i = 0, len = array.length; i < len; ++i) if (virtEquals(item, array[i])) return i; return -1 }; this.lastIndexOf = function(item) { for (var i = array.length - 1; i >= 0; --i) if (virtEquals(item, array[i])) return i; return -1 }; this.add = function() { if (arguments.length === 1) array.push(arguments[0]); else if (arguments.length === 2) { var arg0 = arguments[0]; if (typeof arg0 === "number") if (arg0 >= 0 && arg0 <= array.length) array.splice(arg0, 0, arguments[1]); else throw arg0 + " is not a valid index"; else throw typeof arg0 + " is not a number"; } else throw "Please use the proper number of parameters."; }; this.addAll = function(arg1, arg2) { var it; if (typeof arg1 === "number") { if (arg1 < 0 || arg1 > array.length) throw "Index out of bounds for addAll: " + arg1 + " greater or equal than " + array.length; it = new ObjectIterator(arg2); while (it.hasNext()) array.splice(arg1++, 0, it.next()) } else { it = new ObjectIterator(arg1); while (it.hasNext()) array.push(it.next()) } }; this.set = function() { if (arguments.length === 2) { var arg0 = arguments[0]; if (typeof arg0 === "number") if (arg0 >= 0 && arg0 < array.length) array.splice(arg0, 1, arguments[1]); else throw arg0 + " is not a valid index."; else throw typeof arg0 + " is not a number"; } else throw "Please use the proper number of parameters."; }; this.size = function() { return array.length }; this.clear = function() { array.length = 0 }; this.remove = function(item) { if (typeof item === "number") return array.splice(item, 1)[0]; item = this.indexOf(item); if (item > -1) { array.splice(item, 1); return true } return false }; this.removeAll = function(c) { var i, x, item, newList = new ArrayList; newList.addAll(this); this.clear(); for (i = 0, x = 0; i < newList.size(); i++) { item = newList.get(i); if (!c.contains(item)) this.add(x++, item) } if (this.size() < newList.size()) return true; return false }; this.isEmpty = function() { return !array.length }; this.clone = function() { return new ArrayList(this) }; this.toArray = function() { return array.slice(0) }; this.iterator = function() { return new Iterator(array) } } return ArrayList }(); var HashMap = function() { function HashMap() { if (arguments.length === 1 && arguments[0] instanceof HashMap) return arguments[0].clone(); var initialCapacity = arguments.length > 0 ? arguments[0] : 16; var loadFactor = arguments.length > 1 ? arguments[1] : 0.75; var buckets = []; buckets.length = initialCapacity; var count = 0; var hashMap = this; function getBucketIndex(key) { var index = virtHashCode(key) % buckets.length; return index < 0 ? buckets.length + index : index } function ensureLoad() { if (count <= loadFactor * buckets.length) return; var allEntries = []; for (var i = 0; i < buckets.length; ++i) if (buckets[i] !== undef) allEntries = allEntries.concat(buckets[i]); var newBucketsLength = buckets.length * 2; buckets = []; buckets.length = newBucketsLength; for (var j = 0; j < allEntries.length; ++j) { var index = getBucketIndex(allEntries[j].key); var bucket = buckets[index]; if (bucket === undef) buckets[index] = bucket = []; bucket.push(allEntries[j]) } } function Iterator(conversion, removeItem) { var bucketIndex = 0; var itemIndex = -1; var endOfBuckets = false; var currentItem; function findNext() { while (!endOfBuckets) { ++itemIndex; if (bucketIndex >= buckets.length) endOfBuckets = true; else if (buckets[bucketIndex] === undef || itemIndex >= buckets[bucketIndex].length) { itemIndex = -1; ++bucketIndex } else return } } this.hasNext = function() { return !endOfBuckets }; this.next = function() { currentItem = conversion(buckets[bucketIndex][itemIndex]); findNext(); return currentItem }; this.remove = function() { if (currentItem !== undef) { removeItem(currentItem); --itemIndex; findNext() } }; findNext() } function Set(conversion, isIn, removeItem) { this.clear = function() { hashMap.clear() }; this.contains = function(o) { return isIn(o) }; this.containsAll = function(o) { var it = o.iterator(); while (it.hasNext()) if (!this.contains(it.next())) return false; return true }; this.isEmpty = function() { return hashMap.isEmpty() }; this.iterator = function() { return new Iterator(conversion, removeItem) }; this.remove = function(o) { if (this.contains(o)) { removeItem(o); return true } return false }; this.removeAll = function(c) { var it = c.iterator(); var changed = false; while (it.hasNext()) { var item = it.next(); if (this.contains(item)) { removeItem(item); changed = true } } return true }; this.retainAll = function(c) { var it = this.iterator(); var toRemove = []; while (it.hasNext()) { var entry = it.next(); if (!c.contains(entry)) toRemove.push(entry) } for (var i = 0; i < toRemove.length; ++i) removeItem(toRemove[i]); return toRemove.length > 0 }; this.size = function() { return hashMap.size() }; this.toArray = function() { var result = []; var it = this.iterator(); while (it.hasNext()) result.push(it.next()); return result } } function Entry(pair) { this._isIn = function(map) { return map === hashMap && pair.removed === undef }; this.equals = function(o) { return virtEquals(pair.key, o.getKey()) }; this.getKey = function() { return pair.key }; this.getValue = function() { return pair.value }; this.hashCode = function(o) { return virtHashCode(pair.key) }; this.setValue = function(value) { var old = pair.value; pair.value = value; return old } } this.clear = function() { count = 0; buckets = []; buckets.length = initialCapacity }; this.clone = function() { var map = new HashMap; map.putAll(this); return map }; this.containsKey = function(key) { var index = getBucketIndex(key); var bucket = buckets[index]; if (bucket === undef) return false; for (var i = 0; i < bucket.length; ++i) if (virtEquals(bucket[i].key, key)) return true; return false }; this.containsValue = function(value) { for (var i = 0; i < buckets.length; ++i) { var bucket = buckets[i]; if (bucket === undef) continue; for (var j = 0; j < bucket.length; ++j) if (virtEquals(bucket[j].value, value)) return true } return false }; this.entrySet = function() { return new Set(function(pair) { return new Entry(pair) }, function(pair) { return pair instanceof Entry && pair._isIn(hashMap) }, function(pair) { return hashMap.remove(pair.getKey()) }) }; this.get = function(key) { var index = getBucketIndex(key); var bucket = buckets[index]; if (bucket === undef) return null; for (var i = 0; i < bucket.length; ++i) if (virtEquals(bucket[i].key, key)) return bucket[i].value; return null }; this.isEmpty = function() { return count === 0 }; this.keySet = function() { return new Set(function(pair) { return pair.key }, function(key) { return hashMap.containsKey(key) }, function(key) { return hashMap.remove(key) }) }; this.values = function() { return new Set(function(pair) { return pair.value }, function(value) { return hashMap.containsValue(value) }, function(value) { return hashMap.removeByValue(value) }) }; this.put = function(key, value) { var index = getBucketIndex(key); var bucket = buckets[index]; if (bucket === undef) { ++count; buckets[index] = [{ key: key, value: value }]; ensureLoad(); return null } for (var i = 0; i < bucket.length; ++i) if (virtEquals(bucket[i].key, key)) { var previous = bucket[i].value; bucket[i].value = value; return previous }++count; bucket.push({ key: key, value: value }); ensureLoad(); return null }; this.putAll = function(m) { var it = m.entrySet().iterator(); while (it.hasNext()) { var entry = it.next(); this.put(entry.getKey(), entry.getValue()) } }; this.remove = function(key) { var index = getBucketIndex(key); var bucket = buckets[index]; if (bucket === undef) return null; for (var i = 0; i < bucket.length; ++i) if (virtEquals(bucket[i].key, key)) { --count; var previous = bucket[i].value; bucket[i].removed = true; if (bucket.length > 1) bucket.splice(i, 1); else buckets[index] = undef; return previous } return null }; this.removeByValue = function(value) { var bucket, i, ilen, pair; for (bucket in buckets) if (buckets.hasOwnProperty(bucket)) for (i = 0, ilen = buckets[bucket].length; i < ilen; i++) { pair = buckets[bucket][i]; if (pair.value === value) { buckets[bucket].splice(i, 1); return true } } return false }; this.size = function() { return count } } return HashMap }(); var PVector = function() { function PVector(x, y, z) { this.x = x || 0; this.y = y || 0; this.z = z || 0 } PVector.dist = function(v1, v2) { return v1.dist(v2) }; PVector.dot = function(v1, v2) { return v1.dot(v2) }; PVector.cross = function(v1, v2) { return v1.cross(v2) }; PVector.angleBetween = function(v1, v2) { return Math.acos(v1.dot(v2) / (v1.mag() * v2.mag())) }; PVector.prototype = { set: function(v, y, z) { if (arguments.length === 1) this.set(v.x || v[0] || 0, v.y || v[1] || 0, v.z || v[2] || 0); else { this.x = v; this.y = y; this.z = z } }, get: function() { return new PVector(this.x, this.y, this.z) }, mag: function() { var x = this.x, y = this.y, z = this.z; return Math.sqrt(x * x + y * y + z * z) }, add: function(v, y, z) { if (arguments.length === 1) { this.x += v.x; this.y += v.y; this.z += v.z } else { this.x += v; this.y += y; this.z += z } }, sub: function(v, y, z) { if (arguments.length === 1) { this.x -= v.x; this.y -= v.y; this.z -= v.z } else { this.x -= v; this.y -= y; this.z -= z } }, mult: function(v) { if (typeof v === "number") { this.x *= v; this.y *= v; this.z *= v } else { this.x *= v.x; this.y *= v.y; this.z *= v.z } }, div: function(v) { if (typeof v === "number") { this.x /= v; this.y /= v; this.z /= v } else { this.x /= v.x; this.y /= v.y; this.z /= v.z } }, dist: function(v) { var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; return Math.sqrt(dx * dx + dy * dy + dz * dz) }, dot: function(v, y, z) { if (arguments.length === 1) return this.x * v.x + this.y * v.y + this.z * v.z; return this.x * v + this.y * y + this.z * z }, cross: function(v) { var x = this.x, y = this.y, z = this.z; return new PVector(y * v.z - v.y * z, z * v.x - v.z * x, x * v.y - v.x * y) }, normalize: function() { var m = this.mag(); if (m > 0) this.div(m) }, limit: function(high) { if (this.mag() > high) { this.normalize(); this.mult(high) } }, heading2D: function() { return -Math.atan2(-this.y, this.x) }, toString: function() { return "[" + this.x + ", " + this.y + ", " + this.z + "]" }, array: function() { return [this.x, this.y, this.z] } }; function createPVectorMethod(method) { return function(v1, v2) { var v = v1.get(); v[method](v2); return v } } for (var method in PVector.prototype) if (PVector.prototype.hasOwnProperty(method) && !PVector.hasOwnProperty(method)) PVector[method] = createPVectorMethod(method); return PVector }(); function DefaultScope() {} DefaultScope.prototype = PConstants; var defaultScope = new DefaultScope; defaultScope.ArrayList = ArrayList; defaultScope.HashMap = HashMap; defaultScope.PVector = PVector; defaultScope.ObjectIterator = ObjectIterator; defaultScope.PConstants = PConstants; defaultScope.defineProperty = function(obj, name, desc) { if ("defineProperty" in Object) Object.defineProperty(obj, name, desc); else { if (desc.hasOwnProperty("get")) obj.__defineGetter__(name, desc.get); if (desc.hasOwnProperty("set")) obj.__defineSetter__(name, desc.set) } }; function overloadBaseClassFunction(object, name, basefn) { if (!object.hasOwnProperty(name) || typeof object[name] !== "function") { object[name] = basefn; return } var fn = object[name]; if ("$overloads" in fn) { fn.$defaultOverload = basefn; return } if (! ("$overloads" in basefn) && fn.length === basefn.length) return; var overloads, defaultOverload; if ("$overloads" in basefn) { overloads = basefn.$overloads.slice(0); overloads[fn.length] = fn; defaultOverload = basefn.$defaultOverload } else { overloads = []; overloads[basefn.length] = basefn; overloads[fn.length] = fn; defaultOverload = fn } var hubfn = function() { var fn = hubfn.$overloads[arguments.length] || ("$methodArgsIndex" in hubfn && arguments.length > hubfn.$methodArgsIndex ? hubfn.$overloads[hubfn.$methodArgsIndex] : null) || hubfn.$defaultOverload; return fn.apply(this, arguments) }; hubfn.$overloads = overloads; if ("$methodArgsIndex" in basefn) hubfn.$methodArgsIndex = basefn.$methodArgsIndex; hubfn.$defaultOverload = defaultOverload; hubfn.name = name; object[name] = hubfn } function extendClass(subClass, baseClass) { function extendGetterSetter(propertyName) { defaultScope.defineProperty(subClass, propertyName, { get: function() { return baseClass[propertyName] }, set: function(v) { baseClass[propertyName] = v }, enumerable: true }) } var properties = []; for (var propertyName in baseClass) if (typeof baseClass[propertyName] === "function") overloadBaseClassFunction(subClass, propertyName, baseClass[propertyName]); else if (propertyName.charAt(0) !== "$" && !(propertyName in subClass)) properties.push(propertyName); while (properties.length > 0) extendGetterSetter(properties.shift()); subClass.$super = baseClass } defaultScope.extendClassChain = function(base) { var path = [base]; for (var self = base.$upcast; self; self = self.$upcast) { extendClass(self, base); path.push(self); base = self } while (path.length > 0) path.pop().$self = base }; defaultScope.extendStaticMembers = function(derived, base) { extendClass(derived, base) }; defaultScope.extendInterfaceMembers = function(derived, base) { extendClass(derived, base) }; defaultScope.addMethod = function(object, name, fn, hasMethodArgs) { var existingfn = object[name]; if (existingfn || hasMethodArgs) { var args = fn.length; if ("$overloads" in existingfn) existingfn.$overloads[args] = fn; else { var hubfn = function() { var fn = hubfn.$overloads[arguments.length] || ("$methodArgsIndex" in hubfn && arguments.length > hubfn.$methodArgsIndex ? hubfn.$overloads[hubfn.$methodArgsIndex] : null) || hubfn.$defaultOverload; return fn.apply(this, arguments) }; var overloads = []; if (existingfn) overloads[existingfn.length] = existingfn; overloads[args] = fn; hubfn.$overloads = overloads; hubfn.$defaultOverload = existingfn || fn; if (hasMethodArgs) hubfn.$methodArgsIndex = args; hubfn.name = name; object[name] = hubfn } } else object[name] = fn }; function isNumericalJavaType(type) { if (typeof type !== "string") return false; return ["byte", "int", "char", "color", "float", "long", "double"].indexOf(type) !== -1 } defaultScope.createJavaArray = function(type, bounds) { var result = null, defaultValue = null; if (typeof type === "string") if (type === "boolean") defaultValue = false; else if (isNumericalJavaType(type)) defaultValue = 0; if (typeof bounds[0] === "number") { var itemsCount = 0 | bounds[0]; if (bounds.length <= 1) { result = []; result.length = itemsCount; for (var i = 0; i < itemsCount; ++i) result[i] = defaultValue } else { result = []; var newBounds = bounds.slice(1); for (var j = 0; j < itemsCount; ++j) result.push(defaultScope.createJavaArray(type, newBounds)) } } return result }; var colors = { aliceblue: "#f0f8ff", antiquewhite: "#faebd7", aqua: "#00ffff", aquamarine: "#7fffd4", azure: "#f0ffff", beige: "#f5f5dc", bisque: "#ffe4c4", black: "#000000", blanchedalmond: "#ffebcd", blue: "#0000ff", 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", darkkhaki: "#bdb76b", darkmagenta: "#8b008b", darkolivegreen: "#556b2f", darkorange: "#ff8c00", darkorchid: "#9932cc", darkred: "#8b0000", darksalmon: "#e9967a", darkseagreen: "#8fbc8f", darkslateblue: "#483d8b", darkslategray: "#2f4f4f", darkturquoise: "#00ced1", darkviolet: "#9400d3", deeppink: "#ff1493", deepskyblue: "#00bfff", dimgray: "#696969", dodgerblue: "#1e90ff", firebrick: "#b22222", floralwhite: "#fffaf0", forestgreen: "#228b22", fuchsia: "#ff00ff", gainsboro: "#dcdcdc", ghostwhite: "#f8f8ff", gold: "#ffd700", goldenrod: "#daa520", gray: "#808080", green: "#008000", 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", lightgrey: "#d3d3d3", lightgreen: "#90ee90", lightpink: "#ffb6c1", lightsalmon: "#ffa07a", lightseagreen: "#20b2aa", lightskyblue: "#87cefa", lightslategray: "#778899", lightsteelblue: "#b0c4de", lightyellow: "#ffffe0", lime: "#00ff00", limegreen: "#32cd32", linen: "#faf0e6", magenta: "#ff00ff", maroon: "#800000", mediumaquamarine: "#66cdaa", mediumblue: "#0000cd", mediumorchid: "#ba55d3", mediumpurple: "#9370d8", mediumseagreen: "#3cb371", mediumslateblue: "#7b68ee", mediumspringgreen: "#00fa9a", mediumturquoise: "#48d1cc", mediumvioletred: "#c71585", midnightblue: "#191970", mintcream: "#f5fffa", mistyrose: "#ffe4e1", moccasin: "#ffe4b5", navajowhite: "#ffdead", navy: "#000080", oldlace: "#fdf5e6", olive: "#808000", olivedrab: "#6b8e23", orange: "#ffa500", orangered: "#ff4500", orchid: "#da70d6", palegoldenrod: "#eee8aa", palegreen: "#98fb98", paleturquoise: "#afeeee", palevioletred: "#d87093", papayawhip: "#ffefd5", peachpuff: "#ffdab9", peru: "#cd853f", pink: "#ffc0cb", plum: "#dda0dd", powderblue: "#b0e0e6", purple: "#800080", red: "#ff0000", rosybrown: "#bc8f8f", royalblue: "#4169e1", saddlebrown: "#8b4513", salmon: "#fa8072", sandybrown: "#f4a460", seagreen: "#2e8b57", seashell: "#fff5ee", sienna: "#a0522d", silver: "#c0c0c0", skyblue: "#87ceeb", slateblue: "#6a5acd", slategray: "#708090", snow: "#fffafa", springgreen: "#00ff7f", steelblue: "#4682b4", tan: "#d2b48c", teal: "#008080", thistle: "#d8bfd8", tomato: "#ff6347", turquoise: "#40e0d0", violet: "#ee82ee", wheat: "#f5deb3", white: "#ffffff", whitesmoke: "#f5f5f5", yellow: "#ffff00", yellowgreen: "#9acd32" }; (function(Processing) { var unsupportedP5 = ("open() createOutput() createInput() BufferedReader selectFolder() " + "dataPath() createWriter() selectOutput() beginRecord() " + "saveStream() endRecord() selectInput() saveBytes() createReader() " + "beginRaw() endRaw() PrintWriter delay()").split(" "), count = unsupportedP5.length, prettyName, p5Name; function createUnsupportedFunc(n) { return function() { throw "Processing.js does not support " + n + "."; } } while (count--) { prettyName = unsupportedP5[count]; p5Name = prettyName.replace("()", ""); Processing[p5Name] = createUnsupportedFunc(prettyName) } })(defaultScope); defaultScope.defineProperty(defaultScope, "screenWidth", { get: function() { return window.innerWidth } }); defaultScope.defineProperty(defaultScope, "screenHeight", { get: function() { return window.innerHeight } }); defaultScope.defineProperty(defaultScope, "online", { get: function() { return true } }); var processingInstances = []; var processingInstanceIds = {}; var removeInstance = function(id) { processingInstances.splice(processingInstanceIds[id], 1); delete processingInstanceIds[id] }; var addInstance = function(processing) { if (processing.externals.canvas.id === undef || !processing.externals.canvas.id.length) processing.externals.canvas.id = "__processing" + processingInstances.length; processingInstanceIds[processing.externals.canvas.id] = processingInstances.length; processingInstances.push(processing) }; function computeFontMetrics(pfont) { var emQuad = 250, correctionFactor = pfont.size / emQuad, canvas = document.createElement("canvas"); canvas.width = 2 * emQuad; canvas.height = 2 * emQuad; canvas.style.opacity = 0; var cfmFont = pfont.getCSSDefinition(emQuad + "px", "normal"), ctx = canvas.getContext("2d"); ctx.font = cfmFont; var protrusions = "dbflkhyjqpg"; canvas.width = ctx.measureText(protrusions).width; ctx.font = cfmFont; var leadDiv = document.createElement("div"); leadDiv.style.position = "absolute"; leadDiv.style.opacity = 0; leadDiv.style.fontFamily = '"' + pfont.name + '"'; leadDiv.style.fontSize = emQuad + "px"; leadDiv.innerHTML = protrusions + "<br/>" + protrusions; document.body.appendChild(leadDiv); var w = canvas.width, h = canvas.height, baseline = h / 2; ctx.fillStyle = "white"; ctx.fillRect(0, 0, w, h); ctx.fillStyle = "black"; ctx.fillText(protrusions, 0, baseline); var pixelData = ctx.getImageData(0, 0, w, h).data; var i = 0, w4 = w * 4, len = pixelData.length; while (++i < len && pixelData[i] === 255) nop(); var ascent = Math.round(i / w4); i = len - 1; while (--i > 0 && pixelData[i] === 255) nop(); var descent = Math.round(i / w4); pfont.ascent = correctionFactor * (baseline - ascent); pfont.descent = correctionFactor * (descent - baseline); if (document.defaultView.getComputedStyle) { var leadDivHeight = document.defaultView.getComputedStyle(leadDiv, null).getPropertyValue("height"); leadDivHeight = correctionFactor * leadDivHeight.replace("px", ""); if (leadDivHeight >= pfont.size * 2) pfont.leading = Math.round(leadDivHeight / 2) } document.body.removeChild(leadDiv); if (pfont.caching) return ctx } function PFont(name, size) { if (name === undef) name = ""; this.name = name; if (size === undef) size = 0; this.size = size; this.glyph = false; this.ascent = 0; this.descent = 0; this.leading = 1.2 * size; var illegalIndicator = name.indexOf(" Italic Bold"); if (illegalIndicator !== -1) name = name.substring(0, illegalIndicator); this.style = "normal"; var italicsIndicator = name.indexOf(" Italic"); if (italicsIndicator !== -1) { name = name.substring(0, italicsIndicator); this.style = "italic" } this.weight = "normal"; var boldIndicator = name.indexOf(" Bold"); if (boldIndicator !== -1) { name = name.substring(0, boldIndicator); this.weight = "bold" } this.family = "sans-serif"; if (name !== undef) switch (name) { case "sans-serif": case "serif": case "monospace": case "fantasy": case "cursive": this.family = name; break; default: this.family = '"' + name + '", sans-serif'; break } this.context2d = computeFontMetrics(this); this.css = this.getCSSDefinition(); if (this.context2d) this.context2d.font = this.css } PFont.prototype.caching = true; PFont.prototype.getCSSDefinition = function(fontSize, lineHeight) { if (fontSize === undef) fontSize = this.size + "px"; if (lineHeight === undef) lineHeight = this.leading + "px"; var components = [this.style, "normal", this.weight, fontSize + "/" + lineHeight, this.family]; return components.join(" ") }; PFont.prototype.measureTextWidth = function(string) { return this.context2d.measureText(string).width }; PFont.prototype.measureTextWidthFallback = function(string) { var canvas = document.createElement("canvas"), ctx = canvas.getContext("2d"); ctx.font = this.css; return ctx.measureText(string).width }; PFont.PFontCache = { length: 0 }; PFont.get = function(fontName, fontSize) { fontSize = (fontSize * 10 + 0.5 | 0) / 10; var cache = PFont.PFontCache, idx = fontName + "/" + fontSize; if (!cache[idx]) { cache[idx] = new PFont(fontName, fontSize); cache.length++; if (cache.length === 50) { PFont.prototype.measureTextWidth = PFont.prototype.measureTextWidthFallback; PFont.prototype.caching = false; var entry; for (entry in cache) if (entry !== "length") cache[entry].context2d = null; return new PFont(fontName, fontSize) } if (cache.length === 400) { PFont.PFontCache = {}; PFont.get = PFont.getFallback; return new PFont(fontName, fontSize) } } return cache[idx] }; PFont.getFallback = function(fontName, fontSize) { return new PFont(fontName, fontSize) }; PFont.list = function() { return ["sans-serif", "serif", "monospace", "fantasy", "cursive"] }; PFont.preloading = { template: {}, initialized: false, initialize: function() { var generateTinyFont = function() { var encoded = "#E3KAI2wAgT1MvMg7Eo3VmNtYX7ABi3CxnbHlm" + "7Abw3kaGVhZ7ACs3OGhoZWE7A53CRobXR47AY3" + "AGbG9jYQ7G03Bm1heH7ABC3CBuYW1l7Ae3AgcG" + "9zd7AI3AE#B3AQ2kgTY18PPPUACwAg3ALSRoo3" + "#yld0xg32QAB77#E777773B#E3C#I#Q77773E#" + "Q7777777772CMAIw7AB77732B#M#Q3wAB#g3B#" + "E#E2BB//82BB////w#B7#gAEg3E77x2B32B#E#" + "Q#MTcBAQ32gAe#M#QQJ#E32M#QQJ#I#g32Q77#"; var expand = function(input) { return "AAAAAAAA".substr(~~input ? 7 - input : 6) }; return encoded.replace(/[#237]/g, expand) }; var fontface = document.createElement("style"); fontface.setAttribute("type", "text/css"); fontface.innerHTML = "@font-face {\n" + ' font-family: "PjsEmptyFont";' + "\n" + " src: url('data:application/x-font-ttf;base64," + generateTinyFont() + "')\n" + " format('truetype');\n" + "}"; document.head.appendChild(fontface); var element = document.createElement("span"); element.style.cssText = 'position: absolute; top: 0; left: 0; opacity: 0; font-family: "PjsEmptyFont", fantasy;'; element.innerHTML = "AAAAAAAA"; document.body.appendChild(element); this.template = element; this.initialized = true }, getElementWidth: function(element) { return document.defaultView.getComputedStyle(element, "").getPropertyValue("width") }, timeAttempted: 0, pending: function(intervallength) { if (!this.initialized) this.initialize(); var element, computedWidthFont, computedWidthRef = this.getElementWidth(this.template); for (var i = 0; i < this.fontList.length; i++) { element = this.fontList[i]; computedWidthFont = this.getElementWidth(element); if (this.timeAttempted < 4E3 && computedWidthFont === computedWidthRef) { this.timeAttempted += intervallength; return true } else { document.body.removeChild(element); this.fontList.splice(i--, 1); this.timeAttempted = 0 } } if (this.fontList.length === 0) return false; return true }, fontList: [], addedList: {}, add: function(fontSrc) { if (!this.initialized) this.initialize(); var fontName = typeof fontSrc === "object" ? fontSrc.fontFace : fontSrc, fontUrl = typeof fontSrc === "object" ? fontSrc.url : fontSrc; if (this.addedList[fontName]) return; var style = document.createElement("style"); style.setAttribute("type", "text/css"); style.innerHTML = "@font-face{\n font-family: '" + fontName + "';\n src: url('" + fontUrl + "');\n}\n"; document.head.appendChild(style); this.addedList[fontName] = true; var element = document.createElement("span"); element.style.cssText = "position: absolute; top: 0; left: 0; opacity: 0;"; element.style.fontFamily = '"' + fontName + '", "PjsEmptyFont", fantasy'; element.innerHTML = "AAAAAAAA"; document.body.appendChild(element); this.fontList.push(element) } }; defaultScope.PFont = PFont; var Processing = this.Processing = function(aCanvas, aCode) { if (! (this instanceof Processing)) throw "called Processing constructor as if it were a function: missing 'new'."; var curElement, pgraphicsMode = aCanvas === undef && aCode === undef; if (pgraphicsMode) curElement = document.createElement("canvas"); else curElement = typeof aCanvas === "string" ? document.getElementById(aCanvas) : aCanvas; if (! (curElement instanceof HTMLCanvasElement)) throw "called Processing constructor without passing canvas element reference or id."; function unimplemented(s) { Processing.debug("Unimplemented - " + s) } var p = this; p.externals = { canvas: curElement, context: undef, sketch: undef }; p.name = "Processing.js Instance"; p.use3DContext = false; p.focused = false; p.breakShape = false; p.glyphTable = {}; p.pmouseX = 0; p.pmouseY = 0; p.mouseX = 0; p.mouseY = 0; p.mouseButton = 0; p.mouseScroll = 0; p.mouseClicked = undef; p.mouseDragged = undef; p.mouseMoved = undef; p.mousePressed = undef; p.mouseReleased = undef; p.mouseScrolled = undef; p.mouseOver = undef; p.mouseOut = undef; p.touchStart = undef; p.touchEnd = undef; p.touchMove = undef; p.touchCancel = undef; p.key = undef; p.keyCode = undef; p.keyPressed = nop; p.keyReleased = nop; p.keyTyped = nop; p.draw = undef; p.setup = undef; p.__mousePressed = false; p.__keyPressed = false; p.__frameRate = 60; p.frameCount = 0; p.width = 100; p.height = 100; var curContext, curSketch, drawing, online = true, doFill = true, fillStyle = [1, 1, 1, 1], currentFillColor = 4294967295, isFillDirty = true, doStroke = true, strokeStyle = [0, 0, 0, 1], currentStrokeColor = 4278190080, isStrokeDirty = true, lineWidth = 1, loopStarted = false, renderSmooth = false, doLoop = true, looping = 0, curRectMode = 0, curEllipseMode = 3, normalX = 0, normalY = 0, normalZ = 0, normalMode = 0, curFrameRate = 60, curMsPerFrame = 1E3 / curFrameRate, curCursor = 'default', oldCursor = curElement.style.cursor, curShape = 20, curShapeCount = 0, curvePoints = [], curTightness = 0, curveDet = 20, curveInited = false, backgroundObj = -3355444, bezDetail = 20, colorModeA = 255, colorModeX = 255, colorModeY = 255, colorModeZ = 255, pathOpen = false, mouseDragging = false, pmouseXLastFrame = 0, pmouseYLastFrame = 0, curColorMode = 1, curTint = null, curTint3d = null, getLoaded = false, start = Date.now(), timeSinceLastFPS = start, framesSinceLastFPS = 0, textcanvas, curveBasisMatrix, curveToBezierMatrix, curveDrawMatrix, bezierDrawMatrix, bezierBasisInverse, bezierBasisMatrix, curContextCache = { attributes: {}, locations: {} }, programObject3D, programObject2D, programObjectUnlitShape, boxBuffer, boxNormBuffer, boxOutlineBuffer, rectBuffer, rectNormBuffer, sphereBuffer, lineBuffer, fillBuffer, fillColorBuffer, strokeColorBuffer, pointBuffer, shapeTexVBO, canTex, textTex, curTexture = { width: 0, height: 0 }, curTextureMode = 2, usingTexture = false, textBuffer, textureBuffer, indexBuffer, horizontalTextAlignment = 37, verticalTextAlignment = 0, textMode = 4, curFontName = "Arial", curTextSize = 12, curTextAscent = 9, curTextDescent = 2, curTextLeading = 14, curTextFont = PFont.get(curFontName, curTextSize), originalContext, proxyContext = null, isContextReplaced = false, setPixelsCached, maxPixelsCached = 1E3, pressedKeysMap = [], lastPressedKeyCode = null, codedKeys = [16, 17, 18, 20, 33, 34, 35, 36, 37, 38, 39, 40, 144, 155, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 157]; var stylePaddingLeft, stylePaddingTop, styleBorderLeft, styleBorderTop; if (document.defaultView && document.defaultView.getComputedStyle) { stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(curElement, null)["paddingLeft"], 10) || 0; stylePaddingTop = parseInt(document.defaultView.getComputedStyle(curElement, null)["paddingTop"], 10) || 0; styleBorderLeft = parseInt(document.defaultView.getComputedStyle(curElement, null)["borderLeftWidth"], 10) || 0; styleBorderTop = parseInt(document.defaultView.getComputedStyle(curElement, null)["borderTopWidth"], 10) || 0 } var lightCount = 0; var sphereDetailV = 0, sphereDetailU = 0, sphereX = [], sphereY = [], sphereZ = [], sinLUT = new Float32Array(720), cosLUT = new Float32Array(720), sphereVerts, sphereNorms; var cam, cameraInv, modelView, modelViewInv, userMatrixStack, userReverseMatrixStack, inverseCopy, projection, manipulatingCamera = false, frustumMode = false, cameraFOV = 60 * (Math.PI / 180), cameraX = p.width / 2, cameraY = p.height / 2, cameraZ = cameraY / Math.tan(cameraFOV / 2), cameraNear = cameraZ / 10, cameraFar = cameraZ * 10, cameraAspect = p.width / p.height; var vertArray = [], curveVertArray = [], curveVertCount = 0, isCurve = false, isBezier = false, firstVert = true; var curShapeMode = 0; var styleArray = []; var boxVerts = new Float32Array([0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5]); var boxOutlineVerts = new Float32Array([0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5]); var boxNorms = new Float32Array([0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]); var rectVerts = new Float32Array([0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0]); var rectNorms = new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]); var vertexShaderSrcUnlitShape = "varying vec4 vFrontColor;" + "attribute vec3 aVertex;" + "attribute vec4 aColor;" + "uniform mat4 uView;" + "uniform mat4 uProjection;" + "uniform float uPointSize;" + "void main(void) {" + " vFrontColor = aColor;" + " gl_PointSize = uPointSize;" + " gl_Position = uProjection * uView * vec4(aVertex, 1.0);" + "}"; var fragmentShaderSrcUnlitShape = "#ifdef GL_ES\n" + "precision highp float;\n" + "#endif\n" + "varying vec4 vFrontColor;" + "uniform bool uSmooth;" + "void main(void){" + " if(uSmooth == true){" + " float dist = distance(gl_PointCoord, vec2(0.5));" + " if(dist > 0.5){" + " discard;" + " }" + " }" + " gl_FragColor = vFrontColor;" + "}"; var vertexShaderSrc2D = "varying vec4 vFrontColor;" + "attribute vec3 aVertex;" + "attribute vec2 aTextureCoord;" + "uniform vec4 uColor;" + "uniform mat4 uModel;" + "uniform mat4 uView;" + "uniform mat4 uProjection;" + "uniform float uPointSize;" + "varying vec2 vTextureCoord;" + "void main(void) {" + " gl_PointSize = uPointSize;" + " vFrontColor = uColor;" + " gl_Position = uProjection * uView * uModel * vec4(aVertex, 1.0);" + " vTextureCoord = aTextureCoord;" + "}"; var fragmentShaderSrc2D = "#ifdef GL_ES\n" + "precision highp float;\n" + "#endif\n" + "varying vec4 vFrontColor;" + "varying vec2 vTextureCoord;" + "uniform sampler2D uSampler;" + "uniform int uIsDrawingText;" + "uniform bool uSmooth;" + "void main(void){" + " if(uSmooth == true){" + " float dist = distance(gl_PointCoord, vec2(0.5));" + " if(dist > 0.5){" + " discard;" + " }" + " }" + " if(uIsDrawingText == 1){" + " float alpha = texture2D(uSampler, vTextureCoord).a;" + " gl_FragColor = vec4(vFrontColor.rgb * alpha, alpha);" + " }" + " else{" + " gl_FragColor = vFrontColor;" + " }" + "}"; var webglMaxTempsWorkaround = /Windows/.test(navigator.userAgent); var vertexShaderSrc3D = "varying vec4 vFrontColor;" + "attribute vec3 aVertex;" + "attribute vec3 aNormal;" + "attribute vec4 aColor;" + "attribute vec2 aTexture;" + "varying vec2 vTexture;" + "uniform vec4 uColor;" + "uniform bool uUsingMat;" + "uniform vec3 uSpecular;" + "uniform vec3 uMaterialEmissive;" + "uniform vec3 uMaterialAmbient;" + "uniform vec3 uMaterialSpecular;" + "uniform float uShininess;" + "uniform mat4 uModel;" + "uniform mat4 uView;" + "uniform mat4 uProjection;" + "uniform mat4 uNormalTransform;" + "uniform int uLightCount;" + "uniform vec3 uFalloff;" + "struct Light {" + " int type;" + " vec3 color;" + " vec3 position;" + " vec3 direction;" + " float angle;" + " vec3 halfVector;" + " float concentration;" + "};" + "uniform Light uLights0;" + "uniform Light uLights1;" + "uniform Light uLights2;" + "uniform Light uLights3;" + "uniform Light uLights4;" + "uniform Light uLights5;" + "uniform Light uLights6;" + "uniform Light uLights7;" + "Light getLight(int index){" + " if(index == 0) return uLights0;" + " if(index == 1) return uLights1;" + " if(index == 2) return uLights2;" + " if(index == 3) return uLights3;" + " if(index == 4) return uLights4;" + " if(index == 5) return uLights5;" + " if(index == 6) return uLights6;" + " return uLights7;" + "}" + "void AmbientLight( inout vec3 totalAmbient, in vec3 ecPos, in Light light ) {" + " float d = length( light.position - ecPos );" + " float attenuation = 1.0 / ( uFalloff[0] + ( uFalloff[1] * d ) + ( uFalloff[2] * d * d ));" + " totalAmbient += light.color * attenuation;" + "}" + "void DirectionalLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in Light light ) {" + " float powerFactor = 0.0;" + " float nDotVP = max(0.0, dot( vertNormal, normalize(-light.position) ));" + " float nDotVH = max(0.0, dot( vertNormal, normalize(-light.position-normalize(ecPos) )));" + " if( nDotVP != 0.0 ){" + " powerFactor = pow( nDotVH, uShininess );" + " }" + " col += light.color * nDotVP;" + " spec += uSpecular * powerFactor;" + "}" + "void PointLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in Light light ) {" + " float powerFactor;" + " vec3 VP = light.position - ecPos;" + " float d = length( VP ); " + " VP = normalize( VP );" + " float attenuation = 1.0 / ( uFalloff[0] + ( uFalloff[1] * d ) + ( uFalloff[2] * d * d ));" + " float nDotVP = max( 0.0, dot( vertNormal, VP ));" + " vec3 halfVector = normalize( VP - normalize(ecPos) );" + " float nDotHV = max( 0.0, dot( vertNormal, halfVector ));" + " if( nDotVP == 0.0 ) {" + " powerFactor = 0.0;" + " }" + " else {" + " powerFactor = pow( nDotHV, uShininess );" + " }" + " spec += uSpecular * powerFactor * attenuation;" + " col += light.color * nDotVP * attenuation;" + "}" + "void SpotLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in Light light ) {" + " float spotAttenuation;" + " float powerFactor = 0.0;" + " vec3 VP = light.position - ecPos;" + " vec3 ldir = normalize( -light.direction );" + " float d = length( VP );" + " VP = normalize( VP );" + " float attenuation = 1.0 / ( uFalloff[0] + ( uFalloff[1] * d ) + ( uFalloff[2] * d * d ) );" + " float spotDot = dot( VP, ldir );" + (webglMaxTempsWorkaround ? " spotAttenuation = 1.0; " : " if( spotDot > cos( light.angle ) ) {" + " spotAttenuation = pow( spotDot, light.concentration );" + " }" + " else{" + " spotAttenuation = 0.0;" + " }" + " attenuation *= spotAttenuation;" + "") + " float nDotVP = max( 0.0, dot( vertNormal, VP ) );" + " vec3 halfVector = normalize( VP - normalize(ecPos) );" + " float nDotHV = max( 0.0, dot( vertNormal, halfVector ) );" + " if( nDotVP != 0.0 ) {" + " powerFactor = pow( nDotHV, uShininess );" + " }" + " spec += uSpecular * powerFactor * attenuation;" + " col += light.color * nDotVP * attenuation;" + "}" + "void main(void) {" + " vec3 finalAmbient = vec3( 0.0 );" + " vec3 finalDiffuse = vec3( 0.0 );" + " vec3 finalSpecular = vec3( 0.0 );" + " vec4 col = uColor;" + " if ( uColor[0] == -1.0 ){" + " col = aColor;" + " }" + " vec3 norm = normalize(vec3( uNormalTransform * vec4( aNormal, 0.0 ) ));" + " vec4 ecPos4 = uView * uModel * vec4(aVertex, 1.0);" + " vec3 ecPos = (vec3(ecPos4))/ecPos4.w;" + " if( uLightCount == 0 ) {" + " vFrontColor = col + vec4(uMaterialSpecular, 1.0);" + " }" + " else {" + " for( int i = 0; i < 8; i++ ) {" + " Light l = getLight(i);" + " if( i >= uLightCount ){" + " break;" + " }" + " if( l.type == 0 ) {" + " AmbientLight( finalAmbient, ecPos, l );" + " }" + " else if( l.type == 1 ) {" + " DirectionalLight( finalDiffuse, finalSpecular, norm, ecPos, l );" + " }" + " else if( l.type == 2 ) {" + " PointLight( finalDiffuse, finalSpecular, norm, ecPos, l );" + " }" + " else {" + " SpotLight( finalDiffuse, finalSpecular, norm, ecPos, l );" + " }" + " }" + " if( uUsingMat == false ) {" + " vFrontColor = vec4(" + " vec3( col ) * finalAmbient +" + " vec3( col ) * finalDiffuse +" + " vec3( col ) * finalSpecular," + " col[3] );" + " }" + " else{" + " vFrontColor = vec4( " + " uMaterialEmissive + " + " (vec3(col) * uMaterialAmbient * finalAmbient ) + " + " (vec3(col) * finalDiffuse) + " + " (uMaterialSpecular * finalSpecular), " + " col[3] );" + " }" + " }" + " vTexture.xy = aTexture.xy;" + " gl_Position = uProjection * uView * uModel * vec4( aVertex, 1.0 );" + "}"; var fragmentShaderSrc3D = "#ifdef GL_ES\n" + "precision highp float;\n" + "#endif\n" + "varying vec4 vFrontColor;" + "uniform sampler2D uSampler;" + "uniform bool uUsingTexture;" + "varying vec2 vTexture;" + "void main(void){" + " if( uUsingTexture ){" + " gl_FragColor = vec4(texture2D(uSampler, vTexture.xy)) * vFrontColor;" + " }" + " else{" + " gl_FragColor = vFrontColor;" + " }" + "}"; function uniformf(cacheId, programObj, varName, varValue) { var varLocation = curContextCache.locations[cacheId]; if (varLocation === undef) { varLocation = curContext.getUniformLocation(programObj, varName); curContextCache.locations[cacheId] = varLocation } if (varLocation !== null) if (varValue.length === 4) curContext.uniform4fv(varLocation, varValue); else if (varValue.length === 3) curContext.uniform3fv(varLocation, varValue); else if (varValue.length === 2) curContext.uniform2fv(varLocation, varValue); else curContext.uniform1f(varLocation, varValue) } function uniformi(cacheId, programObj, varName, varValue) { var varLocation = curContextCache.locations[cacheId]; if (varLocation === undef) { varLocation = curContext.getUniformLocation(programObj, varName); curContextCache.locations[cacheId] = varLocation } if (varLocation !== null) if (varValue.length === 4) curContext.uniform4iv(varLocation, varValue); else if (varValue.length === 3) curContext.uniform3iv(varLocation, varValue); else if (varValue.length === 2) curContext.uniform2iv(varLocation, varValue); else curContext.uniform1i(varLocation, varValue) } function uniformMatrix(cacheId, programObj, varName, transpose, matrix) { var varLocation = curContextCache.locations[cacheId]; if (varLocation === undef) { varLocation = curContext.getUniformLocation(programObj, varName); curContextCache.locations[cacheId] = varLocation } if (varLocation !== -1) if (matrix.length === 16) curContext.uniformMatrix4fv(varLocation, transpose, matrix); else if (matrix.length === 9) curContext.uniformMatrix3fv(varLocation, transpose, matrix); else curContext.uniformMatrix2fv(varLocation, transpose, matrix) } function vertexAttribPointer(cacheId, programObj, varName, size, VBO) { var varLocation = curContextCache.attributes[cacheId]; if (varLocation === undef) { varLocation = curContext.getAttribLocation(programObj, varName); curContextCache.attributes[cacheId] = varLocation } if (varLocation !== -1) { curContext.bindBuffer(curContext.ARRAY_BUFFER, VBO); curContext.vertexAttribPointer(varLocation, size, curContext.FLOAT, false, 0, 0); curContext.enableVertexAttribArray(varLocation) } } function disableVertexAttribPointer(cacheId, programObj, varName) { var varLocation = curContextCache.attributes[cacheId]; if (varLocation === undef) { varLocation = curContext.getAttribLocation(programObj, varName); curContextCache.attributes[cacheId] = varLocation } if (varLocation !== -1) curContext.disableVertexAttribArray(varLocation) } var createProgramObject = function(curContext, vetexShaderSource, fragmentShaderSource) { var vertexShaderObject = curContext.createShader(curContext.VERTEX_SHADER); curContext.shaderSource(vertexShaderObject, vetexShaderSource); curContext.compileShader(vertexShaderObject); if (!curContext.getShaderParameter(vertexShaderObject, curContext.COMPILE_STATUS)) throw curContext.getShaderInfoLog(vertexShaderObject); var fragmentShaderObject = curContext.createShader(curContext.FRAGMENT_SHADER); curContext.shaderSource(fragmentShaderObject, fragmentShaderSource); curContext.compileShader(fragmentShaderObject); if (!curContext.getShaderParameter(fragmentShaderObject, curContext.COMPILE_STATUS)) throw curContext.getShaderInfoLog(fragmentShaderObject); var programObject = curContext.createProgram(); curContext.attachShader(programObject, vertexShaderObject); curContext.attachShader(programObject, fragmentShaderObject); curContext.linkProgram(programObject); if (!curContext.getProgramParameter(programObject, curContext.LINK_STATUS)) throw "Error linking shaders."; return programObject }; var imageModeCorner = function(x, y, w, h, whAreSizes) { return { x: x, y: y, w: w, h: h } }; var imageModeConvert = imageModeCorner; var imageModeCorners = function(x, y, w, h, whAreSizes) { return { x: x, y: y, w: whAreSizes ? w : w - x, h: whAreSizes ? h : h - y } }; var imageModeCenter = function(x, y, w, h, whAreSizes) { return { x: x - w / 2, y: y - h / 2, w: w, h: h } }; var DrawingShared = function() {}; var Drawing2D = function() {}; var Drawing3D = function() {}; var DrawingPre = function() {}; Drawing2D.prototype = new DrawingShared; Drawing2D.prototype.constructor = Drawing2D; Drawing3D.prototype = new DrawingShared; Drawing3D.prototype.constructor = Drawing3D; DrawingPre.prototype = new DrawingShared; DrawingPre.prototype.constructor = DrawingPre; DrawingShared.prototype.a3DOnlyFunction = nop; var charMap = {}; var Char = p.Character = function(chr) { if (typeof chr === "string" && chr.length === 1) this.code = chr.charCodeAt(0); else if (typeof chr === "number") this.code = chr; else if (chr instanceof Char) this.code = chr; else this.code = NaN; return charMap[this.code] === undef ? charMap[this.code] = this : charMap[this.code] }; Char.prototype.toString = function() { return String.fromCharCode(this.code) }; Char.prototype.valueOf = function() { return this.code }; var PShape = p.PShape = function(family) { this.family = family || 0; this.visible = true; this.style = true; this.children = []; this.nameTable = []; this.params = []; this.name = ""; this.image = null; this.matrix = null; this.kind = null; this.close = null; this.width = null; this.height = null; this.parent = null }; PShape.prototype = { isVisible: function() { return this.visible }, setVisible: function(visible) { this.visible = visible }, disableStyle: function() { this.style = false; for (var i = 0, j = this.children.length; i < j; i++) this.children[i].disableStyle() }, enableStyle: function() { this.style = true; for (var i = 0, j = this.children.length; i < j; i++) this.children[i].enableStyle() }, getFamily: function() { return this.family }, getWidth: function() { return this.width }, getHeight: function() { return this.height }, setName: function(name) { this.name = name }, getName: function() { return this.name }, draw: function(renderContext) { renderContext = renderContext || p; if (this.visible) { this.pre(renderContext); this.drawImpl(renderContext); this.post(renderContext) } }, drawImpl: function(renderContext) { if (this.family === 0) this.drawGroup(renderContext); else if (this.family === 1) this.drawPrimitive(renderContext); else if (this.family === 3) this.drawGeometry(renderContext); else if (this.family === 21) this.drawPath(renderContext) }, drawPath: function(renderContext) { var i, j; if (this.vertices.length === 0) return; renderContext.beginShape(); if (this.vertexCodes.length === 0) if (this.vertices[0].length === 2) for (i = 0, j = this.vertices.length; i < j; i++) renderContext.vertex(this.vertices[i][0], this.vertices[i][1]); else for (i = 0, j = this.vertices.length; i < j; i++) renderContext.vertex(this.vertices[i][0], this.vertices[i][1], this.vertices[i][2]); else { var index = 0; if (this.vertices[0].length === 2) for (i = 0, j = this.vertexCodes.length; i < j; i++) if (this.vertexCodes[i] === 0) { renderContext.vertex(this.vertices[index][0], this.vertices[index][1], this.vertices[index]["moveTo"]); renderContext.breakShape = false; index++ } else if (this.vertexCodes[i] === 1) { renderContext.bezierVertex(this.vertices[index + 0][0], this.vertices[index + 0][1], this.vertices[index + 1][0], this.vertices[index + 1][1], this.vertices[index + 2][0], this.vertices[index + 2][1]); index += 3 } else if (this.vertexCodes[i] === 2) { renderContext.curveVertex(this.vertices[index][0], this.vertices[index][1]); index++ } else { if (this.vertexCodes[i] === 3) renderContext.breakShape = true } else for (i = 0, j = this.vertexCodes.length; i < j; i++) if (this.vertexCodes[i] === 0) { renderContext.vertex(this.vertices[index][0], this.vertices[index][1], this.vertices[index][2]); if (this.vertices[index]["moveTo"] === true) vertArray[vertArray.length - 1]["moveTo"] = true; else if (this.vertices[index]["moveTo"] === false) vertArray[vertArray.length - 1]["moveTo"] = false; renderContext.breakShape = false } else if (this.vertexCodes[i] === 1) { renderContext.bezierVertex(this.vertices[index + 0][0], this.vertices[index + 0][1], this.vertices[index + 0][2], this.vertices[index + 1][0], this.vertices[index + 1][1], this.vertices[index + 1][2], this.vertices[index + 2][0], this.vertices[index + 2][1], this.vertices[index + 2][2]); index += 3 } else if (this.vertexCodes[i] === 2) { renderContext.curveVertex(this.vertices[index][0], this.vertices[index][1], this.vertices[index][2]); index++ } else if (this.vertexCodes[i] === 3) renderContext.breakShape = true } renderContext.endShape(this.close ? 2 : 1) }, drawGeometry: function(renderContext) { var i, j; renderContext.beginShape(this.kind); if (this.style) for (i = 0, j = this.vertices.length; i < j; i++) renderContext.vertex(this.vertices[i]); else for (i = 0, j = this.vertices.length; i < j; i++) { var vert = this.vertices[i]; if (vert[2] === 0) renderContext.vertex(vert[0], vert[1]); else renderContext.vertex(vert[0], vert[1], vert[2]) } renderContext.endShape() }, drawGroup: function(renderContext) { for (var i = 0, j = this.children.length; i < j; i++) this.children[i].draw(renderContext) }, drawPrimitive: function(renderContext) { if (this.kind === 2) renderContext.point(this.params[0], this.params[1]); else if (this.kind === 4) if (this.params.length === 4) renderContext.line(this.params[0], this.params[1], this.params[2], this.params[3]); else renderContext.line(this.params[0], this.params[1], this.params[2], this.params[3], this.params[4], this.params[5]); else if (this.kind === 8) renderContext.triangle(this.params[0], this.params[1], this.params[2], this.params[3], this.params[4], this.params[5]); else if (this.kind === 16) renderContext.quad(this.params[0], this.params[1], this.params[2], this.params[3], this.params[4], this.params[5], this.params[6], this.params[7]); else if (this.kind === 30) if (this.image !== null) { var imMode = imageModeConvert; renderContext.imageMode(0); renderContext.image(this.image, this.params[0], this.params[1], this.params[2], this.params[3]); imageModeConvert = imMode } else { var rcMode = curRectMode; renderContext.rectMode(0); renderContext.rect(this.params[0], this.params[1], this.params[2], this.params[3]); curRectMode = rcMode } else if (this.kind === 31) { var elMode = curEllipseMode; renderContext.ellipseMode(0); renderContext.ellipse(this.params[0], this.params[1], this.params[2], this.params[3]); curEllipseMode = elMode } else if (this.kind === 32) { var eMode = curEllipseMode; renderContext.ellipseMode(0); renderContext.arc(this.params[0], this.params[1], this.params[2], this.params[3], this.params[4], this.params[5]); curEllipseMode = eMode } else if (this.kind === 41) if (this.params.length === 1) renderContext.box(this.params[0]); else renderContext.box(this.params[0], this.params[1], this.params[2]); else if (this.kind === 40) renderContext.sphere(this.params[0]) }, pre: function(renderContext) { if (this.matrix) { renderContext.pushMatrix(); renderContext.transform(this.matrix) } if (this.style) { renderContext.pushStyle(); this.styles(renderContext) } }, post: function(renderContext) { if (this.matrix) renderContext.popMatrix(); if (this.style) renderContext.popStyle() }, styles: function(renderContext) { if (this.stroke) { renderContext.stroke(this.strokeColor); renderContext.strokeWeight(this.strokeWeight); renderContext.strokeCap(this.strokeCap); renderContext.strokeJoin(this.strokeJoin) } else renderContext.noStroke(); if (this.fill) renderContext.fill(this.fillColor); else renderContext.noFill() }, getChild: function(child) { var i, j; if (typeof child === "number") return this.children[child]; var found; if (child === "" || this.name === child) return this; if (this.nameTable.length > 0) { for (i = 0, j = this.nameTable.length; i < j || found; i++) if (this.nameTable[i].getName === child) { found = this.nameTable[i]; break } if (found) return found } for (i = 0, j = this.children.length; i < j; i++) { found = this.children[i].getChild(child); if (found) return found } return null }, getChildCount: function() { return this.children.length }, addChild: function(child) { this.children.push(child); child.parent = this; if (child.getName() !== null) this.addName(child.getName(), child) }, addName: function(name, shape) { if (this.parent !== null) this.parent.addName(name, shape); else this.nameTable.push([name, shape]) }, translate: function() { if (arguments.length === 2) { this.checkMatrix(2); this.matrix.translate(arguments[0], arguments[1]) } else { this.checkMatrix(3); this.matrix.translate(arguments[0], arguments[1], 0) } }, checkMatrix: function(dimensions) { if (this.matrix === null) if (dimensions === 2) this.matrix = new p.PMatrix2D; else this.matrix = new p.PMatrix3D; else if (dimensions === 3 && this.matrix instanceof p.PMatrix2D) this.matrix = new p.PMatrix3D }, rotateX: function(angle) { this.rotate(angle, 1, 0, 0) }, rotateY: function(angle) { this.rotate(angle, 0, 1, 0) }, rotateZ: function(angle) { this.rotate(angle, 0, 0, 1) }, rotate: function() { if (arguments.length === 1) { this.checkMatrix(2); this.matrix.rotate(arguments[0]) } else { this.checkMatrix(3); this.matrix.rotate(arguments[0], arguments[1], arguments[2], arguments[3]) } }, scale: function() { if (arguments.length === 2) { this.checkMatrix(2); this.matrix.scale(arguments[0], arguments[1]) } else if (arguments.length === 3) { this.checkMatrix(2); this.matrix.scale(arguments[0], arguments[1], arguments[2]) } else { this.checkMatrix(2); this.matrix.scale(arguments[0]) } }, resetMatrix: function() { this.checkMatrix(2); this.matrix.reset() }, applyMatrix: function(matrix) { if (arguments.length === 1) this.applyMatrix(matrix.elements[0], matrix.elements[1], 0, matrix.elements[2], matrix.elements[3], matrix.elements[4], 0, matrix.elements[5], 0, 0, 1, 0, 0, 0, 0, 1); else if (arguments.length === 6) { this.checkMatrix(2); this.matrix.apply(arguments[0], arguments[1], arguments[2], 0, arguments[3], arguments[4], arguments[5], 0, 0, 0, 1, 0, 0, 0, 0, 1) } else if (arguments.length === 16) { this.checkMatrix(3); this.matrix.apply(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], arguments[8], arguments[9], arguments[10], arguments[11], arguments[12], arguments[13], arguments[14], arguments[15]) } } }; var PShapeSVG = p.PShapeSVG = function() { p.PShape.call(this); if (arguments.length === 1) { this.element = arguments[0]; this.vertexCodes = []; this.vertices = []; this.opacity = 1; this.stroke = false; this.strokeColor = 4278190080; this.strokeWeight = 1; this.strokeCap = 'butt'; this.strokeJoin = 'miter'; this.strokeGradient = null; this.strokeGradientPaint = null; this.strokeName = null; this.strokeOpacity = 1; this.fill = true; this.fillColor = 4278190080; this.fillGradient = null; this.fillGradientPaint = null; this.fillName = null; this.fillOpacity = 1; if (this.element.getName() !== "svg") throw "root is not <svg>, it's <" + this.element.getName() + ">"; } else if (arguments.length === 2) if (typeof arguments[1] === "string") { if (arguments[1].indexOf(".svg") > -1) { this.element = new p.XMLElement(p, arguments[1]); this.vertexCodes = []; this.vertices = []; this.opacity = 1; this.stroke = false; this.strokeColor = 4278190080; this.strokeWeight = 1; this.strokeCap = 'butt'; this.strokeJoin = 'miter'; this.strokeGradient = ""; this.strokeGradientPaint = ""; this.strokeName = ""; this.strokeOpacity = 1; this.fill = true; this.fillColor = 4278190080; this.fillGradient = null; this.fillGradientPaint = null; this.fillOpacity = 1 } } else if (arguments[0]) { this.element = arguments[1]; this.vertexCodes = arguments[0].vertexCodes.slice(); this.vertices = arguments[0].vertices.slice(); this.stroke = arguments[0].stroke; this.strokeColor = arguments[0].strokeColor; this.strokeWeight = arguments[0].strokeWeight; this.strokeCap = arguments[0].strokeCap; this.strokeJoin = arguments[0].strokeJoin; this.strokeGradient = arguments[0].strokeGradient; this.strokeGradientPaint = arguments[0].strokeGradientPaint; this.strokeName = arguments[0].strokeName; this.fill = arguments[0].fill; this.fillColor = arguments[0].fillColor; this.fillGradient = arguments[0].fillGradient; this.fillGradientPaint = arguments[0].fillGradientPaint; this.fillName = arguments[0].fillName; this.strokeOpacity = arguments[0].strokeOpacity; this.fillOpacity = arguments[0].fillOpacity; this.opacity = arguments[0].opacity } this.name = this.element.getStringAttribute("id"); var displayStr = this.element.getStringAttribute("display", "inline"); this.visible = displayStr !== "none"; var str = this.element.getAttribute("transform"); if (str) this.matrix = this.parseMatrix(str); var viewBoxStr = this.element.getStringAttribute("viewBox"); if (viewBoxStr !== null) { var viewBox = viewBoxStr.split(" "); this.width = viewBox[2]; this.height = viewBox[3] } var unitWidth = this.element.getStringAttribute("width"); var unitHeight = this.element.getStringAttribute("height"); if (unitWidth !== null) { this.width = this.parseUnitSize(unitWidth); this.height = this.parseUnitSize(unitHeight) } else if (this.width === 0 || this.height === 0) { this.width = 1; this.height = 1; throw "The width and/or height is not " + "readable in the <svg> tag of this file."; } this.parseColors(this.element); this.parseChildren(this.element) }; PShapeSVG.prototype = new PShape; PShapeSVG.prototype.parseMatrix = function() { function getCoords(s) { var m = []; s.replace(/\((.*?)\)/, function() { return function(all, params) { m = params.replace(/,+/g, " ").split(/\s+/) } }()); return m } return function(str) { this.checkMatrix(2); var pieces = []; str.replace(/\s*(\w+)\((.*?)\)/g, function(all) { pieces.push(p.trim(all)) }); if (pieces.length === 0) return null; for (var i = 0, j = pieces.length; i < j; i++) { var m = getCoords(pieces[i]); if (pieces[i].indexOf("matrix") !== -1) this.matrix.set(m[0], m[2], m[4], m[1], m[3], m[5]); else if (pieces[i].indexOf("translate") !== -1) { var tx = m[0]; var ty = m.length === 2 ? m[1] : 0; this.matrix.translate(tx, ty) } else if (pieces[i].indexOf("scale") !== -1) { var sx = m[0]; var sy = m.length === 2 ? m[1] : m[0]; this.matrix.scale(sx, sy) } else if (pieces[i].indexOf("rotate") !== -1) { var angle = m[0]; if (m.length === 1) this.matrix.rotate(p.radians(angle)); else if (m.length === 3) { this.matrix.translate(m[1], m[2]); this.matrix.rotate(p.radians(m[0])); this.matrix.translate(-m[1], -m[2]) } } else if (pieces[i].indexOf("skewX") !== -1) this.matrix.skewX(parseFloat(m[0])); else if (pieces[i].indexOf("skewY") !== -1) this.matrix.skewY(m[0]); else if (pieces[i].indexOf("shearX") !== -1) this.matrix.shearX(m[0]); else if (pieces[i].indexOf("shearY") !== -1) this.matrix.shearY(m[0]) } return this.matrix } }(); PShapeSVG.prototype.parseChildren = function(element) { var newelement = element.getChildren(); var children = new p.PShape; for (var i = 0, j = newelement.length; i < j; i++) { var kid = this.parseChild(newelement[i]); if (kid) children.addChild(kid) } this.children.push(children) }; PShapeSVG.prototype.getName = function() { return this.name }; PShapeSVG.prototype.parseChild = function(elem) { var name = elem.getName(); var shape; if (name === "g") shape = new PShapeSVG(this, elem); else if (name === "defs") shape = new PShapeSVG(this, elem); else if (name === "line") { shape = new PShapeSVG(this, elem); shape.parseLine() } else if (name === "circle") { shape = new PShapeSVG(this, elem); shape.parseEllipse(true) } else if (name === "ellipse") { shape = new PShapeSVG(this, elem); shape.parseEllipse(false) } else if (name === "rect") { shape = new PShapeSVG(this, elem); shape.parseRect() } else if (name === "polygon") { shape = new PShapeSVG(this, elem); shape.parsePoly(true) } else if (name === "polyline") { shape = new PShapeSVG(this, elem); shape.parsePoly(false) } else if (name === "path") { shape = new PShapeSVG(this, elem); shape.parsePath() } else if (name === "radialGradient") unimplemented("PShapeSVG.prototype.parseChild, name = radialGradient"); else if (name === "linearGradient") unimplemented("PShapeSVG.prototype.parseChild, name = linearGradient"); else if (name === "text") unimplemented("PShapeSVG.prototype.parseChild, name = text"); else if (name === "filter") unimplemented("PShapeSVG.prototype.parseChild, name = filter"); else if (name === "mask") unimplemented("PShapeSVG.prototype.parseChild, name = mask"); else nop(); return shape }; PShapeSVG.prototype.parsePath = function() { this.family = 21; this.kind = 0; var pathDataChars = []; var c; var pathData = p.trim(this.element.getStringAttribute("d").replace(/[\s,]+/g, " ")); if (pathData === null) return; pathData = p.__toCharArray(pathData); var cx = 0, cy = 0, ctrlX = 0, ctrlY = 0, ctrlX1 = 0, ctrlX2 = 0, ctrlY1 = 0, ctrlY2 = 0, endX = 0, endY = 0, ppx = 0, ppy = 0, px = 0, py = 0, i = 0, valOf = 0; var str = ""; var tmpArray = []; var flag = false; var lastInstruction; var command; var j, k; while (i < pathData.length) { valOf = pathData[i].valueOf(); if (valOf >= 65 && valOf <= 90 || valOf >= 97 && valOf <= 122) { j = i; i++; if (i < pathData.length) { tmpArray = []; valOf = pathData[i].valueOf(); while (! (valOf >= 65 && valOf <= 90 || valOf >= 97 && valOf <= 100 || valOf >= 102 && valOf <= 122) && flag === false) { if (valOf === 32) { if (str !== "") { tmpArray.push(parseFloat(str)); str = "" } i++ } else if (valOf === 45) if (pathData[i - 1].valueOf() === 101) { str += pathData[i].toString(); i++ } else { if (str !== "") tmpArray.push(parseFloat(str)); str = pathData[i].toString(); i++ } else { str += pathData[i].toString(); i++ } if (i === pathData.length) flag = true; else valOf = pathData[i].valueOf() } } if (str !== "") { tmpArray.push(parseFloat(str)); str = "" } command = pathData[j]; valOf = command.valueOf(); if (valOf === 77) { if (tmpArray.length >= 2 && tmpArray.length % 2 === 0) { cx = tmpArray[0]; cy = tmpArray[1]; this.parsePathMoveto(cx, cy); if (tmpArray.length > 2) for (j = 2, k = tmpArray.length; j < k; j += 2) { cx = tmpArray[j]; cy = tmpArray[j + 1]; this.parsePathLineto(cx, cy) } } } else if (valOf === 109) { if (tmpArray.length >= 2 && tmpArray.length % 2 === 0) { cx += tmpArray[0]; cy += tmpArray[1]; this.parsePathMoveto(cx, cy); if (tmpArray.length > 2) for (j = 2, k = tmpArray.length; j < k; j += 2) { cx += tmpArray[j]; cy += tmpArray[j + 1]; this.parsePathLineto(cx, cy) } } } else if (valOf === 76) { if (tmpArray.length >= 2 && tmpArray.length % 2 === 0) for (j = 0, k = tmpArray.length; j < k; j += 2) { cx = tmpArray[j]; cy = tmpArray[j + 1]; this.parsePathLineto(cx, cy) } } else if (valOf === 108) { if (tmpArray.length >= 2 && tmpArray.length % 2 === 0) for (j = 0, k = tmpArray.length; j < k; j += 2) { cx += tmpArray[j]; cy += tmpArray[j + 1]; this.parsePathLineto(cx, cy) } } else if (valOf === 72) for (j = 0, k = tmpArray.length; j < k; j++) { cx = tmpArray[j]; this.parsePathLineto(cx, cy) } else if (valOf === 104) for (j = 0, k = tmpArray.length; j < k; j++) { cx += tmpArray[j]; this.parsePathLineto(cx, cy) } else if (valOf === 86) for (j = 0, k = tmpArray.length; j < k; j++) { cy = tmpArray[j]; this.parsePathLineto(cx, cy) } else if (valOf === 118) for (j = 0, k = tmpArray.length; j < k; j++) { cy += tmpArray[j]; this.parsePathLineto(cx, cy) } else if (valOf === 67) { if (tmpArray.length >= 6 && tmpArray.length % 6 === 0) for (j = 0, k = tmpArray.length; j < k; j += 6) { ctrlX1 = tmpArray[j]; ctrlY1 = tmpArray[j + 1]; ctrlX2 = tmpArray[j + 2]; ctrlY2 = tmpArray[j + 3]; endX = tmpArray[j + 4]; endY = tmpArray[j + 5]; this.parsePathCurveto(ctrlX1, ctrlY1, ctrlX2, ctrlY2, endX, endY); cx = endX; cy = endY } } else if (valOf === 99) { if (tmpArray.length >= 6 && tmpArray.length % 6 === 0) for (j = 0, k = tmpArray.length; j < k; j += 6) { ctrlX1 = cx + tmpArray[j]; ctrlY1 = cy + tmpArray[j + 1]; ctrlX2 = cx + tmpArray[j + 2]; ctrlY2 = cy + tmpArray[j + 3]; endX = cx + tmpArray[j + 4]; endY = cy + tmpArray[j + 5]; this.parsePathCurveto(ctrlX1, ctrlY1, ctrlX2, ctrlY2, endX, endY); cx = endX; cy = endY } } else if (valOf === 83) { if (tmpArray.length >= 4 && tmpArray.length % 4 === 0) for (j = 0, k = tmpArray.length; j < k; j += 4) { if (lastInstruction.toLowerCase() === "c" || lastInstruction.toLowerCase() === "s") { ppx = this.vertices[this.vertices.length - 2][0]; ppy = this.vertices[this.vertices.length - 2][1]; px = this.vertices[this.vertices.length - 1][0]; py = this.vertices[this.vertices.length - 1][1]; ctrlX1 = px + (px - ppx); ctrlY1 = py + (py - ppy) } else { ctrlX1 = this.vertices[this.vertices.length - 1][0]; ctrlY1 = this.vertices[this.vertices.length - 1][1] } ctrlX2 = tmpArray[j]; ctrlY2 = tmpArray[j + 1]; endX = tmpArray[j + 2]; endY = tmpArray[j + 3]; this.parsePathCurveto(ctrlX1, ctrlY1, ctrlX2, ctrlY2, endX, endY); cx = endX; cy = endY } } else if (valOf === 115) { if (tmpArray.length >= 4 && tmpArray.length % 4 === 0) for (j = 0, k = tmpArray.length; j < k; j += 4) { if (lastInstruction.toLowerCase() === "c" || lastInstruction.toLowerCase() === "s") { ppx = this.vertices[this.vertices.length - 2][0]; ppy = this.vertices[this.vertices.length - 2][1]; px = this.vertices[this.vertices.length - 1][0]; py = this.vertices[this.vertices.length - 1][1]; ctrlX1 = px + (px - ppx); ctrlY1 = py + (py - ppy) } else { ctrlX1 = this.vertices[this.vertices.length - 1][0]; ctrlY1 = this.vertices[this.vertices.length - 1][1] } ctrlX2 = cx + tmpArray[j]; ctrlY2 = cy + tmpArray[j + 1]; endX = cx + tmpArray[j + 2]; endY = cy + tmpArray[j + 3]; this.parsePathCurveto(ctrlX1, ctrlY1, ctrlX2, ctrlY2, endX, endY); cx = endX; cy = endY } } else if (valOf === 81) { if (tmpArray.length >= 4 && tmpArray.length % 4 === 0) for (j = 0, k = tmpArray.length; j < k; j += 4) { ctrlX = tmpArray[j]; ctrlY = tmpArray[j + 1]; endX = tmpArray[j + 2]; endY = tmpArray[j + 3]; this.parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); cx = endX; cy = endY } } else if (valOf === 113) { if (tmpArray.length >= 4 && tmpArray.length % 4 === 0) for (j = 0, k = tmpArray.length; j < k; j += 4) { ctrlX = cx + tmpArray[j]; ctrlY = cy + tmpArray[j + 1]; endX = cx + tmpArray[j + 2]; endY = cy + tmpArray[j + 3]; this.parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); cx = endX; cy = endY } } else if (valOf === 84) { if (tmpArray.length >= 2 && tmpArray.length % 2 === 0) for (j = 0, k = tmpArray.length; j < k; j += 2) { if (lastInstruction.toLowerCase() === "q" || lastInstruction.toLowerCase() === "t") { ppx = this.vertices[this.vertices.length - 2][0]; ppy = this.vertices[this.vertices.length - 2][1]; px = this.vertices[this.vertices.length - 1][0]; py = this.vertices[this.vertices.length - 1][1]; ctrlX = px + (px - ppx); ctrlY = py + (py - ppy) } else { ctrlX = cx; ctrlY = cy } endX = tmpArray[j]; endY = tmpArray[j + 1]; this.parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); cx = endX; cy = endY } } else if (valOf === 116) { if (tmpArray.length >= 2 && tmpArray.length % 2 === 0) for (j = 0, k = tmpArray.length; j < k; j += 2) { if (lastInstruction.toLowerCase() === "q" || lastInstruction.toLowerCase() === "t") { ppx = this.vertices[this.vertices.length - 2][0]; ppy = this.vertices[this.vertices.length - 2][1]; px = this.vertices[this.vertices.length - 1][0]; py = this.vertices[this.vertices.length - 1][1]; ctrlX = px + (px - ppx); ctrlY = py + (py - ppy) } else { ctrlX = cx; ctrlY = cy } endX = cx + tmpArray[j]; endY = cy + tmpArray[j + 1]; this.parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); cx = endX; cy = endY } } else if (valOf === 90 || valOf === 122) this.close = true; lastInstruction = command.toString() } else i++ } }; PShapeSVG.prototype.parsePathQuadto = function(x1, y1, cx, cy, x2, y2) { if (this.vertices.length > 0) { this.parsePathCode(1); this.parsePathVertex(x1 + (cx - x1) * 2 / 3, y1 + (cy - y1) * 2 / 3); this.parsePathVertex(x2 + (cx - x2) * 2 / 3, y2 + (cy - y2) * 2 / 3); this.parsePathVertex(x2, y2) } else throw "Path must start with M/m"; }; PShapeSVG.prototype.parsePathCurveto = function(x1, y1, x2, y2, x3, y3) { if (this.vertices.length > 0) { this.parsePathCode(1); this.parsePathVertex(x1, y1); this.parsePathVertex(x2, y2); this.parsePathVertex(x3, y3) } else throw "Path must start with M/m"; }; PShapeSVG.prototype.parsePathLineto = function(px, py) { if (this.vertices.length > 0) { this.parsePathCode(0); this.parsePathVertex(px, py); this.vertices[this.vertices.length - 1]["moveTo"] = false } else throw "Path must start with M/m"; }; PShapeSVG.prototype.parsePathMoveto = function(px, py) { if (this.vertices.length > 0) this.parsePathCode(3); this.parsePathCode(0); this.parsePathVertex(px, py); this.vertices[this.vertices.length - 1]["moveTo"] = true }; PShapeSVG.prototype.parsePathVertex = function(x, y) { var verts = []; verts[0] = x; verts[1] = y; this.vertices.push(verts) }; PShapeSVG.prototype.parsePathCode = function(what) { this.vertexCodes.push(what) }; PShapeSVG.prototype.parsePoly = function(val) { this.family = 21; this.close = val; var pointsAttr = p.trim(this.element.getStringAttribute("points").replace(/[,\s]+/g, " ")); if (pointsAttr !== null) { var pointsBuffer = pointsAttr.split(" "); if (pointsBuffer.length % 2 === 0) for (var i = 0, j = pointsBuffer.length; i < j; i++) { var verts = []; verts[0] = pointsBuffer[i]; verts[1] = pointsBuffer[++i]; this.vertices.push(verts) } else throw "Error parsing polygon points: odd number of coordinates provided"; } }; PShapeSVG.prototype.parseRect = function() { this.kind = 30; this.family = 1; this.params = []; this.params[0] = this.element.getFloatAttribute("x"); this.params[1] = this.element.getFloatAttribute("y"); this.params[2] = this.element.getFloatAttribute("width"); this.params[3] = this.element.getFloatAttribute("height"); if (this.params[2] < 0 || this.params[3] < 0) throw "svg error: negative width or height found while parsing <rect>"; }; PShapeSVG.prototype.parseEllipse = function(val) { this.kind = 31; this.family = 1; this.params = []; this.params[0] = this.element.getFloatAttribute("cx") | 0; this.params[1] = this.element.getFloatAttribute("cy") | 0; var rx, ry; if (val) { rx = ry = this.element.getFloatAttribute("r"); if (rx < 0) throw "svg error: negative radius found while parsing <circle>"; } else { rx = this.element.getFloatAttribute("rx"); ry = this.element.getFloatAttribute("ry"); if (rx < 0 || ry < 0) throw "svg error: negative x-axis radius or y-axis radius found while parsing <ellipse>"; } this.params[0] -= rx; this.params[1] -= ry; this.params[2] = rx * 2; this.params[3] = ry * 2 }; PShapeSVG.prototype.parseLine = function() { this.kind = 4; this.family = 1; this.params = []; this.params[0] = this.element.getFloatAttribute("x1"); this.params[1] = this.element.getFloatAttribute("y1"); this.params[2] = this.element.getFloatAttribute("x2"); this.params[3] = this.element.getFloatAttribute("y2") }; PShapeSVG.prototype.parseColors = function(element) { if (element.hasAttribute("opacity")) this.setOpacity(element.getAttribute("opacity")); if (element.hasAttribute("stroke")) this.setStroke(element.getAttribute("stroke")); if (element.hasAttribute("stroke-width")) this.setStrokeWeight(element.getAttribute("stroke-width")); if (element.hasAttribute("stroke-linejoin")) this.setStrokeJoin(element.getAttribute("stroke-linejoin")); if (element.hasAttribute("stroke-linecap")) this.setStrokeCap(element.getStringAttribute("stroke-linecap")); if (element.hasAttribute("fill")) this.setFill(element.getStringAttribute("fill")); if (element.hasAttribute("style")) { var styleText = element.getStringAttribute("style"); var styleTokens = styleText.toString().split(";"); for (var i = 0, j = styleTokens.length; i < j; i++) { var tokens = p.trim(styleTokens[i].split(":")); if (tokens[0] === "fill") this.setFill(tokens[1]); else if (tokens[0] === "fill-opacity") this.setFillOpacity(tokens[1]); else if (tokens[0] === "stroke") this.setStroke(tokens[1]); else if (tokens[0] === "stroke-width") this.setStrokeWeight(tokens[1]); else if (tokens[0] === "stroke-linecap") this.setStrokeCap(tokens[1]); else if (tokens[0] === "stroke-linejoin") this.setStrokeJoin(tokens[1]); else if (tokens[0] === "stroke-opacity") this.setStrokeOpacity(tokens[1]); else if (tokens[0] === "opacity") this.setOpacity(tokens[1]) } } }; PShapeSVG.prototype.setFillOpacity = function(opacityText) { this.fillOpacity = parseFloat(opacityText); this.fillColor = this.fillOpacity * 255 << 24 | this.fillColor & 16777215 }; PShapeSVG.prototype.setFill = function(fillText) { var opacityMask = this.fillColor & 4278190080; if (fillText === "none") this.fill = false; else if (fillText.indexOf("#") === 0) { this.fill = true; if (fillText.length === 4) fillText = fillText.replace(/#(.)(.)(.)/, "#$1$1$2$2$3$3"); this.fillColor = opacityMask | parseInt(fillText.substring(1), 16) & 16777215 } else if (fillText.indexOf("rgb") === 0) { this.fill = true; this.fillColor = opacityMask | this.parseRGB(fillText) } else if (fillText.indexOf("url(#") === 0) this.fillName = fillText.substring(5, fillText.length - 1); else if (colors[fillText]) { this.fill = true; this.fillColor = opacityMask | parseInt(colors[fillText].substring(1), 16) & 16777215 } }; PShapeSVG.prototype.setOpacity = function(opacity) { this.strokeColor = parseFloat(opacity) * 255 << 24 | this.strokeColor & 16777215; this.fillColor = parseFloat(opacity) * 255 << 24 | this.fillColor & 16777215 }; PShapeSVG.prototype.setStroke = function(strokeText) { var opacityMask = this.strokeColor & 4278190080; if (strokeText === "none") this.stroke = false; else if (strokeText.charAt(0) === "#") { this.stroke = true; if (strokeText.length === 4) strokeText = strokeText.replace(/#(.)(.)(.)/, "#$1$1$2$2$3$3"); this.strokeColor = opacityMask | parseInt(strokeText.substring(1), 16) & 16777215 } else if (strokeText.indexOf("rgb") === 0) { this.stroke = true; this.strokeColor = opacityMask | this.parseRGB(strokeText) } else if (strokeText.indexOf("url(#") === 0) this.strokeName = strokeText.substring(5, strokeText.length - 1); else if (colors[strokeText]) { this.stroke = true; this.strokeColor = opacityMask | parseInt(colors[strokeText].substring(1), 16) & 16777215 } }; PShapeSVG.prototype.setStrokeWeight = function(weight) { this.strokeWeight = this.parseUnitSize(weight) }; PShapeSVG.prototype.setStrokeJoin = function(linejoin) { if (linejoin === "miter") this.strokeJoin = 'miter'; else if (linejoin === "round") this.strokeJoin = 'round'; else if (linejoin === "bevel") this.strokeJoin = 'bevel' }; PShapeSVG.prototype.setStrokeCap = function(linecap) { if (linecap === "butt") this.strokeCap = 'butt'; else if (linecap === "round") this.strokeCap = 'round'; else if (linecap === "square") this.strokeCap = 'square' }; PShapeSVG.prototype.setStrokeOpacity = function(opacityText) { this.strokeOpacity = parseFloat(opacityText); this.strokeColor = this.strokeOpacity * 255 << 24 | this.strokeColor & 16777215 }; PShapeSVG.prototype.parseRGB = function(color) { var sub = color.substring(color.indexOf("(") + 1, color.indexOf(")")); var values = sub.split(", "); return values[0] << 16 | values[1] << 8 | values[2] }; PShapeSVG.prototype.parseUnitSize = function(text) { var len = text.length - 2; if (len < 0) return text; if (text.indexOf("pt") === len) return parseFloat(text.substring(0, len)) * 1.25; if (text.indexOf("pc") === len) return parseFloat(text.substring(0, len)) * 15; if (text.indexOf("mm") === len) return parseFloat(text.substring(0, len)) * 3.543307; if (text.indexOf("cm") === len) return parseFloat(text.substring(0, len)) * 35.43307; if (text.indexOf("in") === len) return parseFloat(text.substring(0, len)) * 90; if (text.indexOf("px") === len) return parseFloat(text.substring(0, len)); return parseFloat(text) }; p.shape = function(shape, x, y, width, height) { if (arguments.length >= 1 && arguments[0] !== null) if (shape.isVisible()) { p.pushMatrix(); if (curShapeMode === 3) if (arguments.length === 5) { p.translate(x - width / 2, y - height / 2); p.scale(width / shape.getWidth(), height / shape.getHeight()) } else if (arguments.length === 3) p.translate(x - shape.getWidth() / 2, -shape.getHeight() / 2); else p.translate(-shape.getWidth() / 2, -shape.getHeight() / 2); else if (curShapeMode === 0) if (arguments.length === 5) { p.translate(x, y); p.scale(width / shape.getWidth(), height / shape.getHeight()) } else { if (arguments.length === 3) p.translate(x, y) } else if (curShapeMode === 1) if (arguments.length === 5) { width -= x; height -= y; p.translate(x, y); p.scale(width / shape.getWidth(), height / shape.getHeight()) } else if (arguments.length === 3) p.translate(x, y); shape.draw(p); if (arguments.length === 1 && curShapeMode === 3 || arguments.length > 1) p.popMatrix() } }; p.shapeMode = function(mode) { curShapeMode = mode }; p.loadShape = function(filename) { if (arguments.length === 1) if (filename.indexOf(".svg") > -1) return new PShapeSVG(null, filename); return null }; var XMLAttribute = function(fname, n, nameSpace, v, t) { this.fullName = fname || ""; this.name = n || ""; this.namespace = nameSpace || ""; this.value = v; this.type = t }; XMLAttribute.prototype = { getName: function() { return this.name }, getFullName: function() { return this.fullName }, getNamespace: function() { return this.namespace }, getValue: function() { return this.value }, getType: function() { return this.type }, setValue: function(newval) { this.value = newval } }; var XMLElement = p.XMLElement = function(selector, uri, sysid, line) { this.attributes = []; this.children = []; this.fullName = null; this.name = null; this.namespace = ""; this.content = null; this.parent = null; this.lineNr = ""; this.systemID = ""; this.type = "ELEMENT"; if (selector) if (typeof selector === "string") if (uri === undef && selector.indexOf("<") > -1) this.parse(selector); else { this.fullName = selector; this.namespace = uri; this.systemId = sysid; this.lineNr = line } else this.parse(uri) }; XMLElement.prototype = { parse: function(textstring) { var xmlDoc; try { var extension = textstring.substring(textstring.length - 4); if (extension === ".xml" || extension === ".svg") textstring = ajax(textstring); xmlDoc = (new DOMParser).parseFromString(textstring, "text/xml"); var elements = xmlDoc.documentElement; if (elements) this.parseChildrenRecursive(null, elements); else throw "Error loading document"; return this } catch(e) { throw e; } }, parseChildrenRecursive: function(parent, elementpath) { var xmlelement, xmlattribute, tmpattrib, l, m, child; if (!parent) { this.fullName = elementpath.localName; this.name = elementpath.nodeName; xmlelement = this } else { xmlelement = new XMLElement(elementpath.nodeName); xmlelement.parent = parent } if (elementpath.nodeType === 3 && elementpath.textContent !== "") return this.createPCDataElement(elementpath.textContent); if (elementpath.nodeType === 4) return this.createCDataElement(elementpath.textContent); if (elementpath.attributes) for (l = 0, m = elementpath.attributes.length; l < m; l++) { tmpattrib = elementpath.attributes[l]; xmlattribute = new XMLAttribute(tmpattrib.getname, tmpattrib.nodeName, tmpattrib.namespaceURI, tmpattrib.nodeValue, tmpattrib.nodeType); xmlelement.attributes.push(xmlattribute) } if (elementpath.childNodes) for (l = 0, m = elementpath.childNodes.length; l < m; l++) { var node = elementpath.childNodes[l]; child = xmlelement.parseChildrenRecursive(xmlelement, node); if (child !== null) xmlelement.children.push(child) } return xmlelement }, createElement: function(fullname, namespaceuri, sysid, line) { if (sysid === undef) return new XMLElement(fullname, namespaceuri); return new XMLElement(fullname, namespaceuri, sysid, line) }, createPCDataElement: function(content, isCDATA) { if (content.replace(/^\s+$/g, "") === "") return null; var pcdata = new XMLElement; pcdata.type = "TEXT"; pcdata.content = content; return pcdata }, createCDataElement: function(content) { var cdata = this.createPCDataElement(content); if (cdata === null) return null; cdata.type = "CDATA"; var htmlentities = { "<": "&lt;", ">": "&gt;", "'": "&apos;", '"': "&quot;" }, entity; for (entity in htmlentities) if (!Object.hasOwnProperty(htmlentities, entity)) content = content.replace(new RegExp(entity, "g"), htmlentities[entity]); cdata.cdata = content; return cdata }, hasAttribute: function() { if (arguments.length === 1) return this.getAttribute(arguments[0]) !== null; if (arguments.length === 2) return this.getAttribute(arguments[0], arguments[1]) !== null }, equals: function(other) { if (! (other instanceof XMLElement)) return false; var i, j; if (this.fullName !== other.fullName) return false; if (this.attributes.length !== other.getAttributeCount()) return false; if (this.attributes.length !== other.attributes.length) return false; var attr_name, attr_ns, attr_value, attr_type, attr_other; for (i = 0, j = this.attributes.length; i < j; i++) { attr_name = this.attributes[i].getName(); attr_ns = this.attributes[i].getNamespace(); attr_other = other.findAttribute(attr_name, attr_ns); if (attr_other === null) return false; if (this.attributes[i].getValue() !== attr_other.getValue()) return false; if (this.attributes[i].getType() !== attr_other.getType()) return false } if (this.children.length !== other.getChildCount()) return false; if (this.children.length > 0) { var child1, child2; for (i = 0, j = this.children.length; i < j; i++) { child1 = this.getChild(i); child2 = other.getChild(i); if (!child1.equals(child2)) return false } return true } return this.content === other.content }, getContent: function() { if (this.type === "TEXT" || this.type === "CDATA") return this.content; var children = this.children; if (children.length === 1 && (children[0].type === "TEXT" || children[0].type === "CDATA")) return children[0].content; return null }, getAttribute: function() { var attribute; if (arguments.length === 2) { attribute = this.findAttribute(arguments[0]); if (attribute) return attribute.getValue(); return arguments[1] } else if (arguments.length === 1) { attribute = this.findAttribute(arguments[0]); if (attribute) return attribute.getValue(); return null } else if (arguments.length === 3) { attribute = this.findAttribute(arguments[0], arguments[1]); if (attribute) return attribute.getValue(); return arguments[2] } }, getStringAttribute: function() { if (arguments.length === 1) return this.getAttribute(arguments[0]); if (arguments.length === 2) return this.getAttribute(arguments[0], arguments[1]); return this.getAttribute(arguments[0], arguments[1], arguments[2]) }, getString: function(attributeName) { return this.getStringAttribute(attributeName) }, getFloatAttribute: function() { if (arguments.length === 1) return parseFloat(this.getAttribute(arguments[0], 0)); if (arguments.length === 2) return this.getAttribute(arguments[0], arguments[1]); return this.getAttribute(arguments[0], arguments[1], arguments[2]) }, getFloat: function(attributeName) { return this.getFloatAttribute(attributeName) }, getIntAttribute: function() { if (arguments.length === 1) return this.getAttribute(arguments[0], 0); if (arguments.length === 2) return this.getAttribute(arguments[0], arguments[1]); return this.getAttribute(arguments[0], arguments[1], arguments[2]) }, getInt: function(attributeName) { return this.getIntAttribute(attributeName) }, hasChildren: function() { return this.children.length > 0 }, addChild: function(child) { if (child !== null) { child.parent = this; this.children.push(child) } }, insertChild: function(child, index) { if (child) { if (child.getLocalName() === null && !this.hasChildren()) { var lastChild = this.children[this.children.length - 1]; if (lastChild.getLocalName() === null) { lastChild.setContent(lastChild.getContent() + child.getContent()); return } } child.parent = this; this.children.splice(index, 0, child) } }, getChild: function(selector) { if (typeof selector === "number") return this.children[selector]; if (selector.indexOf("/") !== -1) return this.getChildRecursive(selector.split("/"), 0); var kid, kidName; for (var i = 0, j = this.getChildCount(); i < j; i++) { kid = this.getChild(i); kidName = kid.getName(); if (kidName !== null && kidName === selector) return kid } return null }, getChildren: function() { if (arguments.length === 1) { if (typeof arguments[0] === "number") return this.getChild(arguments[0]); if (arguments[0].indexOf("/") !== -1) return this.getChildrenRecursive(arguments[0].split("/"), 0); var matches = []; var kid, kidName; for (var i = 0, j = this.getChildCount(); i < j; i++) { kid = this.getChild(i); kidName = kid.getName(); if (kidName !== null && kidName === arguments[0]) matches.push(kid) } return matches } return this.children }, getChildCount: function() { return this.children.length }, getChildRecursive: function(items, offset) { if (offset === items.length) return this; var kid, kidName, matchName = items[offset]; for (var i = 0, j = this.getChildCount(); i < j; i++) { kid = this.getChild(i); kidName = kid.getName(); if (kidName !== null && kidName === matchName) return kid.getChildRecursive(items, offset + 1) } return null }, getChildrenRecursive: function(items, offset) { if (offset === items.length - 1) return this.getChildren(items[offset]); var matches = this.getChildren(items[offset]); var kidMatches = []; for (var i = 0; i < matches.length; i++) kidMatches = kidMatches.concat(matches[i].getChildrenRecursive(items, offset + 1)); return kidMatches }, isLeaf: function() { return !this.hasChildren() }, listChildren: function() { var arr = []; for (var i = 0, j = this.children.length; i < j; i++) arr.push(this.getChild(i).getName()); return arr }, removeAttribute: function(name, namespace) { this.namespace = namespace || ""; for (var i = 0, j = this.attributes.length; i < j; i++) if (this.attributes[i].getName() === name && this.attributes[i].getNamespace() === this.namespace) { this.attributes.splice(i, 1); break } }, removeChild: function(child) { if (child) for (var i = 0, j = this.children.length; i < j; i++) if (this.children[i].equals(child)) { this.children.splice(i, 1); break } }, removeChildAtIndex: function(index) { if (this.children.length > index) this.children.splice(index, 1) }, findAttribute: function(name, namespace) { this.namespace = namespace || ""; for (var i = 0, j = this.attributes.length; i < j; i++) if (this.attributes[i].getName() === name && this.attributes[i].getNamespace() === this.namespace) return this.attributes[i]; return null }, setAttribute: function() { var attr; if (arguments.length === 3) { var index = arguments[0].indexOf(":"); var name = arguments[0].substring(index + 1); attr = this.findAttribute(name, arguments[1]); if (attr) attr.setValue(arguments[2]); else { attr = new XMLAttribute(arguments[0], name, arguments[1], arguments[2], "CDATA"); this.attributes.push(attr) } } else { attr = this.findAttribute(arguments[0]); if (attr) attr.setValue(arguments[1]); else { attr = new XMLAttribute(arguments[0], arguments[0], null, arguments[1], "CDATA"); this.attributes.push(attr) } } }, setString: function(attribute, value) { this.setAttribute(attribute, value) }, setInt: function(attribute, value) { this.setAttribute(attribute, value) }, setFloat: function(attribute, value) { this.setAttribute(attribute, value) }, setContent: function(content) { if (this.children.length > 0) Processing.debug("Tried to set content for XMLElement with children"); this.content = content }, setName: function() { if (arguments.length === 1) { this.name = arguments[0]; this.fullName = arguments[0]; this.namespace = null } else { var index = arguments[0].indexOf(":"); if (arguments[1] === null || index < 0) this.name = arguments[0]; else this.name = arguments[0].substring(index + 1); this.fullName = arguments[0]; this.namespace = arguments[1] } }, getName: function() { return this.fullName }, getLocalName: function() { return this.name }, getAttributeCount: function() { return this.attributes.length }, toString: function() { if (this.type === "TEXT") return this.content; if (this.type === "CDATA") return this.cdata; var tagstring = this.fullName; var xmlstring = "<" + tagstring; var a, c; for (a = 0; a < this.attributes.length; a++) { var attr = this.attributes[a]; xmlstring += " " + attr.getName() + "=" + '"' + attr.getValue() + '"' } if (this.children.length === 0) if (this.content === "") xmlstring += "/>"; else xmlstring += ">" + this.content + "</" + tagstring + ">"; else { xmlstring += ">"; for (c = 0; c < this.children.length; c++) xmlstring += this.children[c].toString(); xmlstring += "</" + tagstring + ">" } return xmlstring } }; XMLElement.parse = function(xmlstring) { var element = new XMLElement; element.parse(xmlstring); return element }; var XML = p.XML = p.XMLElement; p.loadXML = function(uri) { return new XML(p, uri) }; var printMatrixHelper = function(elements) { var big = 0; for (var i = 0; i < elements.length; i++) if (i !== 0) big = Math.max(big, Math.abs(elements[i])); else big = Math.abs(elements[i]); var digits = (big + "").indexOf("."); if (digits === 0) digits = 1; else if (digits === -1) digits = (big + "").length; return digits }; var PMatrix2D = p.PMatrix2D = function() { if (arguments.length === 0) this.reset(); else if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) this.set(arguments[0].array()); else if (arguments.length === 6) this.set(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]) }; PMatrix2D.prototype = { set: function() { if (arguments.length === 6) { var a = arguments; this.set([a[0], a[1], a[2], a[3], a[4], a[5]]) } else if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) this.elements = arguments[0].array(); else if (arguments.length === 1 && arguments[0] instanceof Array) this.elements = arguments[0].slice() }, get: function() { var outgoing = new PMatrix2D; outgoing.set(this.elements); return outgoing }, reset: function() { this.set([1, 0, 0, 0, 1, 0]) }, array: function array() { return this.elements.slice() }, translate: function(tx, ty) { this.elements[2] = tx * this.elements[0] + ty * this.elements[1] + this.elements[2]; this.elements[5] = tx * this.elements[3] + ty * this.elements[4] + this.elements[5] }, invTranslate: function(tx, ty) { this.translate(-tx, -ty) }, transpose: function() {}, mult: function(source, target) { var x, y; if (source instanceof PVector) { x = source.x; y = source.y; if (!target) target = new PVector } else if (source instanceof Array) { x = source[0]; y = source[1]; if (!target) target = [] } if (target instanceof Array) { target[0] = this.elements[0] * x + this.elements[1] * y + this.elements[2]; target[1] = this.elements[3] * x + this.elements[4] * y + this.elements[5] } else if (target instanceof PVector) { target.x = this.elements[0] * x + this.elements[1] * y + this.elements[2]; target.y = this.elements[3] * x + this.elements[4] * y + this.elements[5]; target.z = 0 } return target }, multX: function(x, y) { return x * this.elements[0] + y * this.elements[1] + this.elements[2] }, multY: function(x, y) { return x * this.elements[3] + y * this.elements[4] + this.elements[5] }, skewX: function(angle) { this.apply(1, 0, 1, angle, 0, 0) }, skewY: function(angle) { this.apply(1, 0, 1, 0, angle, 0) }, shearX: function(angle) { this.apply(1, 0, 1, Math.tan(angle), 0, 0) }, shearY: function(angle) { this.apply(1, 0, 1, 0, Math.tan(angle), 0) }, determinant: function() { return this.elements[0] * this.elements[4] - this.elements[1] * this.elements[3] }, invert: function() { var d = this.determinant(); if (Math.abs(d) > -2147483648) { var old00 = this.elements[0]; var old01 = this.elements[1]; var old02 = this.elements[2]; var old10 = this.elements[3]; var old11 = this.elements[4]; var old12 = this.elements[5]; this.elements[0] = old11 / d; this.elements[3] = -old10 / d; this.elements[1] = -old01 / d; this.elements[4] = old00 / d; this.elements[2] = (old01 * old12 - old11 * old02) / d; this.elements[5] = (old10 * old02 - old00 * old12) / d; return true } return false }, scale: function(sx, sy) { if (sx && !sy) sy = sx; if (sx && sy) { this.elements[0] *= sx; this.elements[1] *= sy; this.elements[3] *= sx; this.elements[4] *= sy } }, invScale: function(sx, sy) { if (sx && !sy) sy = sx; this.scale(1 / sx, 1 / sy) }, apply: function() { var source; if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) source = arguments[0].array(); else if (arguments.length === 6) source = Array.prototype.slice.call(arguments); else if (arguments.length === 1 && arguments[0] instanceof Array) source = arguments[0]; var result = [0, 0, this.elements[2], 0, 0, this.elements[5]]; var e = 0; for (var row = 0; row < 2; row++) for (var col = 0; col < 3; col++, e++) result[e] += this.elements[row * 3 + 0] * source[col + 0] + this.elements[row * 3 + 1] * source[col + 3]; this.elements = result.slice() }, preApply: function() { var source; if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) source = arguments[0].array(); else if (arguments.length === 6) source = Array.prototype.slice.call(arguments); else if (arguments.length === 1 && arguments[0] instanceof Array) source = arguments[0]; var result = [0, 0, source[2], 0, 0, source[5]]; result[2] = source[2] + this.elements[2] * source[0] + this.elements[5] * source[1]; result[5] = source[5] + this.elements[2] * source[3] + this.elements[5] * source[4]; result[0] = this.elements[0] * source[0] + this.elements[3] * source[1]; result[3] = this.elements[0] * source[3] + this.elements[3] * source[4]; result[1] = this.elements[1] * source[0] + this.elements[4] * source[1]; result[4] = this.elements[1] * source[3] + this.elements[4] * source[4]; this.elements = result.slice() }, rotate: function(angle) { var c = Math.cos(angle); var s = Math.sin(angle); var temp1 = this.elements[0]; var temp2 = this.elements[1]; this.elements[0] = c * temp1 + s * temp2; this.elements[1] = -s * temp1 + c * temp2; temp1 = this.elements[3]; temp2 = this.elements[4]; this.elements[3] = c * temp1 + s * temp2; this.elements[4] = -s * temp1 + c * temp2 }, rotateZ: function(angle) { this.rotate(angle) }, invRotateZ: function(angle) { this.rotateZ(angle - Math.PI) }, print: function() { var digits = printMatrixHelper(this.elements); var output = "" + p.nfs(this.elements[0], digits, 4) + " " + p.nfs(this.elements[1], digits, 4) + " " + p.nfs(this.elements[2], digits, 4) + "\n" + p.nfs(this.elements[3], digits, 4) + " " + p.nfs(this.elements[4], digits, 4) + " " + p.nfs(this.elements[5], digits, 4) + "\n\n"; p.println(output) } }; var PMatrix3D = p.PMatrix3D = function() { this.reset() }; PMatrix3D.prototype = { set: function() { if (arguments.length === 16) this.elements = Array.prototype.slice.call(arguments); else if (arguments.length === 1 && arguments[0] instanceof PMatrix3D) this.elements = arguments[0].array(); else if (arguments.length === 1 && arguments[0] instanceof Array) this.elements = arguments[0].slice() }, get: function() { var outgoing = new PMatrix3D; outgoing.set(this.elements); return outgoing }, reset: function() { this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] }, array: function array() { return this.elements.slice() }, translate: function(tx, ty, tz) { if (tz === undef) tz = 0; this.elements[3] += tx * this.elements[0] + ty * this.elements[1] + tz * this.elements[2]; this.elements[7] += tx * this.elements[4] + ty * this.elements[5] + tz * this.elements[6]; this.elements[11] += tx * this.elements[8] + ty * this.elements[9] + tz * this.elements[10]; this.elements[15] += tx * this.elements[12] + ty * this.elements[13] + tz * this.elements[14] }, transpose: function() { var temp = this.elements[4]; this.elements[4] = this.elements[1]; this.elements[1] = temp; temp = this.elements[8]; this.elements[8] = this.elements[2]; this.elements[2] = temp; temp = this.elements[6]; this.elements[6] = this.elements[9]; this.elements[9] = temp; temp = this.elements[3]; this.elements[3] = this.elements[12]; this.elements[12] = temp; temp = this.elements[7]; this.elements[7] = this.elements[13]; this.elements[13] = temp; temp = this.elements[11]; this.elements[11] = this.elements[14]; this.elements[14] = temp }, mult: function(source, target) { var x, y, z, w; if (source instanceof PVector) { x = source.x; y = source.y; z = source.z; w = 1; if (!target) target = new PVector } else if (source instanceof Array) { x = source[0]; y = source[1]; z = source[2]; w = source[3] || 1; if (!target || target.length !== 3 && target.length !== 4) target = [0, 0, 0] } if (target instanceof Array) if (target.length === 3) { target[0] = this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3]; target[1] = this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7]; target[2] = this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11] } else if (target.length === 4) { target[0] = this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3] * w; target[1] = this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7] * w; target[2] = this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11] * w; target[3] = this.elements[12] * x + this.elements[13] * y + this.elements[14] * z + this.elements[15] * w } if (target instanceof PVector) { target.x = this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3]; target.y = this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7]; target.z = this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11] } return target }, preApply: function() { var source; if (arguments.length === 1 && arguments[0] instanceof PMatrix3D) source = arguments[0].array(); else if (arguments.length === 16) source = Array.prototype.slice.call(arguments); else if (arguments.length === 1 && arguments[0] instanceof Array) source = arguments[0]; var result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; var e = 0; for (var row = 0; row < 4; row++) for (var col = 0; col < 4; col++, e++) result[e] += this.elements[col + 0] * source[row * 4 + 0] + this.elements[col + 4] * source[row * 4 + 1] + this.elements[col + 8] * source[row * 4 + 2] + this.elements[col + 12] * source[row * 4 + 3]; this.elements = result.slice() }, apply: function() { var source; if (arguments.length === 1 && arguments[0] instanceof PMatrix3D) source = arguments[0].array(); else if (arguments.length === 16) source = Array.prototype.slice.call(arguments); else if (arguments.length === 1 && arguments[0] instanceof Array) source = arguments[0]; var result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; var e = 0; for (var row = 0; row < 4; row++) for (var col = 0; col < 4; col++, e++) result[e] += this.elements[row * 4 + 0] * source[col + 0] + this.elements[row * 4 + 1] * source[col + 4] + this.elements[row * 4 + 2] * source[col + 8] + this.elements[row * 4 + 3] * source[col + 12]; this.elements = result.slice() }, rotate: function(angle, v0, v1, v2) { if (!v1) this.rotateZ(angle); else { var c = p.cos(angle); var s = p.sin(angle); var t = 1 - c; this.apply(t * v0 * v0 + c, t * v0 * v1 - s * v2, t * v0 * v2 + s * v1, 0, t * v0 * v1 + s * v2, t * v1 * v1 + c, t * v1 * v2 - s * v0, 0, t * v0 * v2 - s * v1, t * v1 * v2 + s * v0, t * v2 * v2 + c, 0, 0, 0, 0, 1) } }, invApply: function() { if (inverseCopy === undef) inverseCopy = new PMatrix3D; var a = arguments; inverseCopy.set(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]); if (!inverseCopy.invert()) return false; this.preApply(inverseCopy); return true }, rotateX: function(angle) { var c = p.cos(angle); var s = p.sin(angle); this.apply([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]) }, rotateY: function(angle) { var c = p.cos(angle); var s = p.sin(angle); this.apply([c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1]) }, rotateZ: function(angle) { var c = Math.cos(angle); var s = Math.sin(angle); this.apply([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]) }, scale: function(sx, sy, sz) { if (sx && !sy && !sz) sy = sz = sx; else if (sx && sy && !sz) sz = 1; if (sx && sy && sz) { this.elements[0] *= sx; this.elements[1] *= sy; this.elements[2] *= sz; this.elements[4] *= sx; this.elements[5] *= sy; this.elements[6] *= sz; this.elements[8] *= sx; this.elements[9] *= sy; this.elements[10] *= sz; this.elements[12] *= sx; this.elements[13] *= sy; this.elements[14] *= sz } }, skewX: function(angle) { var t = Math.tan(angle); this.apply(1, t, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) }, skewY: function(angle) { var t = Math.tan(angle); this.apply(1, 0, 0, 0, t, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) }, shearX: function(angle) { var t = Math.tan(angle); this.apply(1, t, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) }, shearY: function(angle) { var t = Math.tan(angle); this.apply(1, 0, 0, 0, t, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) }, multX: function(x, y, z, w) { if (!z) return this.elements[0] * x + this.elements[1] * y + this.elements[3]; if (!w) return this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3]; return this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3] * w }, multY: function(x, y, z, w) { if (!z) return this.elements[4] * x + this.elements[5] * y + this.elements[7]; if (!w) return this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7]; return this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7] * w }, multZ: function(x, y, z, w) { if (!w) return this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11]; return this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11] * w }, multW: function(x, y, z, w) { if (!w) return this.elements[12] * x + this.elements[13] * y + this.elements[14] * z + this.elements[15]; return this.elements[12] * x + this.elements[13] * y + this.elements[14] * z + this.elements[15] * w }, invert: function() { var fA0 = this.elements[0] * this.elements[5] - this.elements[1] * this.elements[4]; var fA1 = this.elements[0] * this.elements[6] - this.elements[2] * this.elements[4]; var fA2 = this.elements[0] * this.elements[7] - this.elements[3] * this.elements[4]; var fA3 = this.elements[1] * this.elements[6] - this.elements[2] * this.elements[5]; var fA4 = this.elements[1] * this.elements[7] - this.elements[3] * this.elements[5]; var fA5 = this.elements[2] * this.elements[7] - this.elements[3] * this.elements[6]; var fB0 = this.elements[8] * this.elements[13] - this.elements[9] * this.elements[12]; var fB1 = this.elements[8] * this.elements[14] - this.elements[10] * this.elements[12]; var fB2 = this.elements[8] * this.elements[15] - this.elements[11] * this.elements[12]; var fB3 = this.elements[9] * this.elements[14] - this.elements[10] * this.elements[13]; var fB4 = this.elements[9] * this.elements[15] - this.elements[11] * this.elements[13]; var fB5 = this.elements[10] * this.elements[15] - this.elements[11] * this.elements[14]; var fDet = fA0 * fB5 - fA1 * fB4 + fA2 * fB3 + fA3 * fB2 - fA4 * fB1 + fA5 * fB0; if (Math.abs(fDet) <= 1.0E-9) return false; var kInv = []; kInv[0] = +this.elements[5] * fB5 - this.elements[6] * fB4 + this.elements[7] * fB3; kInv[4] = -this.elements[4] * fB5 + this.elements[6] * fB2 - this.elements[7] * fB1; kInv[8] = +this.elements[4] * fB4 - this.elements[5] * fB2 + this.elements[7] * fB0; kInv[12] = -this.elements[4] * fB3 + this.elements[5] * fB1 - this.elements[6] * fB0; kInv[1] = -this.elements[1] * fB5 + this.elements[2] * fB4 - this.elements[3] * fB3; kInv[5] = +this.elements[0] * fB5 - this.elements[2] * fB2 + this.elements[3] * fB1; kInv[9] = -this.elements[0] * fB4 + this.elements[1] * fB2 - this.elements[3] * fB0; kInv[13] = +this.elements[0] * fB3 - this.elements[1] * fB1 + this.elements[2] * fB0; kInv[2] = +this.elements[13] * fA5 - this.elements[14] * fA4 + this.elements[15] * fA3; kInv[6] = -this.elements[12] * fA5 + this.elements[14] * fA2 - this.elements[15] * fA1; kInv[10] = +this.elements[12] * fA4 - this.elements[13] * fA2 + this.elements[15] * fA0; kInv[14] = -this.elements[12] * fA3 + this.elements[13] * fA1 - this.elements[14] * fA0; kInv[3] = -this.elements[9] * fA5 + this.elements[10] * fA4 - this.elements[11] * fA3; kInv[7] = +this.elements[8] * fA5 - this.elements[10] * fA2 + this.elements[11] * fA1; kInv[11] = -this.elements[8] * fA4 + this.elements[9] * fA2 - this.elements[11] * fA0; kInv[15] = +this.elements[8] * fA3 - this.elements[9] * fA1 + this.elements[10] * fA0; var fInvDet = 1 / fDet; kInv[0] *= fInvDet; kInv[1] *= fInvDet; kInv[2] *= fInvDet; kInv[3] *= fInvDet; kInv[4] *= fInvDet; kInv[5] *= fInvDet; kInv[6] *= fInvDet; kInv[7] *= fInvDet; kInv[8] *= fInvDet; kInv[9] *= fInvDet; kInv[10] *= fInvDet; kInv[11] *= fInvDet; kInv[12] *= fInvDet; kInv[13] *= fInvDet; kInv[14] *= fInvDet; kInv[15] *= fInvDet; this.elements = kInv.slice(); return true }, toString: function() { var str = ""; for (var i = 0; i < 15; i++) str += this.elements[i] + ", "; str += this.elements[15]; return str }, print: function() { var digits = printMatrixHelper(this.elements); var output = "" + p.nfs(this.elements[0], digits, 4) + " " + p.nfs(this.elements[1], digits, 4) + " " + p.nfs(this.elements[2], digits, 4) + " " + p.nfs(this.elements[3], digits, 4) + "\n" + p.nfs(this.elements[4], digits, 4) + " " + p.nfs(this.elements[5], digits, 4) + " " + p.nfs(this.elements[6], digits, 4) + " " + p.nfs(this.elements[7], digits, 4) + "\n" + p.nfs(this.elements[8], digits, 4) + " " + p.nfs(this.elements[9], digits, 4) + " " + p.nfs(this.elements[10], digits, 4) + " " + p.nfs(this.elements[11], digits, 4) + "\n" + p.nfs(this.elements[12], digits, 4) + " " + p.nfs(this.elements[13], digits, 4) + " " + p.nfs(this.elements[14], digits, 4) + " " + p.nfs(this.elements[15], digits, 4) + "\n\n"; p.println(output) }, invTranslate: function(tx, ty, tz) { this.preApply(1, 0, 0, -tx, 0, 1, 0, -ty, 0, 0, 1, -tz, 0, 0, 0, 1) }, invRotateX: function(angle) { var c = Math.cos(-angle); var s = Math.sin(-angle); this.preApply([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]) }, invRotateY: function(angle) { var c = Math.cos(-angle); var s = Math.sin(-angle); this.preApply([c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1]) }, invRotateZ: function(angle) { var c = Math.cos(-angle); var s = Math.sin(-angle); this.preApply([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]) }, invScale: function(x, y, z) { this.preApply([1 / x, 0, 0, 0, 0, 1 / y, 0, 0, 0, 0, 1 / z, 0, 0, 0, 0, 1]) } }; var PMatrixStack = p.PMatrixStack = function() { this.matrixStack = [] }; PMatrixStack.prototype.load = function() { var tmpMatrix = drawing.$newPMatrix(); if (arguments.length === 1) tmpMatrix.set(arguments[0]); else tmpMatrix.set(arguments); this.matrixStack.push(tmpMatrix) }; Drawing2D.prototype.$newPMatrix = function() { return new PMatrix2D }; Drawing3D.prototype.$newPMatrix = function() { return new PMatrix3D }; PMatrixStack.prototype.push = function() { this.matrixStack.push(this.peek()) }; PMatrixStack.prototype.pop = function() { return this.matrixStack.pop() }; PMatrixStack.prototype.peek = function() { var tmpMatrix = drawing.$newPMatrix(); tmpMatrix.set(this.matrixStack[this.matrixStack.length - 1]); return tmpMatrix }; PMatrixStack.prototype.mult = function(matrix) { this.matrixStack[this.matrixStack.length - 1].apply(matrix) }; p.split = function(str, delim) { return str.split(delim) }; p.splitTokens = function(str, tokens) { if (tokens === undef) return str.split(/\s+/g); var chars = tokens.split(/()/g), buffer = "", len = str.length, i, c, tokenized = []; for (i = 0; i < len; i++) { c = str[i]; if (chars.indexOf(c) > -1) { if (buffer !== "") tokenized.push(buffer); buffer = "" } else buffer += c } if (buffer !== "") tokenized.push(buffer); return tokenized }; p.append = function(array, element) { array[array.length] = element; return array }; p.concat = function(array1, array2) { return array1.concat(array2) }; p.sort = function(array, numElem) { var ret = []; if (array.length > 0) { var elemsToCopy = numElem > 0 ? numElem : array.length; for (var i = 0; i < elemsToCopy; i++) ret.push(array[i]); if (typeof array[0] === "string") ret.sort(); else ret.sort(function(a, b) { return a - b }); if (numElem > 0) for (var j = ret.length; j < array.length; j++) ret.push(array[j]) } return ret }; p.splice = function(array, value, index) { if (value.length === 0) return array; if (value instanceof Array) for (var i = 0, j = index; i < value.length; j++, i++) array.splice(j, 0, value[i]); else array.splice(index, 0, value); return array }; p.subset = function(array, offset, length) { var end = length !== undef ? offset + length : array.length; return array.slice(offset, end) }; p.join = function(array, seperator) { return array.join(seperator) }; p.shorten = function(ary) { var newary = []; var len = ary.length; for (var i = 0; i < len; i++) newary[i] = ary[i]; newary.pop(); return newary }; p.expand = function(ary, targetSize) { var temp = ary.slice(0), newSize = targetSize || ary.length * 2; temp.length = newSize; return temp }; p.arrayCopy = function() { var src, srcPos = 0, dest, destPos = 0, length; if (arguments.length === 2) { src = arguments[0]; dest = arguments[1]; length = src.length } else if (arguments.length === 3) { src = arguments[0]; dest = arguments[1]; length = arguments[2] } else if (arguments.length === 5) { src = arguments[0]; srcPos = arguments[1]; dest = arguments[2]; destPos = arguments[3]; length = arguments[4] } for (var i = srcPos, j = destPos; i < length + srcPos; i++, j++) if (dest[j] !== undef) dest[j] = src[i]; else throw "array index out of bounds exception"; }; p.reverse = function(array) { return array.reverse() }; p.mix = function(a, b, f) { return a + ((b - a) * f >> 8) }; p.peg = function(n) { return n < 0 ? 0 : n > 255 ? 255 : n }; p.modes = function() { var ALPHA_MASK = 4278190080, RED_MASK = 16711680, GREEN_MASK = 65280, BLUE_MASK = 255, min = Math.min, max = Math.max; function applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb) { var a = min(((c1 & 4278190080) >>> 24) + f, 255) << 24; var r = ar + ((cr - ar) * f >> 8); r = (r < 0 ? 0 : r > 255 ? 255 : r) << 16; var g = ag + ((cg - ag) * f >> 8); g = (g < 0 ? 0 : g > 255 ? 255 : g) << 8; var b = ab + ((cb - ab) * f >> 8); b = b < 0 ? 0 : b > 255 ? 255 : b; return a | r | g | b } return { replace: function(c1, c2) { return c2 }, blend: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24, ar = c1 & RED_MASK, ag = c1 & GREEN_MASK, ab = c1 & BLUE_MASK, br = c2 & RED_MASK, bg = c2 & GREEN_MASK, bb = c2 & BLUE_MASK; return min(((c1 & ALPHA_MASK) >>> 24) + f, 255) << 24 | ar + ((br - ar) * f >> 8) & RED_MASK | ag + ((bg - ag) * f >> 8) & GREEN_MASK | ab + ((bb - ab) * f >> 8) & BLUE_MASK }, add: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24; return min(((c1 & ALPHA_MASK) >>> 24) + f, 255) << 24 | min((c1 & RED_MASK) + ((c2 & RED_MASK) >> 8) * f, RED_MASK) & RED_MASK | min((c1 & GREEN_MASK) + ((c2 & GREEN_MASK) >> 8) * f, GREEN_MASK) & GREEN_MASK | min((c1 & BLUE_MASK) + ((c2 & BLUE_MASK) * f >> 8), BLUE_MASK) }, subtract: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24; return min(((c1 & ALPHA_MASK) >>> 24) + f, 255) << 24 | max((c1 & RED_MASK) - ((c2 & RED_MASK) >> 8) * f, GREEN_MASK) & RED_MASK | max((c1 & GREEN_MASK) - ((c2 & GREEN_MASK) >> 8) * f, BLUE_MASK) & GREEN_MASK | max((c1 & BLUE_MASK) - ((c2 & BLUE_MASK) * f >> 8), 0) }, lightest: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24; return min(((c1 & ALPHA_MASK) >>> 24) + f, 255) << 24 | max(c1 & RED_MASK, ((c2 & RED_MASK) >> 8) * f) & RED_MASK | max(c1 & GREEN_MASK, ((c2 & GREEN_MASK) >> 8) * f) & GREEN_MASK | max(c1 & BLUE_MASK, (c2 & BLUE_MASK) * f >> 8) }, darkest: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24, ar = c1 & RED_MASK, ag = c1 & GREEN_MASK, ab = c1 & BLUE_MASK, br = min(c1 & RED_MASK, ((c2 & RED_MASK) >> 8) * f), bg = min(c1 & GREEN_MASK, ((c2 & GREEN_MASK) >> 8) * f), bb = min(c1 & BLUE_MASK, (c2 & BLUE_MASK) * f >> 8); return min(((c1 & ALPHA_MASK) >>> 24) + f, 255) << 24 | ar + ((br - ar) * f >> 8) & RED_MASK | ag + ((bg - ag) * f >> 8) & GREEN_MASK | ab + ((bb - ab) * f >> 8) & BLUE_MASK }, difference: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24, ar = (c1 & RED_MASK) >> 16, ag = (c1 & GREEN_MASK) >> 8, ab = c1 & BLUE_MASK, br = (c2 & RED_MASK) >> 16, bg = (c2 & GREEN_MASK) >> 8, bb = c2 & BLUE_MASK, cr = ar > br ? ar - br : br - ar, cg = ag > bg ? ag - bg : bg - ag, cb = ab > bb ? ab - bb : bb - ab; return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb) }, exclusion: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24, ar = (c1 & RED_MASK) >> 16, ag = (c1 & GREEN_MASK) >> 8, ab = c1 & BLUE_MASK, br = (c2 & RED_MASK) >> 16, bg = (c2 & GREEN_MASK) >> 8, bb = c2 & BLUE_MASK, cr = ar + br - (ar * br >> 7), cg = ag + bg - (ag * bg >> 7), cb = ab + bb - (ab * bb >> 7); return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb) }, multiply: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24, ar = (c1 & RED_MASK) >> 16, ag = (c1 & GREEN_MASK) >> 8, ab = c1 & BLUE_MASK, br = (c2 & RED_MASK) >> 16, bg = (c2 & GREEN_MASK) >> 8, bb = c2 & BLUE_MASK, cr = ar * br >> 8, cg = ag * bg >> 8, cb = ab * bb >> 8; return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb) }, screen: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24, ar = (c1 & RED_MASK) >> 16, ag = (c1 & GREEN_MASK) >> 8, ab = c1 & BLUE_MASK, br = (c2 & RED_MASK) >> 16, bg = (c2 & GREEN_MASK) >> 8, bb = c2 & BLUE_MASK, cr = 255 - ((255 - ar) * (255 - br) >> 8), cg = 255 - ((255 - ag) * (255 - bg) >> 8), cb = 255 - ((255 - ab) * (255 - bb) >> 8); return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb) }, hard_light: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24, ar = (c1 & RED_MASK) >> 16, ag = (c1 & GREEN_MASK) >> 8, ab = c1 & BLUE_MASK, br = (c2 & RED_MASK) >> 16, bg = (c2 & GREEN_MASK) >> 8, bb = c2 & BLUE_MASK, cr = br < 128 ? ar * br >> 7 : 255 - ((255 - ar) * (255 - br) >> 7), cg = bg < 128 ? ag * bg >> 7 : 255 - ((255 - ag) * (255 - bg) >> 7), cb = bb < 128 ? ab * bb >> 7 : 255 - ((255 - ab) * (255 - bb) >> 7); return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb) }, soft_light: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24, ar = (c1 & RED_MASK) >> 16, ag = (c1 & GREEN_MASK) >> 8, ab = c1 & BLUE_MASK, br = (c2 & RED_MASK) >> 16, bg = (c2 & GREEN_MASK) >> 8, bb = c2 & BLUE_MASK, cr = (ar * br >> 7) + (ar * ar >> 8) - (ar * ar * br >> 15), cg = (ag * bg >> 7) + (ag * ag >> 8) - (ag * ag * bg >> 15), cb = (ab * bb >> 7) + (ab * ab >> 8) - (ab * ab * bb >> 15); return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb) }, overlay: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24, ar = (c1 & RED_MASK) >> 16, ag = (c1 & GREEN_MASK) >> 8, ab = c1 & BLUE_MASK, br = (c2 & RED_MASK) >> 16, bg = (c2 & GREEN_MASK) >> 8, bb = c2 & BLUE_MASK, cr = ar < 128 ? ar * br >> 7 : 255 - ((255 - ar) * (255 - br) >> 7), cg = ag < 128 ? ag * bg >> 7 : 255 - ((255 - ag) * (255 - bg) >> 7), cb = ab < 128 ? ab * bb >> 7 : 255 - ((255 - ab) * (255 - bb) >> 7); return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb) }, dodge: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24, ar = (c1 & RED_MASK) >> 16, ag = (c1 & GREEN_MASK) >> 8, ab = c1 & BLUE_MASK, br = (c2 & RED_MASK) >> 16, bg = (c2 & GREEN_MASK) >> 8, bb = c2 & BLUE_MASK; var cr = 255; if (br !== 255) { cr = (ar << 8) / (255 - br); cr = cr < 0 ? 0 : cr > 255 ? 255 : cr } var cg = 255; if (bg !== 255) { cg = (ag << 8) / (255 - bg); cg = cg < 0 ? 0 : cg > 255 ? 255 : cg } var cb = 255; if (bb !== 255) { cb = (ab << 8) / (255 - bb); cb = cb < 0 ? 0 : cb > 255 ? 255 : cb } return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb) }, burn: function(c1, c2) { var f = (c2 & ALPHA_MASK) >>> 24, ar = (c1 & RED_MASK) >> 16, ag = (c1 & GREEN_MASK) >> 8, ab = c1 & BLUE_MASK, br = (c2 & RED_MASK) >> 16, bg = (c2 & GREEN_MASK) >> 8, bb = c2 & BLUE_MASK; var cr = 0; if (br !== 0) { cr = (255 - ar << 8) / br; cr = 255 - (cr < 0 ? 0 : cr > 255 ? 255 : cr) } var cg = 0; if (bg !== 0) { cg = (255 - ag << 8) / bg; cg = 255 - (cg < 0 ? 0 : cg > 255 ? 255 : cg) } var cb = 0; if (bb !== 0) { cb = (255 - ab << 8) / bb; cb = 255 - (cb < 0 ? 0 : cb > 255 ? 255 : cb) } return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb) } } }(); function color$4(aValue1, aValue2, aValue3, aValue4) { var r, g, b, a; if (curColorMode === 3) { var rgb = p.color.toRGB(aValue1, aValue2, aValue3); r = rgb[0]; g = rgb[1]; b = rgb[2] } else { r = Math.round(255 * (aValue1 / colorModeX)); g = Math.round(255 * (aValue2 / colorModeY)); b = Math.round(255 * (aValue3 / colorModeZ)) } a = Math.round(255 * (aValue4 / colorModeA)); r = r < 0 ? 0 : r; g = g < 0 ? 0 : g; b = b < 0 ? 0 : b; a = a < 0 ? 0 : a; r = r > 255 ? 255 : r; g = g > 255 ? 255 : g; b = b > 255 ? 255 : b; a = a > 255 ? 255 : a; return a << 24 & 4278190080 | r << 16 & 16711680 | g << 8 & 65280 | b & 255 } function color$2(aValue1, aValue2) { var a; if (aValue1 & 4278190080) { a = Math.round(255 * (aValue2 / colorModeA)); a = a > 255 ? 255 : a; a = a < 0 ? 0 : a; return aValue1 - (aValue1 & 4278190080) + (a << 24 & 4278190080) } if (curColorMode === 1) return color$4(aValue1, aValue1, aValue1, aValue2); if (curColorMode === 3) return color$4(0, 0, aValue1 / colorModeX * colorModeZ, aValue2) } function color$1(aValue1) { if (aValue1 <= colorModeX && aValue1 >= 0) { if (curColorMode === 1) return color$4(aValue1, aValue1, aValue1, colorModeA); if (curColorMode === 3) return color$4(0, 0, aValue1 / colorModeX * colorModeZ, colorModeA) } if (aValue1) { if (aValue1 > 2147483647) aValue1 -= 4294967296; return aValue1 } } p.color = function(aValue1, aValue2, aValue3, aValue4) { if (aValue1 !== undef && aValue2 !== undef && aValue3 !== undef && aValue4 !== undef) return color$4(aValue1, aValue2, aValue3, aValue4); if (aValue1 !== undef && aValue2 !== undef && aValue3 !== undef) return color$4(aValue1, aValue2, aValue3, colorModeA); if (aValue1 !== undef && aValue2 !== undef) return color$2(aValue1, aValue2); if (typeof aValue1 === "number") return color$1(aValue1); return color$4(colorModeX, colorModeY, colorModeZ, colorModeA) }; p.color.toString = function(colorInt) { return "rgba(" + ((colorInt >> 16) & 255) + "," + ((colorInt >> 8) & 255) + "," + (colorInt & 255) + "," + ((colorInt >> 24) & 255) / 255 + ")" }; p.color.toInt = function(r, g, b, a) { return a << 24 & 4278190080 | r << 16 & 16711680 | g << 8 & 65280 | b & 255 }; p.color.toArray = function(colorInt) { return [(colorInt >> 16) & 255, (colorInt >> 8) & 255, colorInt & 255, (colorInt >> 24) & 255] }; p.color.toGLArray = function(colorInt) { return [((colorInt & 16711680) >>> 16) / 255, ((colorInt >> 8) & 255) / 255, (colorInt & 255) / 255, ((colorInt >> 24) & 255) / 255] }; p.color.toRGB = function(h, s, b) { h = h > colorModeX ? colorModeX : h; s = s > colorModeY ? colorModeY : s; b = b > colorModeZ ? colorModeZ : b; h = h / colorModeX * 360; s = s / colorModeY * 100; b = b / colorModeZ * 100; var br = Math.round(b / 100 * 255); if (s === 0) return [br, br, br]; var hue = h % 360; var f = hue % 60; var p = Math.round(b * (100 - s) / 1E4 * 255); var q = Math.round(b * (6E3 - s * f) / 6E5 * 255); var t = Math.round(b * (6E3 - s * (60 - f)) / 6E5 * 255); switch (Math.floor(hue / 60)) { case 0: return [br, t, p]; case 1: return [q, br, p]; case 2: return [p, br, t]; case 3: return [p, q, br]; case 4: return [t, p, br]; case 5: return [br, p, q] } }; function colorToHSB(colorInt) { var red, green, blue; red = ((colorInt >> 16) & 255) / 255; green = ((colorInt >> 8) & 255) / 255; blue = (colorInt & 255) / 255; var max = p.max(p.max(red, green), blue), min = p.min(p.min(red, green), blue), hue, saturation; if (min === max) return [0, 0, max * colorModeZ]; saturation = (max - min) / max; if (red === max) hue = (green - blue) / (max - min); else if (green === max) hue = 2 + (blue - red) / (max - min); else hue = 4 + (red - green) / (max - min); hue /= 6; if (hue < 0) hue += 1; else if (hue > 1) hue -= 1; return [hue * colorModeX, saturation * colorModeY, max * colorModeZ] } p.brightness = function(colInt) { return colorToHSB(colInt)[2] }; p.saturation = function(colInt) { return colorToHSB(colInt)[1] }; p.hue = function(colInt) { return colorToHSB(colInt)[0] }; p.red = function(aColor) { return ((aColor >> 16) & 255) / 255 * colorModeX }; p.green = function(aColor) { return ((aColor & 65280) >>> 8) / 255 * colorModeY }; p.blue = function(aColor) { return (aColor & 255) / 255 * colorModeZ }; p.alpha = function(aColor) { return ((aColor >> 24) & 255) / 255 * colorModeA }; p.lerpColor = function(c1, c2, amt) { var r, g, b, a, r1, g1, b1, a1, r2, g2, b2, a2; var hsb1, hsb2, rgb, h, s; var colorBits1 = p.color(c1); var colorBits2 = p.color(c2); if (curColorMode === 3) { hsb1 = colorToHSB(colorBits1); a1 = ((colorBits1 >> 24) & 255) / colorModeA; hsb2 = colorToHSB(colorBits2); a2 = ((colorBits2 & 4278190080) >>> 24) / colorModeA; h = p.lerp(hsb1[0], hsb2[0], amt); s = p.lerp(hsb1[1], hsb2[1], amt); b = p.lerp(hsb1[2], hsb2[2], amt); rgb = p.color.toRGB(h, s, b); a = p.lerp(a1, a2, amt) * colorModeA; return a << 24 & 4278190080 | (rgb[0] & 255) << 16 | (rgb[1] & 255) << 8 | rgb[2] & 255 } r1 = (colorBits1 >> 16) & 255; g1 = (colorBits1 >> 8) & 255; b1 = colorBits1 & 255; a1 = ((colorBits1 >> 24) & 255) / colorModeA; r2 = (colorBits2 & 16711680) >>> 16; g2 = (colorBits2 >> 8) & 255; b2 = colorBits2 & 255; a2 = ((colorBits2 >> 24) & 255) / colorModeA; r = p.lerp(r1, r2, amt) | 0; g = p.lerp(g1, g2, amt) | 0; b = p.lerp(b1, b2, amt) | 0; a = p.lerp(a1, a2, amt) * colorModeA; return a << 24 & 4278190080 | r << 16 & 16711680 | g << 8 & 65280 | b & 255 }; p.colorMode = function() { curColorMode = arguments[0]; if (arguments.length > 1) { colorModeX = arguments[1]; colorModeY = arguments[2] || arguments[1]; colorModeZ = arguments[3] || arguments[1]; colorModeA = arguments[4] || arguments[1] } }; p.blendColor = function(c1, c2, mode) { if (mode === 0) return p.modes.replace(c1, c2); else if (mode === 1) return p.modes.blend(c1, c2); else if (mode === 2) return p.modes.add(c1, c2); else if (mode === 4) return p.modes.subtract(c1, c2); else if (mode === 8) return p.modes.lightest(c1, c2); else if (mode === 16) return p.modes.darkest(c1, c2); else if (mode === 32) return p.modes.difference(c1, c2); else if (mode === 64) return p.modes.exclusion(c1, c2); else if (mode === 128) return p.modes.multiply(c1, c2); else if (mode === 256) return p.modes.screen(c1, c2); else if (mode === 1024) return p.modes.hard_light(c1, c2); else if (mode === 2048) return p.modes.soft_light(c1, c2); else if (mode === 512) return p.modes.overlay(c1, c2); else if (mode === 4096) return p.modes.dodge(c1, c2); else if (mode === 8192) return p.modes.burn(c1, c2) }; function saveContext() { curContext.save() } function restoreContext() { curContext.restore(); isStrokeDirty = true; isFillDirty = true } p.printMatrix = function() { modelView.print() }; Drawing2D.prototype.translate = function(x, y) { modelView.translate(x, y); modelViewInv.invTranslate(x, y); curContext.translate(x, y) }; Drawing3D.prototype.translate = function(x, y, z) { modelView.translate(x, y, z); modelViewInv.invTranslate(x, y, z) }; Drawing2D.prototype.scale = function(x, y) { modelView.scale(x, y); modelViewInv.invScale(x, y); curContext.scale(x, y || x) }; Drawing3D.prototype.scale = function(x, y, z) { modelView.scale(x, y, z); modelViewInv.invScale(x, y, z) }; Drawing2D.prototype.transform = function(pmatrix) { var e = pmatrix.array(); curContext.transform(e[0], e[3], e[1], e[4], e[2], e[5]) }; Drawing3D.prototype.transformm = function(pmatrix3d) { throw "p.transform is currently not supported in 3D mode"; }; Drawing2D.prototype.pushMatrix = function() { userMatrixStack.load(modelView); userReverseMatrixStack.load(modelViewInv); saveContext() }; Drawing3D.prototype.pushMatrix = function() { userMatrixStack.load(modelView); userReverseMatrixStack.load(modelViewInv) }; Drawing2D.prototype.popMatrix = function() { modelView.set(userMatrixStack.pop()); modelViewInv.set(userReverseMatrixStack.pop()); restoreContext() }; Drawing3D.prototype.popMatrix = function() { modelView.set(userMatrixStack.pop()); modelViewInv.set(userReverseMatrixStack.pop()) }; Drawing2D.prototype.resetMatrix = function() { modelView.reset(); modelViewInv.reset(); curContext.setTransform(1, 0, 0, 1, 0, 0) }; Drawing3D.prototype.resetMatrix = function() { modelView.reset(); modelViewInv.reset() }; DrawingShared.prototype.applyMatrix = function() { var a = arguments; modelView.apply(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]); modelViewInv.invApply(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]) }; Drawing2D.prototype.applyMatrix = function() { var a = arguments; for (var cnt = a.length; cnt < 16; cnt++) a[cnt] = 0; a[10] = a[15] = 1; DrawingShared.prototype.applyMatrix.apply(this, a) }; p.rotateX = function(angleInRadians) { modelView.rotateX(angleInRadians); modelViewInv.invRotateX(angleInRadians) }; Drawing2D.prototype.rotateZ = function() { throw "rotateZ() is not supported in 2D mode. Use rotate(float) instead."; }; Drawing3D.prototype.rotateZ = function(angleInRadians) { modelView.rotateZ(angleInRadians); modelViewInv.invRotateZ(angleInRadians) }; p.rotateY = function(angleInRadians) { modelView.rotateY(angleInRadians); modelViewInv.invRotateY(angleInRadians) }; Drawing2D.prototype.rotate = function(angleInRadians) { modelView.rotateZ(angleInRadians); modelViewInv.invRotateZ(angleInRadians); curContext.rotate(angleInRadians) }; Drawing3D.prototype.rotate = function(angleInRadians) { p.rotateZ(angleInRadians) }; Drawing2D.prototype.shearX = function(angleInRadians) { modelView.shearX(angleInRadians); curContext.transform(1, 0, angleInRadians, 1, 0, 0) }; Drawing3D.prototype.shearX = function(angleInRadians) { modelView.shearX(angleInRadians) }; Drawing2D.prototype.shearY = function(angleInRadians) { modelView.shearY(angleInRadians); curContext.transform(1, angleInRadians, 0, 1, 0, 0) }; Drawing3D.prototype.shearY = function(angleInRadians) { modelView.shearY(angleInRadians) }; p.pushStyle = function() { saveContext(); p.pushMatrix(); var newState = { "doFill": doFill, "currentFillColor": currentFillColor, "doStroke": doStroke, "currentStrokeColor": currentStrokeColor, "curTint": curTint, "curRectMode": curRectMode, "curColorMode": curColorMode, "colorModeX": colorModeX, "colorModeZ": colorModeZ, "colorModeY": colorModeY, "colorModeA": colorModeA, "curTextFont": curTextFont, "horizontalTextAlignment": horizontalTextAlignment, "verticalTextAlignment": verticalTextAlignment, "textMode": textMode, "curFontName": curFontName, "curTextSize": curTextSize, "curTextAscent": curTextAscent, "curTextDescent": curTextDescent, "curTextLeading": curTextLeading }; styleArray.push(newState) }; p.popStyle = function() { var oldState = styleArray.pop(); if (oldState) { restoreContext(); p.popMatrix(); doFill = oldState.doFill; currentFillColor = oldState.currentFillColor; doStroke = oldState.doStroke; currentStrokeColor = oldState.currentStrokeColor; curTint = oldState.curTint; curRectMode = oldState.curRectMode; curColorMode = oldState.curColorMode; colorModeX = oldState.colorModeX; colorModeZ = oldState.colorModeZ; colorModeY = oldState.colorModeY; colorModeA = oldState.colorModeA; curTextFont = oldState.curTextFont; curFontName = oldState.curFontName; curTextSize = oldState.curTextSize; horizontalTextAlignment = oldState.horizontalTextAlignment; verticalTextAlignment = oldState.verticalTextAlignment; textMode = oldState.textMode; curTextAscent = oldState.curTextAscent; curTextDescent = oldState.curTextDescent; curTextLeading = oldState.curTextLeading } else throw "Too many popStyle() without enough pushStyle()"; }; p.year = function() { return (new Date).getFullYear() }; p.month = function() { return (new Date).getMonth() + 1 }; p.day = function() { return (new Date).getDate() }; p.hour = function() { return (new Date).getHours() }; p.minute = function() { return (new Date).getMinutes() }; p.second = function() { return (new Date).getSeconds() }; p.millis = function() { return Date.now() - start }; function redrawHelper() { var sec = (Date.now() - timeSinceLastFPS) / 1E3; framesSinceLastFPS++; var fps = framesSinceLastFPS / sec; if (sec > 0.5) { timeSinceLastFPS = Date.now(); framesSinceLastFPS = 0; p.__frameRate = fps } p.frameCount++ } Drawing2D.prototype.redraw = function() { redrawHelper(); curContext.lineWidth = lineWidth; var pmouseXLastEvent = p.pmouseX, pmouseYLastEvent = p.pmouseY; p.pmouseX = pmouseXLastFrame; p.pmouseY = pmouseYLastFrame; saveContext(); p.draw(); restoreContext(); pmouseXLastFrame = p.mouseX; pmouseYLastFrame = p.mouseY; p.pmouseX = pmouseXLastEvent; p.pmouseY = pmouseYLastEvent }; Drawing3D.prototype.redraw = function() { redrawHelper(); var pmouseXLastEvent = p.pmouseX, pmouseYLastEvent = p.pmouseY; p.pmouseX = pmouseXLastFrame; p.pmouseY = pmouseYLastFrame; curContext.clear(curContext.DEPTH_BUFFER_BIT); curContextCache = { attributes: {}, locations: {} }; p.noLights(); p.lightFalloff(1, 0, 0); p.shininess(1); p.ambient(255, 255, 255); p.specular(0, 0, 0); p.emissive(0, 0, 0); p.camera(); p.draw(); pmouseXLastFrame = p.mouseX; pmouseYLastFrame = p.mouseY; p.pmouseX = pmouseXLastEvent; p.pmouseY = pmouseYLastEvent }; p.noLoop = function() { doLoop = false; loopStarted = false; clearInterval(looping); curSketch.onPause() }; p.loop = function() { if (loopStarted) return; timeSinceLastFPS = Date.now(); framesSinceLastFPS = 0; looping = window.setInterval(function() { try { curSketch.onFrameStart(); p.redraw(); curSketch.onFrameEnd() } catch(e_loop) { window.clearInterval(looping); throw e_loop; } }, curMsPerFrame); doLoop = true; loopStarted = true; curSketch.onLoop() }; p.frameRate = function(aRate) { curFrameRate = aRate; curMsPerFrame = 1E3 / curFrameRate; if (doLoop) { p.noLoop(); p.loop() } }; var eventHandlers = []; function attachEventHandler(elem, type, fn) { if (elem.addEventListener) elem.addEventListener(type, fn, false); else elem.attachEvent("on" + type, fn); eventHandlers.push({ elem: elem, type: type, fn: fn }) } function detachEventHandler(eventHandler) { var elem = eventHandler.elem, type = eventHandler.type, fn = eventHandler.fn; if (elem.removeEventListener) elem.removeEventListener(type, fn, false); else if (elem.detachEvent) elem.detachEvent("on" + type, fn) } p.exit = function() { window.clearInterval(looping); removeInstance(p.externals.canvas.id); delete curElement.onmousedown; for (var lib in Processing.lib) if (Processing.lib.hasOwnProperty(lib)) if (Processing.lib[lib].hasOwnProperty("detach")) Processing.lib[lib].detach(p); var i = eventHandlers.length; while (i--) detachEventHandler(eventHandlers[i]); curSketch.onExit() }; p.cursor = function() { if (arguments.length > 1 || arguments.length === 1 && arguments[0] instanceof p.PImage) { var image = arguments[0], x, y; if (arguments.length >= 3) { x = arguments[1]; y = arguments[2]; if (x < 0 || y < 0 || y >= image.height || x >= image.width) throw "x and y must be non-negative and less than the dimensions of the image"; } else { x = image.width >>> 1; y = image.height >>> 1 } var imageDataURL = image.toDataURL(); var style = 'url("' + imageDataURL + '") ' + x + " " + y + ", default"; curCursor = curElement.style.cursor = style } else if (arguments.length === 1) { var mode = arguments[0]; curCursor = curElement.style.cursor = mode } else curCursor = curElement.style.cursor = oldCursor }; p.noCursor = function() { curCursor = curElement.style.cursor = PConstants.NOCURSOR }; p.link = function(href, target) { if (target !== undef) window.open(href, target); else window.location = href }; p.beginDraw = nop; p.endDraw = nop; Drawing2D.prototype.toImageData = function(x, y, w, h) { x = x !== undef ? x : 0; y = y !== undef ? y : 0; w = w !== undef ? w : p.width; h = h !== undef ? h : p.height; return curContext.getImageData(x, y, w, h) }; Drawing3D.prototype.toImageData = function(x, y, w, h) { x = x !== undef ? x : 0; y = y !== undef ? y : 0; w = w !== undef ? w : p.width; h = h !== undef ? h : p.height; var c = document.createElement("canvas"), ctx = c.getContext("2d"), obj = ctx.createImageData(w, h), uBuff = new Uint8Array(w * h * 4); curContext.readPixels(x, y, w, h, curContext.RGBA, curContext.UNSIGNED_BYTE, uBuff); for (var i = 0, ul = uBuff.length, obj_data = obj.data; i < ul; i++) obj_data[i] = uBuff[(h - 1 - Math.floor(i / 4 / w)) * w * 4 + i % (w * 4)]; return obj }; p.status = function(text) { window.status = text }; p.binary = function(num, numBits) { var bit; if (numBits > 0) bit = numBits; else if (num instanceof Char) { bit = 16; num |= 0 } else { bit = 32; while (bit > 1 && !(num >>> bit - 1 & 1)) bit-- } var result = ""; while (bit > 0) result += num >>> --bit & 1 ? "1" : "0"; return result }; p.unbinary = function(binaryString) { var i = binaryString.length - 1, mask = 1, result = 0; while (i >= 0) { var ch = binaryString[i--]; if (ch !== "0" && ch !== "1") throw "the value passed into unbinary was not an 8 bit binary number"; if (ch === "1") result += mask; mask <<= 1 } return result }; function nfCoreScalar(value, plus, minus, leftDigits, rightDigits, group) { var sign = value < 0 ? minus : plus; var autoDetectDecimals = rightDigits === 0; var rightDigitsOfDefault = rightDigits === undef || rightDigits < 0 ? 0 : rightDigits; var absValue = Math.abs(value); if (autoDetectDecimals) { rightDigitsOfDefault = 1; absValue *= 10; while (Math.abs(Math.round(absValue) - absValue) > 1.0E-6 && rightDigitsOfDefault < 7) { ++rightDigitsOfDefault; absValue *= 10 } } else if (rightDigitsOfDefault !== 0) absValue *= Math.pow(10, rightDigitsOfDefault); var number, doubled = absValue * 2; if (Math.floor(absValue) === absValue) number = absValue; else if (Math.floor(doubled) === doubled) { var floored = Math.floor(absValue); number = floored + floored % 2 } else number = Math.round(absValue); var buffer = ""; var totalDigits = leftDigits + rightDigitsOfDefault; while (totalDigits > 0 || number > 0) { totalDigits--; buffer = "" + number % 10 + buffer; number = Math.floor(number / 10) } if (group !== undef) { var i = buffer.length - 3 - rightDigitsOfDefault; while (i > 0) { buffer = buffer.substring(0, i) + group + buffer.substring(i); i -= 3 } } if (rightDigitsOfDefault > 0) return sign + buffer.substring(0, buffer.length - rightDigitsOfDefault) + "." + buffer.substring(buffer.length - rightDigitsOfDefault, buffer.length); return sign + buffer } function nfCore(value, plus, minus, leftDigits, rightDigits, group) { if (value instanceof Array) { var arr = []; for (var i = 0, len = value.length; i < len; i++) arr.push(nfCoreScalar(value[i], plus, minus, leftDigits, rightDigits, group)); return arr } return nfCoreScalar(value, plus, minus, leftDigits, rightDigits, group) } p.nf = function(value, leftDigits, rightDigits) { return nfCore(value, "", "-", leftDigits, rightDigits) }; p.nfs = function(value, leftDigits, rightDigits) { return nfCore(value, " ", "-", leftDigits, rightDigits) }; p.nfp = function(value, leftDigits, rightDigits) { return nfCore(value, "+", "-", leftDigits, rightDigits) }; p.nfc = function(value, leftDigits, rightDigits) { return nfCore(value, "", "-", leftDigits, rightDigits, ",") }; var decimalToHex = function(d, padding) { padding = padding === undef || padding === null ? padding = 8 : padding; if (d < 0) d = 4294967295 + d + 1; var hex = Number(d).toString(16).toUpperCase(); while (hex.length < padding) hex = "0" + hex; if (hex.length >= padding) hex = hex.substring(hex.length - padding, hex.length); return hex }; p.hex = function(value, len) { if (arguments.length === 1) if (value instanceof Char) len = 4; else len = 8; return decimalToHex(value, len) }; function unhexScalar(hex) { var value = parseInt("0x" + hex, 16); if (value > 2147483647) value -= 4294967296; return value } p.unhex = function(hex) { if (hex instanceof Array) { var arr = []; for (var i = 0; i < hex.length; i++) arr.push(unhexScalar(hex[i])); return arr } return unhexScalar(hex) }; p.loadStrings = function(filename) { if (localStorage[filename]) return localStorage[filename].split("\n"); var filecontent = ajax(filename); if (typeof filecontent !== "string" || filecontent === "") return []; filecontent = filecontent.replace(/(\r\n?)/g, "\n").replace(/\n$/, ""); return filecontent.split("\n") }; p.saveStrings = function(filename, strings) { localStorage[filename] = strings.join("\n") }; p.loadBytes = function(url) { var string = ajax(url); var ret = []; for (var i = 0; i < string.length; i++) ret.push(string.charCodeAt(i)); return ret }; function removeFirstArgument(args) { return Array.prototype.slice.call(args, 1) } p.matchAll = function(aString, aRegExp) { var results = [], latest; var regexp = new RegExp(aRegExp, "g"); while ((latest = regexp.exec(aString)) !== null) { results.push(latest); if (latest[0].length === 0)++regexp.lastIndex } return results.length > 0 ? results : null }; p.__contains = function(subject, subStr) { if (typeof subject !== "string") return subject.contains.apply(subject, removeFirstArgument(arguments)); return subject !== null && subStr !== null && typeof subStr === "string" && subject.indexOf(subStr) > -1 }; p.__replaceAll = function(subject, regex, replacement) { if (typeof subject !== "string") return subject.replaceAll.apply(subject, removeFirstArgument(arguments)); return subject.replace(new RegExp(regex, "g"), replacement) }; p.__replaceFirst = function(subject, regex, replacement) { if (typeof subject !== "string") return subject.replaceFirst.apply(subject, removeFirstArgument(arguments)); return subject.replace(new RegExp(regex, ""), replacement) }; p.__replace = function(subject, what, replacement) { if (typeof subject !== "string") return subject.replace.apply(subject, removeFirstArgument(arguments)); if (what instanceof RegExp) return subject.replace(what, replacement); if (typeof what !== "string") what = what.toString(); if (what === "") return subject; var i = subject.indexOf(what); if (i < 0) return subject; var j = 0, result = ""; do { result += subject.substring(j, i) + replacement; j = i + what.length } while ((i = subject.indexOf(what, j)) >= 0); return result + subject.substring(j) }; p.__equals = function(subject, other) { if (subject.equals instanceof Function) return subject.equals.apply(subject, removeFirstArgument(arguments)); return subject.valueOf() === other.valueOf() }; p.__equalsIgnoreCase = function(subject, other) { if (typeof subject !== "string") return subject.equalsIgnoreCase.apply(subject, removeFirstArgument(arguments)); return subject.toLowerCase() === other.toLowerCase() }; p.__toCharArray = function(subject) { if (typeof subject !== "string") return subject.toCharArray.apply(subject, removeFirstArgument(arguments)); var chars = []; for (var i = 0, len = subject.length; i < len; ++i) chars[i] = new Char(subject.charAt(i)); return chars }; p.__split = function(subject, regex, limit) { if (typeof subject !== "string") return subject.split.apply(subject, removeFirstArgument(arguments)); var pattern = new RegExp(regex); if (limit === undef || limit < 1) return subject.split(pattern); var result = [], currSubject = subject, pos; while ((pos = currSubject.search(pattern)) !== -1 && result.length < limit - 1) { var match = pattern.exec(currSubject).toString(); result.push(currSubject.substring(0, pos)); currSubject = currSubject.substring(pos + match.length) } if (pos !== -1 || currSubject !== "") result.push(currSubject); return result }; p.__codePointAt = function(subject, idx) { var code = subject.charCodeAt(idx), hi, low; if (55296 <= code && code <= 56319) { hi = code; low = subject.charCodeAt(idx + 1); return (hi - 55296) * 1024 + (low - 56320) + 65536 } return code }; p.match = function(str, regexp) { return str.match(regexp) }; p.__matches = function(str, regexp) { return (new RegExp(regexp)).test(str) }; p.__startsWith = function(subject, prefix, toffset) { if (typeof subject !== "string") return subject.startsWith.apply(subject, removeFirstArgument(arguments)); toffset = toffset || 0; if (toffset < 0 || toffset > subject.length) return false; return prefix === "" || prefix === subject ? true : subject.indexOf(prefix) === toffset }; p.__endsWith = function(subject, suffix) { if (typeof subject !== "string") return subject.endsWith.apply(subject, removeFirstArgument(arguments)); var suffixLen = suffix ? suffix.length : 0; return suffix === "" || suffix === subject ? true : subject.indexOf(suffix) === subject.length - suffixLen }; p.__hashCode = function(subject) { if (subject.hashCode instanceof Function) return subject.hashCode.apply(subject, removeFirstArgument(arguments)); return virtHashCode(subject) }; p.__printStackTrace = function(subject) { p.println("Exception: " + subject.toString()) }; var logBuffer = []; p.println = function(message) { var bufferLen = logBuffer.length; if (bufferLen) { Processing.logger.log(logBuffer.join("")); logBuffer.length = 0 } if (arguments.length === 0 && bufferLen === 0) Processing.logger.log(""); else if (arguments.length !== 0) Processing.logger.log(message) }; p.print = function(message) { logBuffer.push(message) }; p.str = function(val) { if (val instanceof Array) { var arr = []; for (var i = 0; i < val.length; i++) arr.push(val[i].toString() + ""); return arr } return val.toString() + "" }; p.trim = function(str) { if (str instanceof Array) { var arr = []; for (var i = 0; i < str.length; i++) arr.push(str[i].replace(/^\s*/, "").replace(/\s*$/, "").replace(/\r*$/, "")); return arr } return str.replace(/^\s*/, "").replace(/\s*$/, "").replace(/\r*$/, "") }; function booleanScalar(val) { if (typeof val === "number") return val !== 0; if (typeof val === "boolean") return val; if (typeof val === "string") return val.toLowerCase() === "true"; if (val instanceof Char) return val.code === 49 || val.code === 84 || val.code === 116 } p.parseBoolean = function(val) { if (val instanceof Array) { var ret = []; for (var i = 0; i < val.length; i++) ret.push(booleanScalar(val[i])); return ret } return booleanScalar(val) }; p.parseByte = function(what) { if (what instanceof Array) { var bytes = []; for (var i = 0; i < what.length; i++) bytes.push(0 - (what[i] & 128) | what[i] & 127); return bytes } return 0 - (what & 128) | what & 127 }; p.parseChar = function(key) { if (typeof key === "number") return new Char(String.fromCharCode(key & 65535)); if (key instanceof Array) { var ret = []; for (var i = 0; i < key.length; i++) ret.push(new Char(String.fromCharCode(key[i] & 65535))); return ret } throw "char() may receive only one argument of type int, byte, int[], or byte[]."; }; function floatScalar(val) { if (typeof val === "number") return val; if (typeof val === "boolean") return val ? 1 : 0; if (typeof val === "string") return parseFloat(val); if (val instanceof Char) return val.code } p.parseFloat = function(val) { if (val instanceof Array) { var ret = []; for (var i = 0; i < val.length; i++) ret.push(floatScalar(val[i])); return ret } return floatScalar(val) }; function intScalar(val, radix) { if (typeof val === "number") return val & 4294967295; if (typeof val === "boolean") return val ? 1 : 0; if (typeof val === "string") { var number = parseInt(val, radix || 10); return number & 4294967295 } if (val instanceof Char) return val.code } p.parseInt = function(val, radix) { if (val instanceof Array) { var ret = []; for (var i = 0; i < val.length; i++) if (typeof val[i] === "string" && !/^\s*[+\-]?\d+\s*$/.test(val[i])) ret.push(0); else ret.push(intScalar(val[i], radix)); return ret } return intScalar(val, radix) }; p.__int_cast = function(val) { return 0 | val }; p.__instanceof = function(obj, type) { if (typeof type !== "function") throw "Function is expected as type argument for instanceof operator"; if (typeof obj === "string") return type === Object || type === String; if (obj instanceof type) return true; if (typeof obj !== "object" || obj === null) return false; var objType = obj.constructor; if (type.$isInterface) { var interfaces = []; while (objType) { if (objType.$interfaces) interfaces = interfaces.concat(objType.$interfaces); objType = objType.$base } while (interfaces.length > 0) { var i = interfaces.shift(); if (i === type) return true; if (i.$interfaces) interfaces = interfaces.concat(i.$interfaces) } return false } while (objType.hasOwnProperty("$base")) { objType = objType.$base; if (objType === type) return true } return false }; p.abs = Math.abs; p.ceil = Math.ceil; p.constrain = function(aNumber, aMin, aMax) { return aNumber > aMax ? aMax : aNumber < aMin ? aMin : aNumber }; p.dist = function() { var dx, dy, dz; if (arguments.length === 4) { dx = arguments[0] - arguments[2]; dy = arguments[1] - arguments[3]; return Math.sqrt(dx * dx + dy * dy) } if (arguments.length === 6) { dx = arguments[0] - arguments[3]; dy = arguments[1] - arguments[4]; dz = arguments[2] - arguments[5]; return Math.sqrt(dx * dx + dy * dy + dz * dz) } }; p.exp = Math.exp; p.floor = Math.floor; p.lerp = function(value1, value2, amt) { return (value2 - value1) * amt + value1 }; p.log = Math.log; p.mag = function(a, b, c) { if (c) return Math.sqrt(a * a + b * b + c * c); return Math.sqrt(a * a + b * b) }; p.map = function(value, istart, istop, ostart, ostop) { return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)) }; p.max = function() { if (arguments.length === 2) return arguments[0] < arguments[1] ? arguments[1] : arguments[0]; var numbers = arguments.length === 1 ? arguments[0] : arguments; if (! ("length" in numbers && numbers.length > 0)) throw "Non-empty array is expected"; var max = numbers[0], count = numbers.length; for (var i = 1; i < count; ++i) if (max < numbers[i]) max = numbers[i]; return max }; p.min = function() { if (arguments.length === 2) return arguments[0] < arguments[1] ? arguments[0] : arguments[1]; var numbers = arguments.length === 1 ? arguments[0] : arguments; if (! ("length" in numbers && numbers.length > 0)) throw "Non-empty array is expected"; var min = numbers[0], count = numbers.length; for (var i = 1; i < count; ++i) if (min > numbers[i]) min = numbers[i]; return min }; p.norm = function(aNumber, low, high) { return (aNumber - low) / (high - low) }; p.pow = Math.pow; p.round = Math.round; p.sq = function(aNumber) { return aNumber * aNumber }; p.sqrt = Math.sqrt; p.acos = Math.acos; p.asin = Math.asin; p.atan = Math.atan; p.atan2 = Math.atan2; p.cos = Math.cos; p.degrees = function(aAngle) { return aAngle * 180 / Math.PI }; p.radians = function(aAngle) { return aAngle / 180 * Math.PI }; p.sin = Math.sin; p.tan = Math.tan; var currentRandom = Math.random; p.random = function() { if (arguments.length === 0) return currentRandom(); if (arguments.length === 1) return currentRandom() * arguments[0]; var aMin = arguments[0], aMax = arguments[1]; return currentRandom() * (aMax - aMin) + aMin }; function Marsaglia(i1, i2) { var z = i1 || 362436069, w = i2 || 521288629; var nextInt = function() { z = 36969 * (z & 65535) + (z >>> 16) & 4294967295; w = 18E3 * (w & 65535) + (w >>> 16) & 4294967295; return ((z & 65535) << 16 | w & 65535) & 4294967295 }; this.nextDouble = function() { var i = nextInt() / 4294967296; return i < 0 ? 1 + i : i }; this.nextInt = nextInt } Marsaglia.createRandomized = function() { var now = new Date; return new Marsaglia(now / 6E4 & 4294967295, now & 4294967295) }; p.randomSeed = function(seed) { currentRandom = (new Marsaglia(seed)).nextDouble }; p.Random = function(seed) { var haveNextNextGaussian = false, nextNextGaussian, random; this.nextGaussian = function() { if (haveNextNextGaussian) { haveNextNextGaussian = false; return nextNextGaussian } var v1, v2, s; do { v1 = 2 * random() - 1; v2 = 2 * random() - 1; s = v1 * v1 + v2 * v2 } while (s >= 1 || s === 0); var multiplier = Math.sqrt(-2 * Math.log(s) / s); nextNextGaussian = v2 * multiplier; haveNextNextGaussian = true; return v1 * multiplier }; random = seed === undef ? Math.random : (new Marsaglia(seed)).nextDouble }; function PerlinNoise(seed) { var rnd = seed !== undef ? new Marsaglia(seed) : Marsaglia.createRandomized(); var i, j; var perm = new Uint8Array(512); for (i = 0; i < 256; ++i) perm[i] = i; for (i = 0; i < 256; ++i) { var t = perm[j = rnd.nextInt() & 255]; perm[j] = perm[i]; perm[i] = t } for (i = 0; i < 256; ++i) perm[i + 256] = perm[i]; function grad3d(i, x, y, z) { var h = i & 15; var u = h < 8 ? x : y, v = h < 4 ? y : h === 12 || h === 14 ? x : z; return ((h & 1) === 0 ? u : -u) + ((h & 2) === 0 ? v : -v) } function grad2d(i, x, y) { var v = (i & 1) === 0 ? x : y; return (i & 2) === 0 ? -v : v } function grad1d(i, x) { return (i & 1) === 0 ? -x : x } function lerp(t, a, b) { return a + t * (b - a) } this.noise3d = function(x, y, z) { var X = Math.floor(x) & 255, Y = Math.floor(y) & 255, Z = Math.floor(z) & 255; x -= Math.floor(x); y -= Math.floor(y); z -= Math.floor(z); var fx = (3 - 2 * x) * x * x, fy = (3 - 2 * y) * y * y, fz = (3 - 2 * z) * z * z; var p0 = perm[X] + Y, p00 = perm[p0] + Z, p01 = perm[p0 + 1] + Z, p1 = perm[X + 1] + Y, p10 = perm[p1] + Z, p11 = perm[p1 + 1] + Z; return lerp(fz, lerp(fy, lerp(fx, grad3d(perm[p00], x, y, z), grad3d(perm[p10], x - 1, y, z)), lerp(fx, grad3d(perm[p01], x, y - 1, z), grad3d(perm[p11], x - 1, y - 1, z))), lerp(fy, lerp(fx, grad3d(perm[p00 + 1], x, y, z - 1), grad3d(perm[p10 + 1], x - 1, y, z - 1)), lerp(fx, grad3d(perm[p01 + 1], x, y - 1, z - 1), grad3d(perm[p11 + 1], x - 1, y - 1, z - 1)))) }; this.noise2d = function(x, y) { var X = Math.floor(x) & 255, Y = Math.floor(y) & 255; x -= Math.floor(x); y -= Math.floor(y); var fx = (3 - 2 * x) * x * x, fy = (3 - 2 * y) * y * y; var p0 = perm[X] + Y, p1 = perm[X + 1] + Y; return lerp(fy, lerp(fx, grad2d(perm[p0], x, y), grad2d(perm[p1], x - 1, y)), lerp(fx, grad2d(perm[p0 + 1], x, y - 1), grad2d(perm[p1 + 1], x - 1, y - 1))) }; this.noise1d = function(x) { var X = Math.floor(x) & 255; x -= Math.floor(x); var fx = (3 - 2 * x) * x * x; return lerp(fx, grad1d(perm[X], x), grad1d(perm[X + 1], x - 1)) } } var noiseProfile = { generator: undef, octaves: 4, fallout: 0.5, seed: undef }; p.noise = function(x, y, z) { if (noiseProfile.generator === undef) noiseProfile.generator = new PerlinNoise(noiseProfile.seed); var generator = noiseProfile.generator; var effect = 1, k = 1, sum = 0; for (var i = 0; i < noiseProfile.octaves; ++i) { effect *= noiseProfile.fallout; switch (arguments.length) { case 1: sum += effect * (1 + generator.noise1d(k * x)) / 2; break; case 2: sum += effect * (1 + generator.noise2d(k * x, k * y)) / 2; break; case 3: sum += effect * (1 + generator.noise3d(k * x, k * y, k * z)) / 2; break } k *= 2 } return sum }; p.noiseDetail = function(octaves, fallout) { noiseProfile.octaves = octaves; if (fallout !== undef) noiseProfile.fallout = fallout }; p.noiseSeed = function(seed) { noiseProfile.seed = seed; noiseProfile.generator = undef }; DrawingShared.prototype.size = function(aWidth, aHeight, aMode) { if (doStroke) p.stroke(0); if (doFill) p.fill(255); var savedProperties = { fillStyle: curContext.fillStyle, strokeStyle: curContext.strokeStyle, lineCap: curContext.lineCap, lineJoin: curContext.lineJoin }; if (curElement.style.length > 0) { curElement.style.removeProperty("width"); curElement.style.removeProperty("height") } curElement.width = p.width = aWidth || 100; curElement.height = p.height = aHeight || 100; for (var prop in savedProperties) if (savedProperties.hasOwnProperty(prop)) curContext[prop] = savedProperties[prop]; p.textFont(curTextFont); p.background(); maxPixelsCached = Math.max(1E3, aWidth * aHeight * 0.05); p.externals.context = curContext; for (var i = 0; i < 720; i++) { sinLUT[i] = p.sin(i * (Math.PI / 180) * 0.5); cosLUT[i] = p.cos(i * (Math.PI / 180) * 0.5) } }; Drawing2D.prototype.size = function(aWidth, aHeight, aMode) { if (curContext === undef) { curContext = curElement.getContext("2d"); userMatrixStack = new PMatrixStack; userReverseMatrixStack = new PMatrixStack; modelView = new PMatrix2D; modelViewInv = new PMatrix2D } DrawingShared.prototype.size.apply(this, arguments) }; Drawing3D.prototype.size = function() { var size3DCalled = false; return function size(aWidth, aHeight, aMode) { if (size3DCalled) throw "Multiple calls to size() for 3D renders are not allowed."; size3DCalled = true; function getGLContext(canvas) { var ctxNames = ["experimental-webgl", "webgl", "webkit-3d"], gl; for (var i = 0, l = ctxNames.length; i < l; i++) { gl = canvas.getContext(ctxNames[i], { antialias: false, preserveDrawingBuffer: true }); if (gl) break } return gl } try { curElement.width = p.width = aWidth || 100; curElement.height = p.height = aHeight || 100; curContext = getGLContext(curElement); canTex = curContext.createTexture(); textTex = curContext.createTexture() } catch(e_size) { Processing.debug(e_size) } if (!curContext) throw "WebGL context is not supported on this browser."; curContext.viewport(0, 0, curElement.width, curElement.height); curContext.enable(curContext.DEPTH_TEST); curContext.enable(curContext.BLEND); curContext.blendFunc(curContext.SRC_ALPHA, curContext.ONE_MINUS_SRC_ALPHA); programObject2D = createProgramObject(curContext, vertexShaderSrc2D, fragmentShaderSrc2D); programObjectUnlitShape = createProgramObject(curContext, vertexShaderSrcUnlitShape, fragmentShaderSrcUnlitShape); p.strokeWeight(1); programObject3D = createProgramObject(curContext, vertexShaderSrc3D, fragmentShaderSrc3D); curContext.useProgram(programObject3D); uniformi("usingTexture3d", programObject3D, "usingTexture", usingTexture); p.lightFalloff(1, 0, 0); p.shininess(1); p.ambient(255, 255, 255); p.specular(0, 0, 0); p.emissive(0, 0, 0); boxBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, boxBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, boxVerts, curContext.STATIC_DRAW); boxNormBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, boxNormBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, boxNorms, curContext.STATIC_DRAW); boxOutlineBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, boxOutlineBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, boxOutlineVerts, curContext.STATIC_DRAW); rectBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, rectBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, rectVerts, curContext.STATIC_DRAW); rectNormBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, rectNormBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, rectNorms, curContext.STATIC_DRAW); sphereBuffer = curContext.createBuffer(); lineBuffer = curContext.createBuffer(); fillBuffer = curContext.createBuffer(); fillColorBuffer = curContext.createBuffer(); strokeColorBuffer = curContext.createBuffer(); shapeTexVBO = curContext.createBuffer(); pointBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, pointBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array([0, 0, 0]), curContext.STATIC_DRAW); textBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, textBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array([1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0]), curContext.STATIC_DRAW); textureBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ARRAY_BUFFER, textureBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]), curContext.STATIC_DRAW); indexBuffer = curContext.createBuffer(); curContext.bindBuffer(curContext.ELEMENT_ARRAY_BUFFER, indexBuffer); curContext.bufferData(curContext.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 2, 3, 0]), curContext.STATIC_DRAW); cam = new PMatrix3D; cameraInv = new PMatrix3D; modelView = new PMatrix3D; modelViewInv = new PMatrix3D; projection = new PMatrix3D; p.camera(); p.perspective(); userMatrixStack = new PMatrixStack; userReverseMatrixStack = new PMatrixStack; curveBasisMatrix = new PMatrix3D; curveToBezierMatrix = new PMatrix3D; curveDrawMatrix = new PMatrix3D; bezierDrawMatrix = new PMatrix3D; bezierBasisInverse = new PMatrix3D; bezierBasisMatrix = new PMatrix3D; bezierBasisMatrix.set(-1, 3, -3, 1, 3, -6, 3, 0, -3, 3, 0, 0, 1, 0, 0, 0); DrawingShared.prototype.size.apply(this, arguments) } }(); Drawing2D.prototype.ambientLight = DrawingShared.prototype.a3DOnlyFunction; Drawing3D.prototype.ambientLight = function(r, g, b, x, y, z) { if (lightCount === 8) throw "can only create " + 8 + " lights"; var pos = new PVector(x, y, z); var view = new PMatrix3D; view.scale(1, -1, 1); view.apply(modelView.array()); view.mult(pos, pos); var col = color$4(r, g, b, 0); var normalizedCol = [((col >> 16) & 255) / 255, ((col >> 8) & 255) / 255, (col & 255) / 255]; curContext.useProgram(programObject3D); uniformf("uLights.color.3d." + lightCount, programObject3D, "uLights" + lightCount + ".color", normalizedCol); uniformf("uLights.position.3d." + lightCount, programObject3D, "uLights" + lightCount + ".position", pos.array()); uniformi("uLights.type.3d." + lightCount, programObject3D, "uLights" + lightCount + ".type", 0); uniformi("uLightCount3d", programObject3D, "uLightCount", ++lightCount) }; Drawing2D.prototype.directionalLight = DrawingShared.prototype.a3DOnlyFunction; Drawing3D.prototype.directionalLight = function(r, g, b, nx, ny, nz) { if (lightCount === 8) throw "can only create " + 8 + " lights"; curContext.useProgram(programObject3D); var mvm = new PMatrix3D; mvm.scale(1, -1, 1); mvm.apply(modelView.array()); mvm = mvm.array(); var dir = [mvm[0] * nx + mvm[4] * ny + mvm[8] * nz, mvm[1] * nx + mvm[5] * ny + mvm[9] * nz, mvm[2] * nx + mvm[6] * ny + mvm[10] * nz]; var col = color$4(r, g, b, 0); var normalizedCol = [((col >> 16) & 255) / 255, ((col >> 8) & 255) / 255, (col & 255) / 255]; uniformf("uLights.color.3d." + lightCount, programObject3D, "uLights" + lightCount + ".color", normalizedCol); uniformf("uLights.position.3d." + lightCount, programObject3D, "uLights" + lightCount + ".position", dir); uniformi("uLights.type.3d." + lightCount, programObject3D, "uLights" + lightCount + ".type", 1); uniformi("uLightCount3d", programObject3D, "uLightCount", ++lightCount) }; Drawing2D.prototype.lightFalloff = DrawingShared.prototype.a3DOnlyFunction; Drawing3D.prototype.lightFalloff = function(constant, linear, quadratic) { curContext.useProgram(programObject3D); uniformf("uFalloff3d", programObject3D, "uFalloff", [constant, linear, quadratic]) }; Drawing2D.prototype.lightSpecular = DrawingShared.prototype.a3DOnlyFunction; Drawing3D.prototype.lightSpecular = function(r, g, b) { var col = color$4(r, g, b, 0); var normalizedCol = [((col >> 16) & 255) / 255, ((col >> 8) & 255) / 255, (col & 255) / 255]; curContext.useProgram(programObject3D); uniformf("uSpecular3d", programObject3D, "uSpecular", normalizedCol) }; p.lights = function() { p.ambientLight(128, 128, 128); p.directionalLight(128, 128, 128, 0, 0, -1); p.lightFalloff(1, 0, 0); p.lightSpecular(0, 0, 0) }; Drawing2D.prototype.pointLight = DrawingShared.prototype.a3DOnlyFunction; Drawing3D.prototype.pointLight = function(r, g, b, x, y, z) { if (lightCount === 8) throw "can only create " + 8 + " lights"; var pos = new PVector(x, y, z); var view = new PMatrix3D; view.scale(1, -1, 1); view.apply(modelView.array()); view.mult(pos, pos); var col = color$4(r, g, b, 0); var normalizedCol = [((col >> 16) & 255) / 255, ((col >> 8) & 255) / 255, (col & 255) / 255]; curContext.useProgram(programObject3D); uniformf("uLights.color.3d." + lightCount, programObject3D, "uLights" + lightCount + ".color", normalizedCol); uniformf("uLights.position.3d." + lightCount, programObject3D, "uLights" + lightCount + ".position", pos.array()); uniformi("uLights.type.3d." + lightCount, programObject3D, "uLights" + lightCount + ".type", 2); uniformi("uLightCount3d", programObject3D, "uLightCount", ++lightCount) }; Drawing2D.prototype.noLights = DrawingShared.prototype.a3DOnlyFunction; Drawing3D.prototype.noLights = function() { lightCount = 0; curContext.useProgram(programObject3D); uniformi("uLightCount3d", programObject3D, "uLightCount", lightCount) }; Drawing2D.prototype.spotLight = DrawingShared.prototype.a3DOnlyFunction; Drawing3D.prototype.spotLight = function(r, g, b, x, y, z, nx, ny, nz, angle, concentration) { if (lightCount === 8) throw "can only create " + 8 + " lights"; curContext.useProgram(programObject3D); var pos = new PVector(x, y, z); var mvm = new PMatrix3D; mvm.scale(1, -1, 1); mvm.apply(modelView.array()); mvm.mult(pos, pos); mvm = mvm.array(); var dir = [mvm[0] * nx + mvm[4] * ny + mvm[8] * nz, mvm[1] * nx + mvm[5] * ny + mvm[9] * nz, mvm[2] * nx + mvm[6] * ny + mvm[10] * nz]; var col = color$4(r, g, b, 0); var normalizedCol = [((col >> 16) & 255) / 255, ((col >> 8) & 255) / 255, (col & 255) / 255]; uniformf("uLights.color.3d." + lightCount, programObject3D, "uLights" + lightCount + ".color", normalizedCol); uniformf("uLights.position.3d." + lightCount, programObject3D, "uLights" + lightCount + ".position", pos.array()); uniformf("uLights.direction.3d." + lightCount, programObject3D, "uLights" + lightCount + ".direction", dir); uniformf("uLights.concentration.3d." + lightCount, programObject3D, "uLights" + lightCount + ".concentration", concentration); uniformf("uLights.angle.3d." + lightCount, programObject3D, "uLights" + lightCount + ".angle", angle); uniformi("uLights.type.3d." + lightCount, programObject3D, "uLights" + lightCount + ".type", 3); uniformi("uLightCount3d", programObject3D, "uLightCount", ++lightCount) }; Drawing2D.prototype.beginCamera = function() { throw "beginCamera() is not available in 2D mode"; }; Drawing3D.prototype.beginCamera = function() { if (manipulatingCamera) throw "You cannot call beginCamera() again before calling endCamera()"; manipulatingCamera = true; modelView = cameraInv; modelViewInv = cam }; Drawing2D.prototype.endCamera = function() { throw "endCamera() is not available in 2D mode"; }; Drawing3D.prototype.endCamera = function() { if (!manipulatingCamera) throw "You cannot call endCamera() before calling beginCamera()"; modelView.set(cam); modelViewInv.set(cameraInv); manipulatingCamera = false }; p.camera = function(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) { if (eyeX === undef) { cameraX = p.width / 2; cameraY = p.height / 2; cameraZ = cameraY / Math.tan(cameraFOV / 2); eyeX = cameraX; eyeY = cameraY; eyeZ = cameraZ; centerX = cameraX; centerY = cameraY; centerZ = 0; upX = 0; upY = 1; upZ = 0 } var z = new PVector(eyeX - centerX, eyeY - centerY, eyeZ - centerZ); var y = new PVector(upX, upY, upZ); z.normalize(); var x = PVector.cross(y, z); y = PVector.cross(z, x); x.normalize(); y.normalize(); var xX = x.x, xY = x.y, xZ = x.z; var yX = y.x, yY = y.y, yZ = y.z; var zX = z.x, zY = z.y, zZ = z.z; cam.set(xX, xY, xZ, 0, yX, yY, yZ, 0, zX, zY, zZ, 0, 0, 0, 0, 1); cam.translate(-eyeX, -eyeY, -eyeZ); cameraInv.reset(); cameraInv.invApply(xX, xY, xZ, 0, yX, yY, yZ, 0, zX, zY, zZ, 0, 0, 0, 0, 1); cameraInv.translate(eyeX, eyeY, eyeZ); modelView.set(cam); modelViewInv.set(cameraInv) }; p.perspective = function(fov, aspect, near, far) { if (arguments.length === 0) { cameraY = curElement.height / 2; cameraZ = cameraY / Math.tan(cameraFOV / 2); cameraNear = cameraZ / 10; cameraFar = cameraZ * 10; cameraAspect = p.width / p.height; fov = cameraFOV; aspect = cameraAspect; near = cameraNear; far = cameraFar } var yMax, yMin, xMax, xMin; yMax = near * Math.tan(fov / 2); yMin = -yMax; xMax = yMax * aspect; xMin = yMin * aspect; p.frustum(xMin, xMax, yMin, yMax, near, far) }; Drawing2D.prototype.frustum = function() { throw "Processing.js: frustum() is not supported in 2D mode"; }; Drawing3D.prototype.frustum = function(left, right, bottom, top, near, far) { frustumMode = true; projection = new PMatrix3D; projection.set(2 * near / (right - left), 0, (right + left) / (right - left), 0, 0, 2 * near / (top - bottom), (top + bottom) / (top - bottom), 0, 0, 0, -(far + near) / (far - near), -(2 * far * near) / (far - near), 0, 0, -1, 0); var proj = new PMatrix3D; proj.set(projection); proj.transpose(); curContext.useProgram(programObject2D); uniformMatrix("projection2d", programObject2D, "uProjection", false, proj.array()); curContext.useProgram(programObject3D); uniformMatrix("projection3d", programObject3D, "uProjection", false, proj.array()); curContext.useProgram(programObjectUnlitShape); uniformMatrix("uProjectionUS", programObjectUnlitShape, "uProjection", false, proj.array()) }; p.ortho = function(left, right, bottom, top, near, far) { if (arguments.length === 0) { left = 0; right = p.width; bottom = 0; top = p.height; near = -10; far = 10 } var x = 2 / (right - left); var y = 2 / (top - bottom); var z = -2 / (far - near); var tx = -(right + left) / (right - left); var ty = -(top + bottom) / (top - bottom); var tz = -(far + near) / (far - near); projection = new PMatrix3D; projection.set(x, 0, 0, tx, 0, y, 0, ty, 0, 0, z, tz, 0, 0, 0, 1); var proj = new PMatrix3D; proj.set(projection); proj.transpose(); curContext.useProgram(programObject2D); uniformMatrix("projection2d", programObject2D, "uProjection", false, proj.array()); curContext.useProgram(programObject3D); uniformMatrix("projection3d", programObject3D, "uProjection", false, proj.array()); curContext.useProgram(programObjectUnlitShape); uniformMatrix("uProjectionUS", programObjectUnlitShape, "uProjection", false, proj.array()); frustumMode = false }; p.printProjection = function() { projection.print() }; p.printCamera = function() { cam.print() }; Drawing2D.prototype.box = DrawingShared.prototype.a3DOnlyFunction; Drawing3D.prototype.box = function(w, h, d) { if (!h || !d) h = d = w; var model = new PMatrix3D; model.scale(w, h, d); var view = new PMatrix3D; view.scale(1, -1, 1); view.apply(modelView.array()); view.transpose(); if (doFill) { curContext.useProgram(programObject3D); uniformMatrix("model3d", programObject3D, "uModel", false, model.array()); uniformMatrix("view3d", programObject3D, "uView", false, view.array()); curContext.enable(curContext.POLYGON_OFFSET_FILL); curContext.polygonOffset(1, 1); uniformf("color3d", programObject3D, "uColor", fillStyle); if (lightCount > 0) { var v = new PMatrix3D; v.set(view); var m = new PMatrix3D; m.set(model); v.mult(m); var normalMatrix = new PMatrix3D; normalMatrix.set(v); normalMatrix.invert(); normalMatrix.transpose(); uniformMatrix("uNormalTransform3d", programObject3D, "uNormalTransform", false, normalMatrix.array()); vertexAttribPointer("aNormal3d", programObject3D, "aNormal", 3, boxNormBuffer) } else disableVertexAttribPointer("aNormal3d", programObject3D, "aNormal"); vertexAttribPointer("aVertex3d", programObject3D, "aVertex", 3, boxBuffer); disableVertexAttribPointer("aColor3d", programObject3D, "aColor"); disableVertexAttribPointer("aTexture3d", programObject3D, "aTexture"); curContext.drawArrays(curContext.TRIANGLES, 0, boxVerts.length / 3); curContext.disable(curContext.POLYGON_OFFSET_FILL) } if (lineWidth > 0 && doStroke) { curContext.useProgram(programObject2D); uniformMatrix("uModel2d", programObject2D, "uModel", false, model.array()); uniformMatrix("uView2d", programObject2D, "uView", false, view.array()); uniformf("uColor2d", programObject2D, "uColor", strokeStyle); uniformi("uIsDrawingText2d", programObject2D, "uIsDrawingText", false); vertexAttribPointer("vertex2d", programObject2D, "aVertex", 3, boxOutlineBuffer); disableVertexAttribPointer("aTextureCoord2d", programObject2D, "aTextureCoord"); curContext.drawArrays(curContext.LINES, 0, boxOutlineVerts.length / 3) } }; var initSphere = function() { var i; sphereVerts = []; for (i = 0; i < sphereDetailU; i++) { sphereVerts.push(0); sphereVerts.push(-1); sphereVerts.push(0); sphereVerts.push(sphereX[i]); sphereVerts.push(sphereY[i]); sphereVerts.push(sphereZ[i]) } sphereVerts.push(0); sphereVerts.push(-1); sphereVerts.push(0); sphereVerts.push(sphereX[0]); sphereVerts.push(sphereY[0]); sphereVerts.push(sphereZ[0]); var v1, v11, v2; var voff = 0; for (i = 2; i < sphereDetailV; i++) { v1 = v11 = voff; voff += sphereDetailU; v2 = voff; for (var j = 0; j < sphereDetailU; j++) { sphereVerts.push(sphereX[v1]); sphereVerts.push(sphereY[v1]); sphereVerts.push(sphereZ[v1++]); sphereVerts.push(sphereX[v2]); sphereVerts.push(sphereY[v2]); sphereVerts.push(sphereZ[v2++]) } v1 = v11; v2 = voff; sphereVerts.push(sphereX[v1]); sphereVerts.push(sphereY[v1]); sphereVerts.push(sphereZ[v1]); sphereVerts.push(sphereX[v2]); sphereVerts.push(sphereY[v2]); sphereVerts.push(sphereZ[v2]) } for (i = 0; i < sphereDetailU; i++) { v2 = voff + i; sphereVerts.push(sphereX[v2]); sphereVerts.push(sphereY[v2]); sphereVerts.push(sphereZ[v2]); sphereVerts.push(0); sphereVerts.push(1); sphereVerts.push(0) } sphereVerts.push(sphereX[voff]); sphereVerts.push(sphereY[voff]); sphereVerts.push(sphereZ[voff]); sphereVerts.push(0); sphereVerts.push(1); sphereVerts.push(0); curContext.bindBuffer(curContext.ARRAY_BUFFER, sphereBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(sphereVerts), curContext.STATIC_DRAW) }; p.sphereDetail = function(ures, vres) { var i; if (arguments.length === 1) ures = vres = arguments[0]; if (ures < 3) ures = 3; if (vres < 2) vres = 2; if (ures === sphereDetailU && vres === sphereDetailV) return; var delta = 720 / ures; var cx = new Float32Array(ures); var cz = new Float32Array(ures); for (i = 0; i < ures; i++) { cx[i] = cosLUT[i * delta % 720 | 0]; cz[i] = sinLUT[i * delta % 720 | 0] } var vertCount = ures * (vres - 1) + 2; var currVert = 0; sphereX = new Float32Array(vertCount); sphereY = new Float32Array(vertCount); sphereZ = new Float32Array(vertCount); var angle_step = 720 * 0.5 / vres; var angle = angle_step; for (i = 1; i < vres; i++) { var curradius = sinLUT[angle % 720 | 0]; var currY = -cosLUT[angle % 720 | 0]; for (var j = 0; j < ures; j++) { sphereX[currVert] = cx[j] * curradius; sphereY[currVert] = currY; sphereZ[currVert++] = cz[j] * curradius } angle += angle_step } sphereDetailU = ures; sphereDetailV = vres; initSphere() }; Drawing2D.prototype.sphere = DrawingShared.prototype.a3DOnlyFunction; Drawing3D.prototype.sphere = function() { var sRad = arguments[0]; if (sphereDetailU < 3 || sphereDetailV < 2) p.sphereDetail(30); var model = new PMatrix3D; model.scale(sRad, sRad, sRad); var view = new PMatrix3D; view.scale(1, -1, 1); view.apply(modelView.array()); view.transpose(); if (doFill) { if (lightCount > 0) { var v = new PMatrix3D; v.set(view); var m = new PMatrix3D; m.set(model); v.mult(m); var normalMatrix = new PMatrix3D; normalMatrix.set(v); normalMatrix.invert(); normalMatrix.transpose(); uniformMatrix("uNormalTransform3d", programObject3D, "uNormalTransform", false, normalMatrix.array()); vertexAttribPointer("aNormal3d", programObject3D, "aNormal", 3, sphereBuffer) } else disableVertexAttribPointer("aNormal3d", programObject3D, "aNormal"); curContext.useProgram(programObject3D); disableVertexAttribPointer("aTexture3d", programObject3D, "aTexture"); uniformMatrix("uModel3d", programObject3D, "uModel", false, model.array()); uniformMatrix("uView3d", programObject3D, "uView", false, view.array()); vertexAttribPointer("aVertex3d", programObject3D, "aVertex", 3, sphereBuffer); disableVertexAttribPointer("aColor3d", programObject3D, "aColor"); curContext.enable(curContext.POLYGON_OFFSET_FILL); curContext.polygonOffset(1, 1); uniformf("uColor3d", programObject3D, "uColor", fillStyle); curContext.drawArrays(curContext.TRIANGLE_STRIP, 0, sphereVerts.length / 3); curContext.disable(curContext.POLYGON_OFFSET_FILL) } if (lineWidth > 0 && doStroke) { curContext.useProgram(programObject2D); uniformMatrix("uModel2d", programObject2D, "uModel", false, model.array()); uniformMatrix("uView2d", programObject2D, "uView", false, view.array()); vertexAttribPointer("aVertex2d", programObject2D, "aVertex", 3, sphereBuffer); disableVertexAttribPointer("aTextureCoord2d", programObject2D, "aTextureCoord"); uniformf("uColor2d", programObject2D, "uColor", strokeStyle); uniformi("uIsDrawingText", programObject2D, "uIsDrawingText", false); curContext.drawArrays(curContext.LINE_STRIP, 0, sphereVerts.length / 3) } }; p.modelX = function(x, y, z) { var mv = modelView.array(); var ci = cameraInv.array(); var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; var ox = ci[0] * ax + ci[1] * ay + ci[2] * az + ci[3] * aw; var ow = ci[12] * ax + ci[13] * ay + ci[14] * az + ci[15] * aw; return ow !== 0 ? ox / ow : ox }; p.modelY = function(x, y, z) { var mv = modelView.array(); var ci = cameraInv.array(); var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; var oy = ci[4] * ax + ci[5] * ay + ci[6] * az + ci[7] * aw; var ow = ci[12] * ax + ci[13] * ay + ci[14] * az + ci[15] * aw; return ow !== 0 ? oy / ow : oy }; p.modelZ = function(x, y, z) { var mv = modelView.array(); var ci = cameraInv.array(); var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; var oz = ci[8] * ax + ci[9] * ay + ci[10] * az + ci[11] * aw; var ow = ci[12] * ax + ci[13] * ay + ci[14] * az + ci[15] * aw; return ow !== 0 ? oz / ow : oz }; Drawing2D.prototype.ambient = DrawingShared.prototype.a3DOnlyFunction; Drawing3D.prototype.ambient = function(v1, v2, v3) { curContext.useProgram(programObject3D); uniformi("uUsingMat3d", programObject3D, "uUsingMat", true); var col = p.color(v1, v2, v3); uniformf("uMaterialAmbient3d", programObject3D, "uMaterialAmbient", p.color.toGLArray(col).slice(0, 3)) }; Drawing2D.prototype.emissive = DrawingShared.prototype.a3DOnlyFunction; Drawing3D.prototype.emissive = function(v1, v2, v3) { curContext.useProgram(programObject3D); uniformi("uUsingMat3d", programObject3D, "uUsingMat", true); var col = p.color(v1, v2, v3); uniformf("uMaterialEmissive3d", programObject3D, "uMaterialEmissive", p.color.toGLArray(col).slice(0, 3)) }; Drawing2D.prototype.shininess = DrawingShared.prototype.a3DOnlyFunction; Drawing3D.prototype.shininess = function(shine) { curContext.useProgram(programObject3D); uniformi("uUsingMat3d", programObject3D, "uUsingMat", true); uniformf("uShininess3d", programObject3D, "uShininess", shine) }; Drawing2D.prototype.specular = DrawingShared.prototype.a3DOnlyFunction; Drawing3D.prototype.specular = function(v1, v2, v3) { curContext.useProgram(programObject3D); uniformi("uUsingMat3d", programObject3D, "uUsingMat", true); var col = p.color(v1, v2, v3); uniformf("uMaterialSpecular3d", programObject3D, "uMaterialSpecular", p.color.toGLArray(col).slice(0, 3)) }; p.screenX = function(x, y, z) { var mv = modelView.array(); if (mv.length === 16) { var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; var pj = projection.array(); var ox = pj[0] * ax + pj[1] * ay + pj[2] * az + pj[3] * aw; var ow = pj[12] * ax + pj[13] * ay + pj[14] * az + pj[15] * aw; if (ow !== 0) ox /= ow; return p.width * (1 + ox) / 2 } return modelView.multX(x, y) }; p.screenY = function screenY(x, y, z) { var mv = modelView.array(); if (mv.length === 16) { var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; var pj = projection.array(); var oy = pj[4] * ax + pj[5] * ay + pj[6] * az + pj[7] * aw; var ow = pj[12] * ax + pj[13] * ay + pj[14] * az + pj[15] * aw; if (ow !== 0) oy /= ow; return p.height * (1 + oy) / 2 } return modelView.multY(x, y) }; p.screenZ = function screenZ(x, y, z) { var mv = modelView.array(); if (mv.length !== 16) return 0; var pj = projection.array(); var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; var oz = pj[8] * ax + pj[9] * ay + pj[10] * az + pj[11] * aw; var ow = pj[12] * ax + pj[13] * ay + pj[14] * az + pj[15] * aw; if (ow !== 0) oz /= ow; return (oz + 1) / 2 }; DrawingShared.prototype.fill = function() { var color = p.color(arguments[0], arguments[1], arguments[2], arguments[3]); if (color === currentFillColor && doFill) return; doFill = true; currentFillColor = color }; Drawing2D.prototype.fill = function() { DrawingShared.prototype.fill.apply(this, arguments); isFillDirty = true }; Drawing3D.prototype.fill = function() { DrawingShared.prototype.fill.apply(this, arguments); fillStyle = p.color.toGLArray(currentFillColor) }; function executeContextFill() { if (doFill) { if (isFillDirty) { curContext.fillStyle = p.color.toString(currentFillColor); isFillDirty = false } curContext.fill() } } p.noFill = function() { doFill = false }; DrawingShared.prototype.stroke = function() { var color = p.color(arguments[0], arguments[1], arguments[2], arguments[3]); if (color === currentStrokeColor && doStroke) return; doStroke = true; currentStrokeColor = color }; Drawing2D.prototype.stroke = function() { DrawingShared.prototype.stroke.apply(this, arguments); isStrokeDirty = true }; Drawing3D.prototype.stroke = function() { DrawingShared.prototype.stroke.apply(this, arguments); strokeStyle = p.color.toGLArray(currentStrokeColor) }; function executeContextStroke() { if (doStroke) { if (isStrokeDirty) { curContext.strokeStyle = p.color.toString(currentStrokeColor); isStrokeDirty = false } curContext.stroke() } } p.noStroke = function() { doStroke = false }; DrawingShared.prototype.strokeWeight = function(w) { lineWidth = w }; Drawing2D.prototype.strokeWeight = function(w) { DrawingShared.prototype.strokeWeight.apply(this, arguments); curContext.lineWidth = w }; Drawing3D.prototype.strokeWeight = function(w) { DrawingShared.prototype.strokeWeight.apply(this, arguments); curContext.useProgram(programObject2D); uniformf("pointSize2d", programObject2D, "uPointSize", w); curContext.useProgram(programObjectUnlitShape); uniformf("pointSizeUnlitShape", programObjectUnlitShape, "uPointSize", w); curContext.lineWidth(w) }; p.strokeCap = function(value) { drawing.$ensureContext().lineCap = value }; p.strokeJoin = function(value) { drawing.$ensureContext().lineJoin = value }; Drawing2D.prototype.smooth = function() { renderSmooth = true; var style = curElement.style; style.setProperty("image-rendering", "optimizeQuality", "important"); style.setProperty("-ms-interpolation-mode", "bicubic", "important"); if (curContext.hasOwnProperty("mozImageSmoothingEnabled")) curContext.mozImageSmoothingEnabled = true }; Drawing3D.prototype.smooth = function() { renderSmooth = true }; Drawing2D.prototype.noSmooth = function() { renderSmooth = false; var style = curElement.style; style.setProperty("image-rendering", "optimizeSpeed", "important"); style.setProperty("image-rendering", "-moz-crisp-edges", "important"); style.setProperty("image-rendering", "-webkit-optimize-contrast", "important"); style.setProperty("image-rendering", "optimize-contrast", "important"); style.setProperty("-ms-interpolation-mode", "nearest-neighbor", "important"); if (curContext.hasOwnProperty("mozImageSmoothingEnabled")) curContext.mozImageSmoothingEnabled = false }; Drawing3D.prototype.noSmooth = function() { renderSmooth = false }; Drawing2D.prototype.point = function(x, y) { if (!doStroke) return; x = Math.round(x); y = Math.round(y); curContext.fillStyle = p.color.toString(currentStrokeColor); isFillDirty = true; if (lineWidth > 1) { curContext.beginPath(); curContext.arc(x, y, lineWidth / 2, 0, 6.283185307179586, false); curContext.fill() } else curContext.fillRect(x, y, 1, 1) }; Drawing3D.prototype.point = function(x, y, z) { var model = new PMatrix3D; model.translate(x, y, z || 0); model.transpose(); var view = new PMatrix3D; view.scale(1, -1, 1); view.apply(modelView.array()); view.transpose(); curContext.useProgram(programObject2D); uniformMatrix("uModel2d", programObject2D, "uModel", false, model.array()); uniformMatrix("uView2d", programObject2D, "uView", false, view.array()); if (lineWidth > 0 && doStroke) { uniformf("uColor2d", programObject2D, "uColor", strokeStyle); uniformi("uIsDrawingText2d", programObject2D, "uIsDrawingText", false); uniformi("uSmooth2d", programObject2D, "uSmooth", renderSmooth); vertexAttribPointer("aVertex2d", programObject2D, "aVertex", 3, pointBuffer); disableVertexAttribPointer("aTextureCoord2d", programObject2D, "aTextureCoord"); curContext.drawArrays(curContext.POINTS, 0, 1) } }; p.beginShape = function(type) { curShape = type; curvePoints = []; vertArray = [] }; Drawing2D.prototype.vertex = function(x, y, moveTo) { var vert = []; if (firstVert) firstVert = false; vert["isVert"] = true; vert[0] = x; vert[1] = y; vert[2] = 0; vert[3] = 0; vert[4] = 0; vert[5] = currentFillColor; vert[6] = currentStrokeColor; vertArray.push(vert); if (moveTo) vertArray[vertArray.length - 1]["moveTo"] = moveTo }; Drawing3D.prototype.vertex = function(x, y, z, u, v) { var vert = []; if (firstVert) firstVert = false; vert["isVert"] = true; if (v === undef && usingTexture) { v = u; u = z; z = 0 } if (u !== undef && v !== undef) { if (curTextureMode === 2) { u /= curTexture.width; v /= curTexture.height } u = u > 1 ? 1 : u; u = u < 0 ? 0 : u; v = v > 1 ? 1 : v; v = v < 0 ? 0 : v } vert[0] = x; vert[1] = y; vert[2] = z || 0; vert[3] = u || 0; vert[4] = v || 0; vert[5] = fillStyle[0]; vert[6] = fillStyle[1]; vert[7] = fillStyle[2]; vert[8] = fillStyle[3]; vert[9] = strokeStyle[0]; vert[10] = strokeStyle[1]; vert[11] = strokeStyle[2]; vert[12] = strokeStyle[3]; vert[13] = normalX; vert[14] = normalY; vert[15] = normalZ; vertArray.push(vert) }; var point3D = function(vArray, cArray) { var view = new PMatrix3D; view.scale(1, -1, 1); view.apply(modelView.array()); view.transpose(); curContext.useProgram(programObjectUnlitShape); uniformMatrix("uViewUS", programObjectUnlitShape, "uView", false, view.array()); uniformi("uSmoothUS", programObjectUnlitShape, "uSmooth", renderSmooth); vertexAttribPointer("aVertexUS", programObjectUnlitShape, "aVertex", 3, pointBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(vArray), curContext.STREAM_DRAW); vertexAttribPointer("aColorUS", programObjectUnlitShape, "aColor", 4, fillColorBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(cArray), curContext.STREAM_DRAW); curContext.drawArrays(curContext.POINTS, 0, vArray.length / 3) }; var line3D = function(vArray, mode, cArray) { var ctxMode; if (mode === "LINES") ctxMode = curContext.LINES; else if (mode === "LINE_LOOP") ctxMode = curContext.LINE_LOOP; else ctxMode = curContext.LINE_STRIP; var view = new PMatrix3D; view.scale(1, -1, 1); view.apply(modelView.array()); view.transpose(); curContext.useProgram(programObjectUnlitShape); uniformMatrix("uViewUS", programObjectUnlitShape, "uView", false, view.array()); vertexAttribPointer("aVertexUS", programObjectUnlitShape, "aVertex", 3, lineBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(vArray), curContext.STREAM_DRAW); vertexAttribPointer("aColorUS", programObjectUnlitShape, "aColor", 4, strokeColorBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(cArray), curContext.STREAM_DRAW); curContext.drawArrays(ctxMode, 0, vArray.length / 3) }; var fill3D = function(vArray, mode, cArray, tArray) { var ctxMode; if (mode === "TRIANGLES") ctxMode = curContext.TRIANGLES; else if (mode === "TRIANGLE_FAN") ctxMode = curContext.TRIANGLE_FAN; else ctxMode = curContext.TRIANGLE_STRIP; var view = new PMatrix3D; view.scale(1, -1, 1); view.apply(modelView.array()); view.transpose(); curContext.useProgram(programObject3D); uniformMatrix("model3d", programObject3D, "uModel", false, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); uniformMatrix("view3d", programObject3D, "uView", false, view.array()); curContext.enable(curContext.POLYGON_OFFSET_FILL); curContext.polygonOffset(1, 1); uniformf("color3d", programObject3D, "uColor", [-1, 0, 0, 0]); vertexAttribPointer("vertex3d", programObject3D, "aVertex", 3, fillBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(vArray), curContext.STREAM_DRAW); if (usingTexture && curTint !== null) curTint3d(cArray); vertexAttribPointer("aColor3d", programObject3D, "aColor", 4, fillColorBuffer); curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(cArray), curContext.STREAM_DRAW); disableVertexAttribPointer("aNormal3d", programObject3D, "aNormal"); if (usingTexture) { uniformi("uUsingTexture3d", programObject3D, "uUsingTexture", usingTexture); vertexAttribPointer("aTexture3d", programObject3D, "aTexture", 2, shapeTexVBO); curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(tArray), curContext.STREAM_DRAW) } curContext.drawArrays(ctxMode, 0, vArray.length / 3); curContext.disable(curContext.POLYGON_OFFSET_FILL) }; function fillStrokeClose() { executeContextFill(); executeContextStroke(); curContext.closePath() } Drawing2D.prototype.endShape = function(mode) { if (vertArray.length === 0) return; var closeShape = mode === 2; if (closeShape) vertArray.push(vertArray[0]); var lineVertArray = []; var fillVertArray = []; var colorVertArray = []; var strokeVertArray = []; var texVertArray = []; var cachedVertArray; firstVert = true; var i, j, k; var vertArrayLength = vertArray.length; for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; for (j = 0; j < 3; j++) fillVertArray.push(cachedVertArray[j]) } for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; for (j = 5; j < 9; j++) colorVertArray.push(cachedVertArray[j]) } for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; for (j = 9; j < 13; j++) strokeVertArray.push(cachedVertArray[j]) } for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; texVertArray.push(cachedVertArray[3]); texVertArray.push(cachedVertArray[4]) } if (isCurve && (curShape === 20 || curShape === undef)) { if (vertArrayLength > 3) { var b = [], s = 1 - curTightness; curContext.beginPath(); curContext.moveTo(vertArray[1][0], vertArray[1][1]); for (i = 1; i + 2 < vertArrayLength; i++) { cachedVertArray = vertArray[i]; b[0] = [cachedVertArray[0], cachedVertArray[1]]; b[1] = [cachedVertArray[0] + (s * vertArray[i + 1][0] - s * vertArray[i - 1][0]) / 6, cachedVertArray[1] + (s * vertArray[i + 1][1] - s * vertArray[i - 1][1]) / 6]; b[2] = [vertArray[i + 1][0] + (s * vertArray[i][0] - s * vertArray[i + 2][0]) / 6, vertArray[i + 1][1] + (s * vertArray[i][1] - s * vertArray[i + 2][1]) / 6]; b[3] = [vertArray[i + 1][0], vertArray[i + 1][1]]; curContext.bezierCurveTo(b[1][0], b[1][1], b[2][0], b[2][1], b[3][0], b[3][1]) } fillStrokeClose() } } else if (isBezier && (curShape === 20 || curShape === undef)) { curContext.beginPath(); for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; if (vertArray[i]["isVert"]) if (vertArray[i]["moveTo"]) curContext.moveTo(cachedVertArray[0], cachedVertArray[1]); else curContext.lineTo(cachedVertArray[0], cachedVertArray[1]); else curContext.bezierCurveTo(vertArray[i][0], vertArray[i][1], vertArray[i][2], vertArray[i][3], vertArray[i][4], vertArray[i][5]) } fillStrokeClose() } else if (curShape === 2) for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; if (doStroke) p.stroke(cachedVertArray[6]); p.point(cachedVertArray[0], cachedVertArray[1]) } else if (curShape === 4) for (i = 0; i + 1 < vertArrayLength; i += 2) { cachedVertArray = vertArray[i]; if (doStroke) p.stroke(vertArray[i + 1][6]); p.line(cachedVertArray[0], cachedVertArray[1], vertArray[i + 1][0], vertArray[i + 1][1]) } else if (curShape === 9) for (i = 0; i + 2 < vertArrayLength; i += 3) { cachedVertArray = vertArray[i]; curContext.beginPath(); curContext.moveTo(cachedVertArray[0], cachedVertArray[1]); curContext.lineTo(vertArray[i + 1][0], vertArray[i + 1][1]); curContext.lineTo(vertArray[i + 2][0], vertArray[i + 2][1]); curContext.lineTo(cachedVertArray[0], cachedVertArray[1]); if (doFill) { p.fill(vertArray[i + 2][5]); executeContextFill() } if (doStroke) { p.stroke(vertArray[i + 2][6]); executeContextStroke() } curContext.closePath() } else if (curShape === 10) for (i = 0; i + 1 < vertArrayLength; i++) { cachedVertArray = vertArray[i]; curContext.beginPath(); curContext.moveTo(vertArray[i + 1][0], vertArray[i + 1][1]); curContext.lineTo(cachedVertArray[0], cachedVertArray[1]); if (doStroke) p.stroke(vertArray[i + 1][6]); if (doFill) p.fill(vertArray[i + 1][5]); if (i + 2 < vertArrayLength) { curContext.lineTo(vertArray[i + 2][0], vertArray[i + 2][1]); if (doStroke) p.stroke(vertArray[i + 2][6]); if (doFill) p.fill(vertArray[i + 2][5]) } fillStrokeClose() } else if (curShape === 11) { if (vertArrayLength > 2) { curContext.beginPath(); curContext.moveTo(vertArray[0][0], vertArray[0][1]); curContext.lineTo(vertArray[1][0], vertArray[1][1]); curContext.lineTo(vertArray[2][0], vertArray[2][1]); if (doFill) { p.fill(vertArray[2][5]); executeContextFill() } if (doStroke) { p.stroke(vertArray[2][6]); executeContextStroke() } curContext.closePath(); for (i = 3; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; curContext.beginPath(); curContext.moveTo(vertArray[0][0], vertArray[0][1]); curContext.lineTo(vertArray[i - 1][0], vertArray[i - 1][1]); curContext.lineTo(cachedVertArray[0], cachedVertArray[1]); if (doFill) { p.fill(cachedVertArray[5]); executeContextFill() } if (doStroke) { p.stroke(cachedVertArray[6]); executeContextStroke() } curContext.closePath() } } } else if (curShape === 16) for (i = 0; i + 3 < vertArrayLength; i += 4) { cachedVertArray = vertArray[i]; curContext.beginPath(); curContext.moveTo(cachedVertArray[0], cachedVertArray[1]); for (j = 1; j < 4; j++) curContext.lineTo(vertArray[i + j][0], vertArray[i + j][1]); curContext.lineTo(cachedVertArray[0], cachedVertArray[1]); if (doFill) { p.fill(vertArray[i + 3][5]); executeContextFill() } if (doStroke) { p.stroke(vertArray[i + 3][6]); executeContextStroke() } curContext.closePath() } else if (curShape === 17) { if (vertArrayLength > 3) for (i = 0; i + 1 < vertArrayLength; i += 2) { cachedVertArray = vertArray[i]; curContext.beginPath(); if (i + 3 < vertArrayLength) { curContext.moveTo(vertArray[i + 2][0], vertArray[i + 2][1]); curContext.lineTo(cachedVertArray[0], cachedVertArray[1]); curContext.lineTo(vertArray[i + 1][0], vertArray[i + 1][1]); curContext.lineTo(vertArray[i + 3][0], vertArray[i + 3][1]); if (doFill) p.fill(vertArray[i + 3][5]); if (doStroke) p.stroke(vertArray[i + 3][6]) } else { curContext.moveTo(cachedVertArray[0], cachedVertArray[1]); curContext.lineTo(vertArray[i + 1][0], vertArray[i + 1][1]) } fillStrokeClose() } } else { curContext.beginPath(); curContext.moveTo(vertArray[0][0], vertArray[0][1]); for (i = 1; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; if (cachedVertArray["isVert"]) if (cachedVertArray["moveTo"]) curContext.moveTo(cachedVertArray[0], cachedVertArray[1]); else curContext.lineTo(cachedVertArray[0], cachedVertArray[1]) } fillStrokeClose() } isCurve = false; isBezier = false; curveVertArray = []; curveVertCount = 0; if (closeShape) vertArray.pop() }; Drawing3D.prototype.endShape = function(mode) { if (vertArray.length === 0) return; var closeShape = mode === 2; var lineVertArray = []; var fillVertArray = []; var colorVertArray = []; var strokeVertArray = []; var texVertArray = []; var cachedVertArray; firstVert = true; var i, j, k; var vertArrayLength = vertArray.length; for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; for (j = 0; j < 3; j++) fillVertArray.push(cachedVertArray[j]) } for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; for (j = 5; j < 9; j++) colorVertArray.push(cachedVertArray[j]) } for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; for (j = 9; j < 13; j++) strokeVertArray.push(cachedVertArray[j]) } for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; texVertArray.push(cachedVertArray[3]); texVertArray.push(cachedVertArray[4]) } if (closeShape) { fillVertArray.push(vertArray[0][0]); fillVertArray.push(vertArray[0][1]); fillVertArray.push(vertArray[0][2]); for (i = 5; i < 9; i++) colorVertArray.push(vertArray[0][i]); for (i = 9; i < 13; i++) strokeVertArray.push(vertArray[0][i]); texVertArray.push(vertArray[0][3]); texVertArray.push(vertArray[0][4]) } if (isCurve && (curShape === 20 || curShape === undef)) { lineVertArray = fillVertArray; if (doStroke) line3D(lineVertArray, null, strokeVertArray); if (doFill) fill3D(fillVertArray, null, colorVertArray) } else if (isBezier && (curShape === 20 || curShape === undef)) { lineVertArray = fillVertArray; lineVertArray.splice(lineVertArray.length - 3); strokeVertArray.splice(strokeVertArray.length - 4); if (doStroke) line3D(lineVertArray, null, strokeVertArray); if (doFill) fill3D(fillVertArray, "TRIANGLES", colorVertArray) } else { if (curShape === 2) { for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; for (j = 0; j < 3; j++) lineVertArray.push(cachedVertArray[j]) } point3D(lineVertArray, strokeVertArray) } else if (curShape === 4) { for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; for (j = 0; j < 3; j++) lineVertArray.push(cachedVertArray[j]) } for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; for (j = 5; j < 9; j++) colorVertArray.push(cachedVertArray[j]) } line3D(lineVertArray, "LINES", strokeVertArray) } else if (curShape === 9) { if (vertArrayLength > 2) for (i = 0; i + 2 < vertArrayLength; i += 3) { fillVertArray = []; texVertArray = []; lineVertArray = []; colorVertArray = []; strokeVertArray = []; for (j = 0; j < 3; j++) for (k = 0; k < 3; k++) { lineVertArray.push(vertArray[i + j][k]); fillVertArray.push(vertArray[i + j][k]) } for (j = 0; j < 3; j++) for (k = 3; k < 5; k++) texVertArray.push(vertArray[i + j][k]); for (j = 0; j < 3; j++) for (k = 5; k < 9; k++) { colorVertArray.push(vertArray[i + j][k]); strokeVertArray.push(vertArray[i + j][k + 4]) } if (doStroke) line3D(lineVertArray, "LINE_LOOP", strokeVertArray); if (doFill || usingTexture) fill3D(fillVertArray, "TRIANGLES", colorVertArray, texVertArray) } } else if (curShape === 10) { if (vertArrayLength > 2) for (i = 0; i + 2 < vertArrayLength; i++) { lineVertArray = []; fillVertArray = []; strokeVertArray = []; colorVertArray = []; texVertArray = []; for (j = 0; j < 3; j++) for (k = 0; k < 3; k++) { lineVertArray.push(vertArray[i + j][k]); fillVertArray.push(vertArray[i + j][k]) } for (j = 0; j < 3; j++) for (k = 3; k < 5; k++) texVertArray.push(vertArray[i + j][k]); for (j = 0; j < 3; j++) for (k = 5; k < 9; k++) { strokeVertArray.push(vertArray[i + j][k + 4]); colorVertArray.push(vertArray[i + j][k]) } if (doFill || usingTexture) fill3D(fillVertArray, "TRIANGLE_STRIP", colorVertArray, texVertArray); if (doStroke) line3D(lineVertArray, "LINE_LOOP", strokeVertArray) } } else if (curShape === 11) { if (vertArrayLength > 2) { for (i = 0; i < 3; i++) { cachedVertArray = vertArray[i]; for (j = 0; j < 3; j++) lineVertArray.push(cachedVertArray[j]) } for (i = 0; i < 3; i++) { cachedVertArray = vertArray[i]; for (j = 9; j < 13; j++) strokeVertArray.push(cachedVertArray[j]) } if (doStroke) line3D(lineVertArray, "LINE_LOOP", strokeVertArray); for (i = 2; i + 1 < vertArrayLength; i++) { lineVertArray = []; strokeVertArray = []; lineVertArray.push(vertArray[0][0]); lineVertArray.push(vertArray[0][1]); lineVertArray.push(vertArray[0][2]); strokeVertArray.push(vertArray[0][9]); strokeVertArray.push(vertArray[0][10]); strokeVertArray.push(vertArray[0][11]); strokeVertArray.push(vertArray[0][12]); for (j = 0; j < 2; j++) for (k = 0; k < 3; k++) lineVertArray.push(vertArray[i + j][k]); for (j = 0; j < 2; j++) for (k = 9; k < 13; k++) strokeVertArray.push(vertArray[i + j][k]); if (doStroke) line3D(lineVertArray, "LINE_STRIP", strokeVertArray) } if (doFill || usingTexture) fill3D(fillVertArray, "TRIANGLE_FAN", colorVertArray, texVertArray) } } else if (curShape === 16) for (i = 0; i + 3 < vertArrayLength; i += 4) { lineVertArray = []; for (j = 0; j < 4; j++) { cachedVertArray = vertArray[i + j]; for (k = 0; k < 3; k++) lineVertArray.push(cachedVertArray[k]) } if (doStroke) line3D(lineVertArray, "LINE_LOOP", strokeVertArray); if (doFill) { fillVertArray = []; colorVertArray = []; texVertArray = []; for (j = 0; j < 3; j++) fillVertArray.push(vertArray[i][j]); for (j = 5; j < 9; j++) colorVertArray.push(vertArray[i][j]); for (j = 0; j < 3; j++) fillVertArray.push(vertArray[i + 1][j]); for (j = 5; j < 9; j++) colorVertArray.push(vertArray[i + 1][j]); for (j = 0; j < 3; j++) fillVertArray.push(vertArray[i + 3][j]); for (j = 5; j < 9; j++) colorVertArray.push(vertArray[i + 3][j]); for (j = 0; j < 3; j++) fillVertArray.push(vertArray[i + 2][j]); for (j = 5; j < 9; j++) colorVertArray.push(vertArray[i + 2][j]); if (usingTexture) { texVertArray.push(vertArray[i + 0][3]); texVertArray.push(vertArray[i + 0][4]); texVertArray.push(vertArray[i + 1][3]); texVertArray.push(vertArray[i + 1][4]); texVertArray.push(vertArray[i + 3][3]); texVertArray.push(vertArray[i + 3][4]); texVertArray.push(vertArray[i + 2][3]); texVertArray.push(vertArray[i + 2][4]) } fill3D(fillVertArray, "TRIANGLE_STRIP", colorVertArray, texVertArray) } } else if (curShape === 17) { var tempArray = []; if (vertArrayLength > 3) { for (i = 0; i < 2; i++) { cachedVertArray = vertArray[i]; for (j = 0; j < 3; j++) lineVertArray.push(cachedVertArray[j]) } for (i = 0; i < 2; i++) { cachedVertArray = vertArray[i]; for (j = 9; j < 13; j++) strokeVertArray.push(cachedVertArray[j]) } line3D(lineVertArray, "LINE_STRIP", strokeVertArray); if (vertArrayLength > 4 && vertArrayLength % 2 > 0) { tempArray = fillVertArray.splice(fillVertArray.length - 3); vertArray.pop() } for (i = 0; i + 3 < vertArrayLength; i += 2) { lineVertArray = []; strokeVertArray = []; for (j = 0; j < 3; j++) lineVertArray.push(vertArray[i + 1][j]); for (j = 0; j < 3; j++) lineVertArray.push(vertArray[i + 3][j]); for (j = 0; j < 3; j++) lineVertArray.push(vertArray[i + 2][j]); for (j = 0; j < 3; j++) lineVertArray.push(vertArray[i + 0][j]); for (j = 9; j < 13; j++) strokeVertArray.push(vertArray[i + 1][j]); for (j = 9; j < 13; j++) strokeVertArray.push(vertArray[i + 3][j]); for (j = 9; j < 13; j++) strokeVertArray.push(vertArray[i + 2][j]); for (j = 9; j < 13; j++) strokeVertArray.push(vertArray[i + 0][j]); if (doStroke) line3D(lineVertArray, "LINE_STRIP", strokeVertArray) } if (doFill || usingTexture) fill3D(fillVertArray, "TRIANGLE_LIST", colorVertArray, texVertArray) } } else if (vertArrayLength === 1) { for (j = 0; j < 3; j++) lineVertArray.push(vertArray[0][j]); for (j = 9; j < 13; j++) strokeVertArray.push(vertArray[0][j]); point3D(lineVertArray, strokeVertArray) } else { for (i = 0; i < vertArrayLength; i++) { cachedVertArray = vertArray[i]; for (j = 0; j < 3; j++) lineVertArray.push(cachedVertArray[j]); for (j = 5; j < 9; j++) strokeVertArray.push(cachedVertArray[j]) } if (doStroke && closeShape) line3D(lineVertArray, "LINE_LOOP", strokeVertArray); else if (doStroke && !closeShape) line3D(lineVertArray, "LINE_STRIP", strokeVertArray); if (doFill || usingTexture) fill3D(fillVertArray, "TRIANGLE_FAN", colorVertArray, texVertArray) } usingTexture = false; curContext.useProgram(programObject3D); uniformi("usingTexture3d", programObject3D, "uUsingTexture", usingTexture) } isCurve = false; isBezier = false; curveVertArray = []; curveVertCount = 0 }; var splineForward = function(segments, matrix) { var f = 1 / segments; var ff = f * f; var fff = ff * f; matrix.set(0, 0, 0, 1, fff, ff, f, 0, 6 * fff, 2 * ff, 0, 0, 6 * fff, 0, 0, 0) }; var curveInit = function() { if (!curveDrawMatrix) { curveBasisMatrix = new PMatrix3D; curveDrawMatrix = new PMatrix3D; curveInited = true } var s = curTightness; curveBasisMatrix.set((s - 1) / 2, (s + 3) / 2, (-3 - s) / 2, (1 - s) / 2, 1 - s, (-5 - s) / 2, s + 2, (s - 1) / 2, (s - 1) / 2, 0, (1 - s) / 2, 0, 0, 1, 0, 0); splineForward(curveDet, curveDrawMatrix); if (!bezierBasisInverse) curveToBezierMatrix = new PMatrix3D; curveToBezierMatrix.set(curveBasisMatrix); curveToBezierMatrix.preApply(bezierBasisInverse); curveDrawMatrix.apply(curveBasisMatrix) }; Drawing2D.prototype.bezierVertex = function() { isBezier = true; var vert = []; if (firstVert) throw "vertex() must be used at least once before calling bezierVertex()"; for (var i = 0; i < arguments.length; i++) vert[i] = arguments[i]; vertArray.push(vert); vertArray[vertArray.length - 1]["isVert"] = false }; Drawing3D.prototype.bezierVertex = function() { isBezier = true; var vert = []; if (firstVert) throw "vertex() must be used at least once before calling bezierVertex()"; if (arguments.length === 9) { if (bezierDrawMatrix === undef) bezierDrawMatrix = new PMatrix3D; var lastPoint = vertArray.length - 1; splineForward(bezDetail, bezierDrawMatrix); bezierDrawMatrix.apply(bezierBasisMatrix); var draw = bezierDrawMatrix.array(); var x1 = vertArray[lastPoint][0], y1 = vertArray[lastPoint][1], z1 = vertArray[lastPoint][2]; var xplot1 = draw[4] * x1 + draw[5] * arguments[0] + draw[6] * arguments[3] + draw[7] * arguments[6]; var xplot2 = draw[8] * x1 + draw[9] * arguments[0] + draw[10] * arguments[3] + draw[11] * arguments[6]; var xplot3 = draw[12] * x1 + draw[13] * arguments[0] + draw[14] * arguments[3] + draw[15] * arguments[6]; var yplot1 = draw[4] * y1 + draw[5] * arguments[1] + draw[6] * arguments[4] + draw[7] * arguments[7]; var yplot2 = draw[8] * y1 + draw[9] * arguments[1] + draw[10] * arguments[4] + draw[11] * arguments[7]; var yplot3 = draw[12] * y1 + draw[13] * arguments[1] + draw[14] * arguments[4] + draw[15] * arguments[7]; var zplot1 = draw[4] * z1 + draw[5] * arguments[2] + draw[6] * arguments[5] + draw[7] * arguments[8]; var zplot2 = draw[8] * z1 + draw[9] * arguments[2] + draw[10] * arguments[5] + draw[11] * arguments[8]; var zplot3 = draw[12] * z1 + draw[13] * arguments[2] + draw[14] * arguments[5] + draw[15] * arguments[8]; for (var j = 0; j < bezDetail; j++) { x1 += xplot1; xplot1 += xplot2; xplot2 += xplot3; y1 += yplot1; yplot1 += yplot2; yplot2 += yplot3; z1 += zplot1; zplot1 += zplot2; zplot2 += zplot3; p.vertex(x1, y1, z1) } p.vertex(arguments[6], arguments[7], arguments[8]) } }; p.texture = function(pimage) { var curContext = drawing.$ensureContext(); if (pimage.__texture) curContext.bindTexture(curContext.TEXTURE_2D, pimage.__texture); else if (pimage.localName === "canvas") { curContext.bindTexture(curContext.TEXTURE_2D, canTex); curContext.texImage2D(curContext.TEXTURE_2D, 0, curContext.RGBA, curContext.RGBA, curContext.UNSIGNED_BYTE, pimage); curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_MAG_FILTER, curContext.LINEAR); curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_MIN_FILTER, curContext.LINEAR); curContext.generateMipmap(curContext.TEXTURE_2D); curTexture.width = pimage.width; curTexture.height = pimage.height } else { var texture = curContext.createTexture(), cvs = document.createElement("canvas"), cvsTextureCtx = cvs.getContext("2d"), pot; if (pimage.width & pimage.width - 1 === 0) cvs.width = pimage.width; else { pot = 1; while (pot < pimage.width) pot *= 2; cvs.width = pot } if (pimage.height & pimage.height - 1 === 0) cvs.height = pimage.height; else { pot = 1; while (pot < pimage.height) pot *= 2; cvs.height = pot } cvsTextureCtx.drawImage(pimage.sourceImg, 0, 0, pimage.width, pimage.height, 0, 0, cvs.width, cvs.height); curContext.bindTexture(curContext.TEXTURE_2D, texture); curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_MIN_FILTER, curContext.LINEAR_MIPMAP_LINEAR); curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_MAG_FILTER, curContext.LINEAR); curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_WRAP_T, curContext.CLAMP_TO_EDGE); curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_WRAP_S, curContext.CLAMP_TO_EDGE); curContext.texImage2D(curContext.TEXTURE_2D, 0, curContext.RGBA, curContext.RGBA, curContext.UNSIGNED_BYTE, cvs); curContext.generateMipmap(curContext.TEXTURE_2D); pimage.__texture = texture; curTexture.width = pimage.width; curTexture.height = pimage.height } usingTexture = true; curContext.useProgram(programObject3D); uniformi("usingTexture3d", programObject3D, "uUsingTexture", usingTexture) }; p.textureMode = function(mode) { curTextureMode = mode }; var curveVertexSegment = function(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) { var x0 = x2; var y0 = y2; var z0 = z2; var draw = curveDrawMatrix.array(); var xplot1 = draw[4] * x1 + draw[5] * x2 + draw[6] * x3 + draw[7] * x4; var xplot2 = draw[8] * x1 + draw[9] * x2 + draw[10] * x3 + draw[11] * x4; var xplot3 = draw[12] * x1 + draw[13] * x2 + draw[14] * x3 + draw[15] * x4; var yplot1 = draw[4] * y1 + draw[5] * y2 + draw[6] * y3 + draw[7] * y4; var yplot2 = draw[8] * y1 + draw[9] * y2 + draw[10] * y3 + draw[11] * y4; var yplot3 = draw[12] * y1 + draw[13] * y2 + draw[14] * y3 + draw[15] * y4; var zplot1 = draw[4] * z1 + draw[5] * z2 + draw[6] * z3 + draw[7] * z4; var zplot2 = draw[8] * z1 + draw[9] * z2 + draw[10] * z3 + draw[11] * z4; var zplot3 = draw[12] * z1 + draw[13] * z2 + draw[14] * z3 + draw[15] * z4; p.vertex(x0, y0, z0); for (var j = 0; j < curveDet; j++) { x0 += xplot1; xplot1 += xplot2; xplot2 += xplot3; y0 += yplot1; yplot1 += yplot2; yplot2 += yplot3; z0 += zplot1; zplot1 += zplot2; zplot2 += zplot3; p.vertex(x0, y0, z0) } }; Drawing2D.prototype.curveVertex = function(x, y) { isCurve = true; p.vertex(x, y) }; Drawing3D.prototype.curveVertex = function(x, y, z) { isCurve = true; if (!curveInited) curveInit(); var vert = []; vert[0] = x; vert[1] = y; vert[2] = z; curveVertArray.push(vert); curveVertCount++; if (curveVertCount > 3) curveVertexSegment(curveVertArray[curveVertCount - 4][0], curveVertArray[curveVertCount - 4][1], curveVertArray[curveVertCount - 4][2], curveVertArray[curveVertCount - 3][0], curveVertArray[curveVertCount - 3][1], curveVertArray[curveVertCount - 3][2], curveVertArray[curveVertCount - 2][0], curveVertArray[curveVertCount - 2][1], curveVertArray[curveVertCount - 2][2], curveVertArray[curveVertCount - 1][0], curveVertArray[curveVertCount - 1][1], curveVertArray[curveVertCount - 1][2]) }; Drawing2D.prototype.curve = function(x1, y1, x2, y2, x3, y3, x4, y4) { p.beginShape(); p.curveVertex(x1, y1); p.curveVertex(x2, y2); p.curveVertex(x3, y3); p.curveVertex(x4, y4); p.endShape() }; Drawing3D.prototype.curve = function(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) { if (z4 !== undef) { p.beginShape(); p.curveVertex(x1, y1, z1); p.curveVertex(x2, y2, z2); p.curveVertex(x3, y3, z3); p.curveVertex(x4, y4, z4); p.endShape(); return } p.beginShape(); p.curveVertex(x1, y1); p.curveVertex(z1, x2); p.curveVertex(y2, z2); p.curveVertex(x3, y3); p.endShape() }; p.curveTightness = function(tightness) { curTightness = tightness }; p.curveDetail = function(detail) { curveDet = detail; curveInit() }; p.rectMode = function(aRectMode) { curRectMode = aRectMode }; p.imageMode = function(mode) { switch (mode) { case 0: imageModeConvert = imageModeCorner; break; case 1: imageModeConvert = imageModeCorners; break; case 3: imageModeConvert = imageModeCenter; break; default: throw "Invalid imageMode"; } }; p.ellipseMode = function(aEllipseMode) { curEllipseMode = aEllipseMode }; p.arc = function(x, y, width, height, start, stop) { if (width <= 0 || stop < start) return; if (curEllipseMode === 1) { width = width - x; height = height - y } else if (curEllipseMode === 2) { x = x - width; y = y - height; width = width * 2; height = height * 2 } else if (curEllipseMode === 3) { x = x - width / 2; y = y - height / 2 } while (start < 0) { start += 6.283185307179586; stop += 6.283185307179586 } if (stop - start > 6.283185307179586) { start = 0; stop = 6.283185307179586 } var hr = width / 2, vr = height / 2, centerX = x + hr, centerY = y + vr, startLUT = 0 | 0.5 + start * p.RAD_TO_DEG * 2, stopLUT = 0 | 0.5 + stop * p.RAD_TO_DEG * 2, i, j; if (doFill) { var savedStroke = doStroke; doStroke = false; p.beginShape(); p.vertex(centerX, centerY); for (i = startLUT; i <= stopLUT; i++) { j = i % 720; p.vertex(centerX + cosLUT[j] * hr, centerY + sinLUT[j] * vr) } p.endShape(2); doStroke = savedStroke } if (doStroke) { var savedFill = doFill; doFill = false; p.beginShape(); for (i = startLUT; i <= stopLUT; i++) { j = i % 720; p.vertex(centerX + cosLUT[j] * hr, centerY + sinLUT[j] * vr) } p.endShape(); doFill = savedFill } }; Drawing2D.prototype.line = function(x1, y1, x2, y2) { if (!doStroke) return; x1 = Math.round(x1); x2 = Math.round(x2); y1 = Math.round(y1); y2 = Math.round(y2); if (x1 === x2 && y1 === y2) { p.point(x1, y1); return } var swap = undef, lineCap = undef, drawCrisp = true, currentModelView = modelView.array(), identityMatrix = [1, 0, 0, 0, 1, 0]; for (var i = 0; i < 6 && drawCrisp; i++) drawCrisp = currentModelView[i] === identityMatrix[i]; if (drawCrisp) { if (x1 === x2) { if (y1 > y2) { swap = y1; y1 = y2; y2 = swap } y2++; if (lineWidth % 2 === 1) curContext.translate(0.5, 0) } else if (y1 === y2) { if (x1 > x2) { swap = x1; x1 = x2; x2 = swap } x2++; if (lineWidth % 2 === 1) curContext.translate(0, 0.5) } if (lineWidth === 1) { lineCap = curContext.lineCap; curContext.lineCap = "butt" } } curContext.beginPath(); curContext.moveTo(x1 || 0, y1 || 0); curContext.lineTo(x2 || 0, y2 || 0); executeContextStroke(); if (drawCrisp) { if (x1 === x2 && lineWidth % 2 === 1) curContext.translate(-0.5, 0); else if (y1 === y2 && lineWidth % 2 === 1) curContext.translate(0, -0.5); if (lineWidth === 1) curContext.lineCap = lineCap } }; Drawing3D.prototype.line = function(x1, y1, z1, x2, y2, z2) { if (y2 === undef || z2 === undef) { z2 = 0; y2 = x2; x2 = z1; z1 = 0 } if (x1 === x2 && y1 === y2 && z1 === z2) { p.point(x1, y1, z1); return } var lineVerts = [x1, y1, z1, x2, y2, z2]; var view = new PMatrix3D; view.scale(1, -1, 1); view.apply(modelView.array()); view.transpose(); if (lineWidth > 0 && doStroke) { curContext.useProgram(programObject2D); uniformMatrix("uModel2d", programObject2D, "uModel", false, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); uniformMatrix("uView2d", programObject2D, "uView", false, view.array()); uniformf("uColor2d", programObject2D, "uColor", strokeStyle); uniformi("uIsDrawingText", programObject2D, "uIsDrawingText", false); vertexAttribPointer("aVertex2d", programObject2D, "aVertex", 3, lineBuffer); disableVertexAttribPointer("aTextureCoord2d", programObject2D, "aTextureCoord"); curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(lineVerts), curContext.STREAM_DRAW); curContext.drawArrays(curContext.LINES, 0, 2) } }; Drawing2D.prototype.bezier = function() { if (arguments.length !== 8) throw "You must use 8 parameters for bezier() in 2D mode"; p.beginShape(); p.vertex(arguments[0], arguments[1]); p.bezierVertex(arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7]); p.endShape() }; Drawing3D.prototype.bezier = function() { if (arguments.length !== 12) throw "You must use 12 parameters for bezier() in 3D mode"; p.beginShape(); p.vertex(arguments[0], arguments[1], arguments[2]); p.bezierVertex(arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], arguments[8], arguments[9], arguments[10], arguments[11]); p.endShape() }; p.bezierDetail = function(detail) { bezDetail = detail }; p.bezierPoint = function(a, b, c, d, t) { return (1 - t) * (1 - t) * (1 - t) * a + 3 * (1 - t) * (1 - t) * t * b + 3 * (1 - t) * t * t * c + t * t * t * d }; p.bezierTangent = function(a, b, c, d, t) { return 3 * t * t * (-a + 3 * b - 3 * c + d) + 6 * t * (a - 2 * b + c) + 3 * (-a + b) }; p.curvePoint = function(a, b, c, d, t) { return 0.5 * (2 * b + (-a + c) * t + (2 * a - 5 * b + 4 * c - d) * t * t + (-a + 3 * b - 3 * c + d) * t * t * t) }; p.curveTangent = function(a, b, c, d, t) { return 0.5 * (-a + c + 2 * (2 * a - 5 * b + 4 * c - d) * t + 3 * (-a + 3 * b - 3 * c + d) * t * t) }; p.triangle = function(x1, y1, x2, y2, x3, y3) { p.beginShape(9); p.vertex(x1, y1, 0); p.vertex(x2, y2, 0); p.vertex(x3, y3, 0); p.endShape() }; p.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) { p.beginShape(16); p.vertex(x1, y1, 0); p.vertex(x2, y2, 0); p.vertex(x3, y3, 0); p.vertex(x4, y4, 0); p.endShape() }; var roundedRect$2d = function(x, y, width, height, tl, tr, br, bl) { if (bl === undef) { tr = tl; br = tl; bl = tl } var halfWidth = width / 2, halfHeight = height / 2; if (tl > halfWidth || tl > halfHeight) tl = Math.min(halfWidth, halfHeight); if (tr > halfWidth || tr > halfHeight) tr = Math.min(halfWidth, halfHeight); if (br > halfWidth || br > halfHeight) br = Math.min(halfWidth, halfHeight); if (bl > halfWidth || bl > halfHeight) bl = Math.min(halfWidth, halfHeight); if (!doFill || doStroke) curContext.translate(0.5, 0.5); curContext.beginPath(); curContext.moveTo(x + tl, y); curContext.lineTo(x + width - tr, y); curContext.quadraticCurveTo(x + width, y, x + width, y + tr); curContext.lineTo(x + width, y + height - br); curContext.quadraticCurveTo(x + width, y + height, x + width - br, y + height); curContext.lineTo(x + bl, y + height); curContext.quadraticCurveTo(x, y + height, x, y + height - bl); curContext.lineTo(x, y + tl); curContext.quadraticCurveTo(x, y, x + tl, y); if (!doFill || doStroke) curContext.translate(-0.5, -0.5); executeContextFill(); executeContextStroke() }; Drawing2D.prototype.rect = function(x, y, width, height, tl, tr, br, bl) { if (!width && !height) return; if (curRectMode === 1) { width -= x; height -= y } else if (curRectMode === 2) { width *= 2; height *= 2; x -= width / 2; y -= height / 2 } else if (curRectMode === 3) { x -= width / 2; y -= height / 2 } x = Math.round(x); y = Math.round(y); width = Math.round(width); height = Math.round(height); if (tl !== undef) { roundedRect$2d(x, y, width, height, tl, tr, br, bl); return } if (doStroke && lineWidth % 2 === 1) curContext.translate(0.5, 0.5); curContext.beginPath(); curContext.rect(x, y, width, height); executeContextFill(); executeContextStroke(); if (doStroke && lineWidth % 2 === 1) curContext.translate(-0.5, -0.5) }; Drawing3D.prototype.rect = function(x, y, width, height, tl, tr, br, bl) { if (tl !== undef) throw "rect() with rounded corners is not supported in 3D mode"; if (curRectMode === 1) { width -= x; height -= y } else if (curRectMode === 2) { width *= 2; height *= 2; x -= width / 2; y -= height / 2 } else if (curRectMode === 3) { x -= width / 2; y -= height / 2 } var model = new PMatrix3D; model.translate(x, y, 0); model.scale(width, height, 1); model.transpose(); var view = new PMatrix3D; view.scale(1, -1, 1); view.apply(modelView.array()); view.transpose(); if (lineWidth > 0 && doStroke) { curContext.useProgram(programObject2D); uniformMatrix("uModel2d", programObject2D, "uModel", false, model.array()); uniformMatrix("uView2d", programObject2D, "uView", false, view.array()); uniformf("uColor2d", programObject2D, "uColor", strokeStyle); uniformi("uIsDrawingText2d", programObject2D, "uIsDrawingText", false); vertexAttribPointer("aVertex2d", programObject2D, "aVertex", 3, rectBuffer); disableVertexAttribPointer("aTextureCoord2d", programObject2D, "aTextureCoord"); curContext.drawArrays(curContext.LINE_LOOP, 0, rectVerts.length / 3) } if (doFill) { curContext.useProgram(programObject3D); uniformMatrix("uModel3d", programObject3D, "uModel", false, model.array()); uniformMatrix("uView3d", programObject3D, "uView", false, view.array()); curContext.enable(curContext.POLYGON_OFFSET_FILL); curContext.polygonOffset(1, 1); uniformf("color3d", programObject3D, "uColor", fillStyle); if (lightCount > 0) { var v = new PMatrix3D; v.set(view); var m = new PMatrix3D; m.set(model); v.mult(m); var normalMatrix = new PMatrix3D; normalMatrix.set(v); normalMatrix.invert(); normalMatrix.transpose(); uniformMatrix("uNormalTransform3d", programObject3D, "uNormalTransform", false, normalMatrix.array()); vertexAttribPointer("aNormal3d", programObject3D, "aNormal", 3, rectNormBuffer) } else disableVertexAttribPointer("normal3d", programObject3D, "aNormal"); vertexAttribPointer("vertex3d", programObject3D, "aVertex", 3, rectBuffer); curContext.drawArrays(curContext.TRIANGLE_FAN, 0, rectVerts.length / 3); curContext.disable(curContext.POLYGON_OFFSET_FILL) } }; Drawing2D.prototype.ellipse = function(x, y, width, height) { x = x || 0; y = y || 0; if (width <= 0 && height <= 0) return; if (curEllipseMode === 2) { width *= 2; height *= 2 } else if (curEllipseMode === 1) { width = width - x; height = height - y; x += width / 2; y += height / 2 } else if (curEllipseMode === 0) { x += width / 2; y += height / 2 } if (width === height) { curContext.beginPath(); curContext.arc(x, y, width / 2, 0, 6.283185307179586, false); executeContextFill(); executeContextStroke() } else { var w = width / 2, h = height / 2, C = 0.5522847498307933, c_x = C * w, c_y = C * h; p.beginShape(); p.vertex(x + w, y); p.bezierVertex(x + w, y - c_y, x + c_x, y - h, x, y - h); p.bezierVertex(x - c_x, y - h, x - w, y - c_y, x - w, y); p.bezierVertex(x - w, y + c_y, x - c_x, y + h, x, y + h); p.bezierVertex(x + c_x, y + h, x + w, y + c_y, x + w, y); p.endShape() } }; Drawing3D.prototype.ellipse = function(x, y, width, height) { x = x || 0; y = y || 0; if (width <= 0 && height <= 0) return; if (curEllipseMode === 2) { width *= 2; height *= 2 } else if (curEllipseMode === 1) { width = width - x; height = height - y; x += width / 2; y += height / 2 } else if (curEllipseMode === 0) { x += width / 2; y += height / 2 } var w = width / 2, h = height / 2, C = 0.5522847498307933, c_x = C * w, c_y = C * h; p.beginShape(); p.vertex(x + w, y); p.bezierVertex(x + w, y - c_y, 0, x + c_x, y - h, 0, x, y - h, 0); p.bezierVertex(x - c_x, y - h, 0, x - w, y - c_y, 0, x - w, y, 0); p.bezierVertex(x - w, y + c_y, 0, x - c_x, y + h, 0, x, y + h, 0); p.bezierVertex(x + c_x, y + h, 0, x + w, y + c_y, 0, x + w, y, 0); p.endShape(); if (doFill) { var xAv = 0, yAv = 0, i, j; for (i = 0; i < vertArray.length; i++) { xAv += vertArray[i][0]; yAv += vertArray[i][1] } xAv /= vertArray.length; yAv /= vertArray.length; var vert = [], fillVertArray = [], colorVertArray = []; vert[0] = xAv; vert[1] = yAv; vert[2] = 0; vert[3] = 0; vert[4] = 0; vert[5] = fillStyle[0]; vert[6] = fillStyle[1]; vert[7] = fillStyle[2]; vert[8] = fillStyle[3]; vert[9] = strokeStyle[0]; vert[10] = strokeStyle[1]; vert[11] = strokeStyle[2]; vert[12] = strokeStyle[3]; vert[13] = normalX; vert[14] = normalY; vert[15] = normalZ; vertArray.unshift(vert); for (i = 0; i < vertArray.length; i++) { for (j = 0; j < 3; j++) fillVertArray.push(vertArray[i][j]); for (j = 5; j < 9; j++) colorVertArray.push(vertArray[i][j]) } fill3D(fillVertArray, "TRIANGLE_FAN", colorVertArray) } }; p.normal = function(nx, ny, nz) { if (arguments.length !== 3 || !(typeof nx === "number" && typeof ny === "number" && typeof nz === "number")) throw "normal() requires three numeric arguments."; normalX = nx; normalY = ny; normalZ = nz; if (curShape !== 0) if (normalMode === 0) normalMode = 1; else if (normalMode === 1) normalMode = 2 }; p.save = function(file, img) { if (img !== undef) return window.open(img.toDataURL(), "_blank"); return window.open(p.externals.canvas.toDataURL(), "_blank") }; var saveNumber = 0; p.saveFrame = function(file) { if (file === undef) file = "screen-####.png"; var frameFilename = file.replace(/#+/, function(all) { var s = "" + saveNumber++; while (s.length < all.length) s = "0" + s; return s }); p.save(frameFilename) }; var utilityContext2d = document.createElement("canvas").getContext("2d"); var canvasDataCache = [undef, undef, undef]; function getCanvasData(obj, w, h) { var canvasData = canvasDataCache.shift(); if (canvasData === undef) { canvasData = {}; canvasData.canvas = document.createElement("canvas"); canvasData.context = canvasData.canvas.getContext("2d") } canvasDataCache.push(canvasData); var canvas = canvasData.canvas, context = canvasData.context, width = w || obj.width, height = h || obj.height; canvas.width = width; canvas.height = height; if (!obj) context.clearRect(0, 0, width, height); else if ("data" in obj) context.putImageData(obj, 0, 0); else { context.clearRect(0, 0, width, height); context.drawImage(obj, 0, 0, width, height) } return canvasData } function buildPixelsObject(pImage) { return { getLength: function(aImg) { return function() { if (aImg.isRemote) throw "Image is loaded remotely. Cannot get length."; else return aImg.imageData.data.length ? aImg.imageData.data.length / 4 : 0 } }(pImage), getPixel: function(aImg) { return function(i) { var offset = i * 4, data = aImg.imageData.data; if (aImg.isRemote) throw "Image is loaded remotely. Cannot get pixels."; return (data[offset + 3] & 255) << 24 | (data[offset] & 255) << 16 | (data[offset + 1] & 255) << 8 | data[offset + 2] & 255 } }(pImage), setPixel: function(aImg) { return function(i, c) { var offset = i * 4, data = aImg.imageData.data; if (aImg.isRemote) throw "Image is loaded remotely. Cannot set pixel."; data[offset + 0] = (c >> 16) & 255; data[offset + 1] = (c >> 8) & 255; data[offset + 2] = c & 255; data[offset + 3] = (c >> 24) & 255; aImg.__isDirty = true } }(pImage), toArray: function(aImg) { return function() { var arr = [], data = aImg.imageData.data, length = aImg.width * aImg.height; if (aImg.isRemote) throw "Image is loaded remotely. Cannot get pixels."; for (var i = 0, offset = 0; i < length; i++, offset += 4) arr.push((data[offset + 3] & 255) << 24 | (data[offset] & 255) << 16 | (data[offset + 1] & 255) << 8 | data[offset + 2] & 255); return arr } }(pImage), set: function(aImg) { return function(arr) { var offset, data, c; if (this.isRemote) throw "Image is loaded remotely. Cannot set pixels."; data = aImg.imageData.data; for (var i = 0, aL = arr.length; i < aL; i++) { c = arr[i]; offset = i * 4; data[offset + 0] = (c >> 16) & 255; data[offset + 1] = (c >> 8) & 255; data[offset + 2] = c & 255; data[offset + 3] = (c >> 24) & 255 } aImg.__isDirty = true } }(pImage) } } var PImage = function(aWidth, aHeight, aFormat) { this.__isDirty = false; if (aWidth instanceof HTMLImageElement) this.fromHTMLImageData(aWidth); else if (aHeight || aFormat) { this.width = aWidth || 1; this.height = aHeight || 1; var canvas = this.sourceImg = document.createElement("canvas"); canvas.width = this.width; canvas.height = this.height; var imageData = this.imageData = canvas.getContext("2d").createImageData(this.width, this.height); this.format = aFormat === 2 || aFormat === 4 ? aFormat : 1; if (this.format === 1) for (var i = 3, data = this.imageData.data, len = data.length; i < len; i += 4) data[i] = 255; this.__isDirty = true; this.updatePixels() } else { this.width = 0; this.height = 0; this.imageData = utilityContext2d.createImageData(1, 1); this.format = 2 } this.pixels = buildPixelsObject(this) }; PImage.prototype = { __isPImage: true, updatePixels: function() { var canvas = this.sourceImg; if (canvas && canvas instanceof HTMLCanvasElement && this.__isDirty) canvas.getContext("2d").putImageData(this.imageData, 0, 0); this.__isDirty = false }, fromHTMLImageData: function(htmlImg) { var canvasData = getCanvasData(htmlImg); try { var imageData = canvasData.context.getImageData(0, 0, htmlImg.width, htmlImg.height); this.fromImageData(imageData) } catch(e) { if (htmlImg.width && htmlImg.height) { this.isRemote = true; this.width = htmlImg.width; this.height = htmlImg.height } } this.sourceImg = htmlImg }, "get": function(x, y, w, h) { if (!arguments.length) return p.get(this); if (arguments.length === 2) return p.get(x, y, this); if (arguments.length === 4) return p.get(x, y, w, h, this) }, "set": function(x, y, c) { p.set(x, y, c, this); this.__isDirty = true }, blend: function(srcImg, x, y, width, height, dx, dy, dwidth, dheight, MODE) { if (arguments.length === 9) p.blend(this, srcImg, x, y, width, height, dx, dy, dwidth, dheight, this); else if (arguments.length === 10) p.blend(srcImg, x, y, width, height, dx, dy, dwidth, dheight, MODE, this); delete this.sourceImg }, copy: function(srcImg, sx, sy, swidth, sheight, dx, dy, dwidth, dheight) { if (arguments.length === 8) p.blend(this, srcImg, sx, sy, swidth, sheight, dx, dy, dwidth, 0, this); else if (arguments.length === 9) p.blend(srcImg, sx, sy, swidth, sheight, dx, dy, dwidth, dheight, 0, this); delete this.sourceImg }, filter: function(mode, param) { if (arguments.length === 2) p.filter(mode, param, this); else if (arguments.length === 1) p.filter(mode, null, this); delete this.sourceImg }, save: function(file) { p.save(file, this) }, resize: function(w, h) { if (this.isRemote) throw "Image is loaded remotely. Cannot resize."; if (this.width !== 0 || this.height !== 0) { if (w === 0 && h !== 0) w = Math.floor(this.width / this.height * h); else if (h === 0 && w !== 0) h = Math.floor(this.height / this.width * w); var canvas = getCanvasData(this.imageData).canvas; var imageData = getCanvasData(canvas, w, h).context.getImageData(0, 0, w, h); this.fromImageData(imageData) } }, mask: function(mask) { var obj = this.toImageData(), i, size; if (mask instanceof PImage || mask.__isPImage) if (mask.width === this.width && mask.height === this.height) { mask = mask.toImageData(); for (i = 2, size = this.width * this.height * 4; i < size; i += 4) obj.data[i + 1] = mask.data[i] } else throw "mask must have the same dimensions as PImage."; else if (mask instanceof Array) if (this.width * this.height === mask.length) for (i = 0, size = mask.length; i < size; ++i) obj.data[i * 4 + 3] = mask[i]; else throw "mask array must be the same length as PImage pixels array."; this.fromImageData(obj) }, loadPixels: nop, toImageData: function() { if (this.isRemote) return this.sourceImg; if (!this.__isDirty) return this.imageData; var canvasData = getCanvasData(this.sourceImg); return canvasData.context.getImageData(0, 0, this.width, this.height) }, toDataURL: function() { if (this.isRemote) throw "Image is loaded remotely. Cannot create dataURI."; var canvasData = getCanvasData(this.imageData); return canvasData.canvas.toDataURL() }, fromImageData: function(canvasImg) { var w = canvasImg.width, h = canvasImg.height, canvas = document.createElement("canvas"), ctx = canvas.getContext("2d"); this.width = canvas.width = w; this.height = canvas.height = h; ctx.putImageData(canvasImg, 0, 0); this.format = 2; this.imageData = canvasImg; this.sourceImg = canvas } }; p.PImage = PImage; p.createImage = function(w, h, mode) { return new PImage(w, h, mode) }; p.loadImage = function(file, type, callback) { if (type) file = file + "." + type; var pimg; if (curSketch.imageCache.images[file]) { pimg = new PImage(curSketch.imageCache.images[file]); pimg.loaded = true; return pimg } pimg = new PImage; var img = document.createElement("img"); pimg.sourceImg = img; img.onload = function(aImage, aPImage, aCallback) { var image = aImage; var pimg = aPImage; var callback = aCallback; return function() { pimg.fromHTMLImageData(image); pimg.loaded = true; if (callback) callback() } }(img, pimg, callback); img.src = file; return pimg }; p.requestImage = p.loadImage; function get$2(x, y) { var data; if (x >= p.width || x < 0 || y < 0 || y >= p.height) return 0; if (isContextReplaced) { var offset = ((0 | x) + p.width * (0 | y)) * 4; data = p.imageData.data; return (data[offset + 3] & 255) << 24 | (data[offset] & 255) << 16 | (data[offset + 1] & 255) << 8 | data[offset + 2] & 255 } data = p.toImageData(0 | x, 0 | y, 1, 1).data; return (data[3] & 255) << 24 | (data[0] & 255) << 16 | (data[1] & 255) << 8 | data[2] & 255 } function get$3(x, y, img) { if (img.isRemote) throw "Image is loaded remotely. Cannot get x,y."; var offset = y * img.width * 4 + x * 4, data = img.imageData.data; return (data[offset + 3] & 255) << 24 | (data[offset] & 255) << 16 | (data[offset + 1] & 255) << 8 | data[offset + 2] & 255 } function get$4(x, y, w, h) { var c = new PImage(w, h, 2); c.fromImageData(p.toImageData(x, y, w, h)); return c } function get$5(x, y, w, h, img) { if (img.isRemote) throw "Image is loaded remotely. Cannot get x,y,w,h."; var c = new PImage(w, h, 2), cData = c.imageData.data, imgWidth = img.width, imgHeight = img.height, imgData = img.imageData.data; var startRow = Math.max(0, -y), startColumn = Math.max(0, -x), stopRow = Math.min(h, imgHeight - y), stopColumn = Math.min(w, imgWidth - x); for (var i = startRow; i < stopRow; ++i) { var sourceOffset = ((y + i) * imgWidth + (x + startColumn)) * 4; var targetOffset = (i * w + startColumn) * 4; for (var j = startColumn; j < stopColumn; ++j) { cData[targetOffset++] = imgData[sourceOffset++]; cData[targetOffset++] = imgData[sourceOffset++]; cData[targetOffset++] = imgData[sourceOffset++]; cData[targetOffset++] = imgData[sourceOffset++] } } c.__isDirty = true; return c } p.get = function(x, y, w, h, img) { if (img !== undefined) return get$5(x, y, w, h, img); if (h !== undefined) return get$4(x, y, w, h); if (w !== undefined) return get$3(x, y, w); if (y !== undefined) return get$2(x, y); if (x !== undefined) return get$5(0, 0, x.width, x.height, x); return get$4(0, 0, p.width, p.height) }; p.createGraphics = function(w, h, render) { var pg = new Processing; pg.size(w, h, render); pg.background(0, 0); return pg }; function resetContext() { if (isContextReplaced) { curContext = originalContext; isContextReplaced = false; p.updatePixels() } } function SetPixelContextWrapper() { function wrapFunction(newContext, name) { function wrapper() { resetContext(); curContext[name].apply(curContext, arguments) } newContext[name] = wrapper } function wrapProperty(newContext, name) { function getter() { resetContext(); return curContext[name] } function setter(value) { resetContext(); curContext[name] = value } p.defineProperty(newContext, name, { get: getter, set: setter }) } for (var n in curContext) if (typeof curContext[n] === "function") wrapFunction(this, n); else wrapProperty(this, n) } function replaceContext() { if (isContextReplaced) return; p.loadPixels(); if (proxyContext === null) { originalContext = curContext; proxyContext = new SetPixelContextWrapper } isContextReplaced = true; curContext = proxyContext; setPixelsCached = 0 } function set$3(x, y, c) { if (x < p.width && x >= 0 && y >= 0 && y < p.height) { replaceContext(); p.pixels.setPixel((0 | x) + p.width * (0 | y), c); if (++setPixelsCached > maxPixelsCached) resetContext() } } function set$4(x, y, obj, img) { if (img.isRemote) throw "Image is loaded remotely. Cannot set x,y."; var c = p.color.toArray(obj); var offset = y * img.width * 4 + x * 4; var data = img.imageData.data; data[offset] = c[0]; data[offset + 1] = c[1]; data[offset + 2] = c[2]; data[offset + 3] = c[3] } p.set = function(x, y, obj, img) { var color, oldFill; if (arguments.length === 3) if (typeof obj === "number") set$3(x, y, obj); else { if (obj instanceof PImage || obj.__isPImage) p.image(obj, x, y) } else if (arguments.length === 4) set$4(x, y, obj, img) }; p.imageData = {}; p.pixels = { getLength: function() { return p.imageData.data.length ? p.imageData.data.length / 4 : 0 }, getPixel: function(i) { var offset = i * 4, data = p.imageData.data; return data[offset + 3] << 24 & 4278190080 | data[offset + 0] << 16 & 16711680 | data[offset + 1] << 8 & 65280 | data[offset + 2] & 255 }, setPixel: function(i, c) { var offset = i * 4, data = p.imageData.data; data[offset + 0] = (c & 16711680) >>> 16; data[offset + 1] = (c & 65280) >>> 8; data[offset + 2] = c & 255; data[offset + 3] = (c & 4278190080) >>> 24 }, toArray: function() { var arr = [], length = p.imageData.width * p.imageData.height, data = p.imageData.data; for (var i = 0, offset = 0; i < length; i++, offset += 4) arr.push(data[offset + 3] << 24 & 4278190080 | data[offset + 0] << 16 & 16711680 | data[offset + 1] << 8 & 65280 | data[offset + 2] & 255); return arr }, set: function(arr) { for (var i = 0, aL = arr.length; i < aL; i++) this.setPixel(i, arr[i]) } }; p.loadPixels = function() { p.imageData = drawing.$ensureContext().getImageData(0, 0, p.width, p.height) }; p.updatePixels = function() { if (p.imageData) drawing.$ensureContext().putImageData(p.imageData, 0, 0) }; p.hint = function(which) { var curContext = drawing.$ensureContext(); if (which === 4) { curContext.disable(curContext.DEPTH_TEST); curContext.depthMask(false); curContext.clear(curContext.DEPTH_BUFFER_BIT) } else if (which === -4) { curContext.enable(curContext.DEPTH_TEST); curContext.depthMask(true) } else if (which === -1 || which === 2) renderSmooth = true; else if (which === 1) renderSmooth = false }; var backgroundHelper = function(arg1, arg2, arg3, arg4) { var obj; if (arg1 instanceof PImage || arg1.__isPImage) { obj = arg1; if (!obj.loaded) throw "Error using image in background(): PImage not loaded."; if (obj.width !== p.width || obj.height !== p.height) throw "Background image must be the same dimensions as the canvas."; } else obj = p.color(arg1, arg2, arg3, arg4); backgroundObj = obj }; Drawing2D.prototype.background = function(arg1, arg2, arg3, arg4) { if (arg1 !== undef) backgroundHelper(arg1, arg2, arg3, arg4); if (backgroundObj instanceof PImage || backgroundObj.__isPImage) { saveContext(); curContext.setTransform(1, 0, 0, 1, 0, 0); p.image(backgroundObj, 0, 0); restoreContext() } else { saveContext(); curContext.setTransform(1, 0, 0, 1, 0, 0); if (p.alpha(backgroundObj) !== colorModeA) curContext.clearRect(0, 0, p.width, p.height); curContext.fillStyle = p.color.toString(backgroundObj); curContext.fillRect(0, 0, p.width, p.height); isFillDirty = true; restoreContext() } }; Drawing3D.prototype.background = function(arg1, arg2, arg3, arg4) { if (arguments.length > 0) backgroundHelper(arg1, arg2, arg3, arg4); var c = p.color.toGLArray(backgroundObj); curContext.clearColor(c[0], c[1], c[2], c[3]); curContext.clear(curContext.COLOR_BUFFER_BIT | curContext.DEPTH_BUFFER_BIT) }; Drawing2D.prototype.image = function(img, x, y, w, h) { x = Math.round(x); y = Math.round(y); if (img.width > 0) { var wid = w || img.width; var hgt = h || img.height; var bounds = imageModeConvert(x || 0, y || 0, w || img.width, h || img.height, arguments.length < 4); var fastImage = !!img.sourceImg && curTint === null; if (fastImage) { var htmlElement = img.sourceImg; if (img.__isDirty) img.updatePixels(); curContext.drawImage(htmlElement, 0, 0, htmlElement.width, htmlElement.height, bounds.x, bounds.y, bounds.w, bounds.h) } else { var obj = img.toImageData(); if (curTint !== null) { curTint(obj); img.__isDirty = true } curContext.drawImage(getCanvasData(obj).canvas, 0, 0, img.width, img.height, bounds.x, bounds.y, bounds.w, bounds.h) } } }; Drawing3D.prototype.image = function(img, x, y, w, h) { if (img.width > 0) { x = Math.round(x); y = Math.round(y); w = w || img.width; h = h || img.height; p.beginShape(p.QUADS); p.texture(img); p.vertex(x, y, 0, 0, 0); p.vertex(x, y + h, 0, 0, h); p.vertex(x + w, y + h, 0, w, h); p.vertex(x + w, y, 0, w, 0); p.endShape() } }; p.tint = function(a1, a2, a3, a4) { var tintColor = p.color(a1, a2, a3, a4); var r = p.red(tintColor) / colorModeX; var g = p.green(tintColor) / colorModeY; var b = p.blue(tintColor) / colorModeZ; var a = p.alpha(tintColor) / colorModeA; curTint = function(obj) { var data = obj.data, length = 4 * obj.width * obj.height; for (var i = 0; i < length;) { data[i++] *= r; data[i++] *= g; data[i++] *= b; data[i++] *= a } }; curTint3d = function(data) { for (var i = 0; i < data.length;) { data[i++] = r; data[i++] = g; data[i++] = b; data[i++] = a } } }; p.noTint = function() { curTint = null; curTint3d = null }; p.copy = function(src, sx, sy, sw, sh, dx, dy, dw, dh) { if (dh === undef) { dh = dw; dw = dy; dy = dx; dx = sh; sh = sw; sw = sy; sy = sx; sx = src; src = p } p.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, 0) }; p.blend = function(src, sx, sy, sw, sh, dx, dy, dw, dh, mode, pimgdest) { if (src.isRemote) throw "Image is loaded remotely. Cannot blend image."; if (mode === undef) { mode = dh; dh = dw; dw = dy; dy = dx; dx = sh; sh = sw; sw = sy; sy = sx; sx = src; src = p } var sx2 = sx + sw, sy2 = sy + sh, dx2 = dx + dw, dy2 = dy + dh, dest = pimgdest || p; if (pimgdest === undef || mode === undef) p.loadPixels(); src.loadPixels(); if (src === p && p.intersect(sx, sy, sx2, sy2, dx, dy, dx2, dy2)) p.blit_resize(p.get(sx, sy, sx2 - sx, sy2 - sy), 0, 0, sx2 - sx - 1, sy2 - sy - 1, dest.imageData.data, dest.width, dest.height, dx, dy, dx2, dy2, mode); else p.blit_resize(src, sx, sy, sx2, sy2, dest.imageData.data, dest.width, dest.height, dx, dy, dx2, dy2, mode); if (pimgdest === undef) p.updatePixels() }; var buildBlurKernel = function(r) { var radius = p.floor(r * 3.5), i, radiusi; radius = radius < 1 ? 1 : radius < 248 ? radius : 248; if (p.shared.blurRadius !== radius) { p.shared.blurRadius = radius; p.shared.blurKernelSize = 1 + (p.shared.blurRadius << 1); p.shared.blurKernel = new Float32Array(p.shared.blurKernelSize); var sharedBlurKernal = p.shared.blurKernel; var sharedBlurKernelSize = p.shared.blurKernelSize; var sharedBlurRadius = p.shared.blurRadius; for (i = 0; i < sharedBlurKernelSize; i++) sharedBlurKernal[i] = 0; var radiusiSquared = (radius - 1) * (radius - 1); for (i = 1; i < radius; i++) sharedBlurKernal[radius + i] = sharedBlurKernal[radiusi] = radiusiSquared; sharedBlurKernal[radius] = radius * radius } }; var blurARGB = function(r, aImg) { var sum, cr, cg, cb, ca, c, m; var read, ri, ym, ymi, bk0; var wh = aImg.pixels.getLength(); var r2 = new Float32Array(wh); var g2 = new Float32Array(wh); var b2 = new Float32Array(wh); var a2 = new Float32Array(wh); var yi = 0; var x, y, i, offset; buildBlurKernel(r); var aImgHeight = aImg.height; var aImgWidth = aImg.width; var sharedBlurKernelSize = p.shared.blurKernelSize; var sharedBlurRadius = p.shared.blurRadius; var sharedBlurKernal = p.shared.blurKernel; var pix = aImg.imageData.data; for (y = 0; y < aImgHeight; y++) { for (x = 0; x < aImgWidth; x++) { cb = cg = cr = ca = sum = 0; read = x - sharedBlurRadius; if (read < 0) { bk0 = -read; read = 0 } else { if (read >= aImgWidth) break; bk0 = 0 } for (i = bk0; i < sharedBlurKernelSize; i++) { if (read >= aImgWidth) break; offset = (read + yi) * 4; m = sharedBlurKernal[i]; ca += m * pix[offset + 3]; cr += m * pix[offset]; cg += m * pix[offset + 1]; cb += m * pix[offset + 2]; sum += m; read++ } ri = yi + x; a2[ri] = ca / sum; r2[ri] = cr / sum; g2[ri] = cg / sum; b2[ri] = cb / sum } yi += aImgWidth } yi = 0; ym = -sharedBlurRadius; ymi = ym * aImgWidth; for (y = 0; y < aImgHeight; y++) { for (x = 0; x < aImgWidth; x++) { cb = cg = cr = ca = sum = 0; if (ym < 0) { bk0 = ri = -ym; read = x } else { if (ym >= aImgHeight) break; bk0 = 0; ri = ym; read = x + ymi } for (i = bk0; i < sharedBlurKernelSize; i++) { if (ri >= aImgHeight) break; m = sharedBlurKernal[i]; ca += m * a2[read]; cr += m * r2[read]; cg += m * g2[read]; cb += m * b2[read]; sum += m; ri++; read += aImgWidth } offset = (x + yi) * 4; pix[offset] = cr / sum; pix[offset + 1] = cg / sum; pix[offset + 2] = cb / sum; pix[offset + 3] = ca / sum } yi += aImgWidth; ymi += aImgWidth; ym++ } }; var dilate = function(isInverted, aImg) { var currIdx = 0; var maxIdx = aImg.pixels.getLength(); var out = new Int32Array(maxIdx); var currRowIdx, maxRowIdx, colOrig, colOut, currLum; var idxRight, idxLeft, idxUp, idxDown, colRight, colLeft, colUp, colDown, lumRight, lumLeft, lumUp, lumDown; if (!isInverted) while (currIdx < maxIdx) { currRowIdx = currIdx; maxRowIdx = currIdx + aImg.width; while (currIdx < maxRowIdx) { colOrig = colOut = aImg.pixels.getPixel(currIdx); idxLeft = currIdx - 1; idxRight = currIdx + 1; idxUp = currIdx - aImg.width; idxDown = currIdx + aImg.width; if (idxLeft < currRowIdx) idxLeft = currIdx; if (idxRight >= maxRowIdx) idxRight = currIdx; if (idxUp < 0) idxUp = 0; if (idxDown >= maxIdx) idxDown = currIdx; colUp = aImg.pixels.getPixel(idxUp); colLeft = aImg.pixels.getPixel(idxLeft); colDown = aImg.pixels.getPixel(idxDown); colRight = aImg.pixels.getPixel(idxRight); currLum = 77 * (colOrig >> 16 & 255) + 151 * (colOrig >> 8 & 255) + 28 * (colOrig & 255); lumLeft = 77 * (colLeft >> 16 & 255) + 151 * (colLeft >> 8 & 255) + 28 * (colLeft & 255); lumRight = 77 * (colRight >> 16 & 255) + 151 * (colRight >> 8 & 255) + 28 * (colRight & 255); lumUp = 77 * (colUp >> 16 & 255) + 151 * (colUp >> 8 & 255) + 28 * (colUp & 255); lumDown = 77 * (colDown >> 16 & 255) + 151 * (colDown >> 8 & 255) + 28 * (colDown & 255); if (lumLeft > currLum) { colOut = colLeft; currLum = lumLeft } if (lumRight > currLum) { colOut = colRight; currLum = lumRight } if (lumUp > currLum) { colOut = colUp; currLum = lumUp } if (lumDown > currLum) { colOut = colDown; currLum = lumDown } out[currIdx++] = colOut } } else while (currIdx < maxIdx) { currRowIdx = currIdx; maxRowIdx = currIdx + aImg.width; while (currIdx < maxRowIdx) { colOrig = colOut = aImg.pixels.getPixel(currIdx); idxLeft = currIdx - 1; idxRight = currIdx + 1; idxUp = currIdx - aImg.width; idxDown = currIdx + aImg.width; if (idxLeft < currRowIdx) idxLeft = currIdx; if (idxRight >= maxRowIdx) idxRight = currIdx; if (idxUp < 0) idxUp = 0; if (idxDown >= maxIdx) idxDown = currIdx; colUp = aImg.pixels.getPixel(idxUp); colLeft = aImg.pixels.getPixel(idxLeft); colDown = aImg.pixels.getPixel(idxDown); colRight = aImg.pixels.getPixel(idxRight); currLum = 77 * (colOrig >> 16 & 255) + 151 * (colOrig >> 8 & 255) + 28 * (colOrig & 255); lumLeft = 77 * (colLeft >> 16 & 255) + 151 * (colLeft >> 8 & 255) + 28 * (colLeft & 255); lumRight = 77 * (colRight >> 16 & 255) + 151 * (colRight >> 8 & 255) + 28 * (colRight & 255); lumUp = 77 * (colUp >> 16 & 255) + 151 * (colUp >> 8 & 255) + 28 * (colUp & 255); lumDown = 77 * (colDown >> 16 & 255) + 151 * (colDown >> 8 & 255) + 28 * (colDown & 255); if (lumLeft < currLum) { colOut = colLeft; currLum = lumLeft } if (lumRight < currLum) { colOut = colRight; currLum = lumRight } if (lumUp < currLum) { colOut = colUp; currLum = lumUp } if (lumDown < currLum) { colOut = colDown; currLum = lumDown } out[currIdx++] = colOut } } aImg.pixels.set(out) }; p.filter = function(kind, param, aImg) { var img, col, lum, i; if (arguments.length === 3) { aImg.loadPixels(); img = aImg } else { p.loadPixels(); img = p } if (param === undef) param = null; if (img.isRemote) throw "Image is loaded remotely. Cannot filter image."; var imglen = img.pixels.getLength(); switch (kind) { case 11: var radius = param || 1; blurARGB(radius, img); break; case 12: if (img.format === 4) { for (i = 0; i < imglen; i++) { col = 255 - img.pixels.getPixel(i); img.pixels.setPixel(i, 4278190080 | col << 16 | col << 8 | col) } img.format = 1 } else for (i = 0; i < imglen; i++) { col = img.pixels.getPixel(i); lum = 77 * (col >> 16 & 255) + 151 * (col >> 8 & 255) + 28 * (col & 255) >> 8; img.pixels.setPixel(i, col & 4278190080 | lum << 16 | lum << 8 | lum) } break; case 13: for (i = 0; i < imglen; i++) img.pixels.setPixel(i, img.pixels.getPixel(i) ^ 16777215); break; case 15: if (param === null) throw "Use filter(POSTERIZE, int levels) instead of filter(POSTERIZE)"; var levels = p.floor(param); if (levels < 2 || levels > 255) throw "Levels must be between 2 and 255 for filter(POSTERIZE, levels)"; var levels1 = levels - 1; for (i = 0; i < imglen; i++) { var rlevel = img.pixels.getPixel(i) >> 16 & 255; var glevel = img.pixels.getPixel(i) >> 8 & 255; var blevel = img.pixels.getPixel(i) & 255; rlevel = (rlevel * levels >> 8) * 255 / levels1; glevel = (glevel * levels >> 8) * 255 / levels1; blevel = (blevel * levels >> 8) * 255 / levels1; img.pixels.setPixel(i, 4278190080 & img.pixels.getPixel(i) | rlevel << 16 | glevel << 8 | blevel) } break; case 14: for (i = 0; i < imglen; i++) img.pixels.setPixel(i, img.pixels.getPixel(i) | 4278190080); img.format = 1; break; case 16: if (param === null) param = 0.5; if (param < 0 || param > 1) throw "Level must be between 0 and 1 for filter(THRESHOLD, level)"; var thresh = p.floor(param * 255); for (i = 0; i < imglen; i++) { var max = p.max((img.pixels.getPixel(i) & 16711680) >> 16, p.max((img.pixels.getPixel(i) & 65280) >> 8, img.pixels.getPixel(i) & 255)); img.pixels.setPixel(i, img.pixels.getPixel(i) & 4278190080 | (max < thresh ? 0 : 16777215)) } break; case 17: dilate(true, img); break; case 18: dilate(false, img); break } img.updatePixels() }; p.shared = { fracU: 0, ifU: 0, fracV: 0, ifV: 0, u1: 0, u2: 0, v1: 0, v2: 0, sX: 0, sY: 0, iw: 0, iw1: 0, ih1: 0, ul: 0, ll: 0, ur: 0, lr: 0, cUL: 0, cLL: 0, cUR: 0, cLR: 0, srcXOffset: 0, srcYOffset: 0, r: 0, g: 0, b: 0, a: 0, srcBuffer: null, blurRadius: 0, blurKernelSize: 0, blurKernel: null }; p.intersect = function(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2) { var sw = sx2 - sx1 + 1; var sh = sy2 - sy1 + 1; var dw = dx2 - dx1 + 1; var dh = dy2 - dy1 + 1; if (dx1 < sx1) { dw += dx1 - sx1; if (dw > sw) dw = sw } else { var w = sw + sx1 - dx1; if (dw > w) dw = w } if (dy1 < sy1) { dh += dy1 - sy1; if (dh > sh) dh = sh } else { var h = sh + sy1 - dy1; if (dh > h) dh = h } return ! (dw <= 0 || dh <= 0) }; var blendFuncs = {}; blendFuncs[1] = p.modes.blend; blendFuncs[2] = p.modes.add; blendFuncs[4] = p.modes.subtract; blendFuncs[8] = p.modes.lightest; blendFuncs[16] = p.modes.darkest; blendFuncs[0] = p.modes.replace; blendFuncs[32] = p.modes.difference; blendFuncs[64] = p.modes.exclusion; blendFuncs[128] = p.modes.multiply; blendFuncs[256] = p.modes.screen; blendFuncs[512] = p.modes.overlay; blendFuncs[1024] = p.modes.hard_light; blendFuncs[2048] = p.modes.soft_light; blendFuncs[4096] = p.modes.dodge; blendFuncs[8192] = p.modes.burn; p.blit_resize = function(img, srcX1, srcY1, srcX2, srcY2, destPixels, screenW, screenH, destX1, destY1, destX2, destY2, mode) { var x, y; if (srcX1 < 0) srcX1 = 0; if (srcY1 < 0) srcY1 = 0; if (srcX2 >= img.width) srcX2 = img.width - 1; if (srcY2 >= img.height) srcY2 = img.height - 1; var srcW = srcX2 - srcX1; var srcH = srcY2 - srcY1; var destW = destX2 - destX1; var destH = destY2 - destY1; if (destW <= 0 || destH <= 0 || srcW <= 0 || srcH <= 0 || destX1 >= screenW || destY1 >= screenH || srcX1 >= img.width || srcY1 >= img.height) return; var dx = Math.floor(srcW / destW * 32768); var dy = Math.floor(srcH / destH * 32768); var pshared = p.shared; pshared.srcXOffset = Math.floor(destX1 < 0 ? -destX1 * dx : srcX1 * 32768); pshared.srcYOffset = Math.floor(destY1 < 0 ? -destY1 * dy : srcY1 * 32768); if (destX1 < 0) { destW += destX1; destX1 = 0 } if (destY1 < 0) { destH += destY1; destY1 = 0 } destW = Math.min(destW, screenW - destX1); destH = Math.min(destH, screenH - destY1); var destOffset = destY1 * screenW + destX1; var destColor; pshared.srcBuffer = img.imageData.data; pshared.iw = img.width; pshared.iw1 = img.width - 1; pshared.ih1 = img.height - 1; var filterBilinear = p.filter_bilinear, filterNewScanline = p.filter_new_scanline, blendFunc = blendFuncs[mode], blendedColor, idx, cULoffset, cURoffset, cLLoffset, cLRoffset, ALPHA_MASK = 4278190080, RED_MASK = 16711680, GREEN_MASK = 65280, BLUE_MASK = 255, PREC_MAXVAL = 32767, PRECISIONB = 15, PREC_RED_SHIFT = 1, PREC_ALPHA_SHIFT = 9, srcBuffer = pshared.srcBuffer, min = Math.min; for (y = 0; y < destH; y++) { pshared.sX = pshared.srcXOffset; pshared.fracV = pshared.srcYOffset & PREC_MAXVAL; pshared.ifV = PREC_MAXVAL - pshared.fracV; pshared.v1 = (pshared.srcYOffset >> PRECISIONB) * pshared.iw; pshared.v2 = min((pshared.srcYOffset >> PRECISIONB) + 1, pshared.ih1) * pshared.iw; for (x = 0; x < destW; x++) { idx = (destOffset + x) * 4; destColor = destPixels[idx + 3] << 24 & ALPHA_MASK | destPixels[idx] << 16 & RED_MASK | destPixels[idx + 1] << 8 & GREEN_MASK | destPixels[idx + 2] & BLUE_MASK; pshared.fracU = pshared.sX & PREC_MAXVAL; pshared.ifU = PREC_MAXVAL - pshared.fracU; pshared.ul = pshared.ifU * pshared.ifV >> PRECISIONB; pshared.ll = pshared.ifU * pshared.fracV >> PRECISIONB; pshared.ur = pshared.fracU * pshared.ifV >> PRECISIONB; pshared.lr = pshared.fracU * pshared.fracV >> PRECISIONB; pshared.u1 = pshared.sX >> PRECISIONB; pshared.u2 = min(pshared.u1 + 1, pshared.iw1); cULoffset = (pshared.v1 + pshared.u1) * 4; cURoffset = (pshared.v1 + pshared.u2) * 4; cLLoffset = (pshared.v2 + pshared.u1) * 4; cLRoffset = (pshared.v2 + pshared.u2) * 4; pshared.cUL = srcBuffer[cULoffset + 3] << 24 & ALPHA_MASK | srcBuffer[cULoffset] << 16 & RED_MASK | srcBuffer[cULoffset + 1] << 8 & GREEN_MASK | srcBuffer[cULoffset + 2] & BLUE_MASK; pshared.cUR = srcBuffer[cURoffset + 3] << 24 & ALPHA_MASK | srcBuffer[cURoffset] << 16 & RED_MASK | srcBuffer[cURoffset + 1] << 8 & GREEN_MASK | srcBuffer[cURoffset + 2] & BLUE_MASK; pshared.cLL = srcBuffer[cLLoffset + 3] << 24 & ALPHA_MASK | srcBuffer[cLLoffset] << 16 & RED_MASK | srcBuffer[cLLoffset + 1] << 8 & GREEN_MASK | srcBuffer[cLLoffset + 2] & BLUE_MASK; pshared.cLR = srcBuffer[cLRoffset + 3] << 24 & ALPHA_MASK | srcBuffer[cLRoffset] << 16 & RED_MASK | srcBuffer[cLRoffset + 1] << 8 & GREEN_MASK | srcBuffer[cLRoffset + 2] & BLUE_MASK; pshared.r = pshared.ul * ((pshared.cUL & RED_MASK) >> 16) + pshared.ll * ((pshared.cLL & RED_MASK) >> 16) + pshared.ur * ((pshared.cUR & RED_MASK) >> 16) + pshared.lr * ((pshared.cLR & RED_MASK) >> 16) << PREC_RED_SHIFT & RED_MASK; pshared.g = pshared.ul * (pshared.cUL & GREEN_MASK) + pshared.ll * (pshared.cLL & GREEN_MASK) + pshared.ur * (pshared.cUR & GREEN_MASK) + pshared.lr * (pshared.cLR & GREEN_MASK) >>> PRECISIONB & GREEN_MASK; pshared.b = pshared.ul * (pshared.cUL & BLUE_MASK) + pshared.ll * (pshared.cLL & BLUE_MASK) + pshared.ur * (pshared.cUR & BLUE_MASK) + pshared.lr * (pshared.cLR & BLUE_MASK) >>> PRECISIONB; pshared.a = pshared.ul * ((pshared.cUL & ALPHA_MASK) >>> 24) + pshared.ll * ((pshared.cLL & ALPHA_MASK) >>> 24) + pshared.ur * ((pshared.cUR & ALPHA_MASK) >>> 24) + pshared.lr * ((pshared.cLR & ALPHA_MASK) >>> 24) << PREC_ALPHA_SHIFT & ALPHA_MASK; blendedColor = blendFunc(destColor, pshared.a | pshared.r | pshared.g | pshared.b); destPixels[idx] = (blendedColor & RED_MASK) >>> 16; destPixels[idx + 1] = (blendedColor & GREEN_MASK) >>> 8; destPixels[idx + 2] = blendedColor & BLUE_MASK; destPixels[idx + 3] = (blendedColor & ALPHA_MASK) >>> 24; pshared.sX += dx } destOffset += screenW; pshared.srcYOffset += dy } }; p.loadFont = function(name, size) { if (name === undef) throw "font name required in loadFont."; if (name.indexOf(".svg") === -1) { if (size === undef) size = curTextFont.size; return PFont.get(name, size) } var font = p.loadGlyphs(name); return { name: name, css: "12px sans-serif", glyph: true, units_per_em: font.units_per_em, horiz_adv_x: 1 / font.units_per_em * font.horiz_adv_x, ascent: font.ascent, descent: font.descent, width: function(str) { var width = 0; var len = str.length; for (var i = 0; i < len; i++) try { width += parseFloat(p.glyphLook(p.glyphTable[name], str[i]).horiz_adv_x) } catch(e) { Processing.debug(e) } return width / p.glyphTable[name].units_per_em } } }; p.createFont = function(name, size) { return p.loadFont(name, size) }; p.textFont = function(pfont, size) { if (size !== undef) { if (!pfont.glyph) pfont = PFont.get(pfont.name, size); curTextSize = size } curTextFont = pfont; curFontName = curTextFont.name; curTextAscent = curTextFont.ascent; curTextDescent = curTextFont.descent; curTextLeading = curTextFont.leading; var curContext = drawing.$ensureContext(); curContext.font = curTextFont.css }; p.textSize = function(size) { curTextFont = PFont.get(curFontName, size); curTextSize = size; curTextAscent = curTextFont.ascent; curTextDescent = curTextFont.descent; curTextLeading = curTextFont.leading; var curContext = drawing.$ensureContext(); curContext.font = curTextFont.css }; p.textAscent = function() { return curTextAscent }; p.textDescent = function() { return curTextDescent }; p.textLeading = function(leading) { curTextLeading = leading }; p.textAlign = function(xalign, yalign) { horizontalTextAlignment = xalign; verticalTextAlignment = yalign || 0 }; function toP5String(obj) { if (obj instanceof String) return obj; if (typeof obj === "number") { if (obj === (0 | obj)) return obj.toString(); return p.nf(obj, 0, 3) } if (obj === null || obj === undef) return ""; return obj.toString() } Drawing2D.prototype.textWidth = function(str) { var lines = toP5String(str).split(/\r?\n/g), width = 0; var i, linesCount = lines.length; curContext.font = curTextFont.css; for (i = 0; i < linesCount; ++i) width = Math.max(width, curTextFont.measureTextWidth(lines[i])); return width | 0 }; Drawing3D.prototype.textWidth = function(str) { var lines = toP5String(str).split(/\r?\n/g), width = 0; var i, linesCount = lines.length; if (textcanvas === undef) textcanvas = document.createElement("canvas"); var textContext = textcanvas.getContext("2d"); textContext.font = curTextFont.css; for (i = 0; i < linesCount; ++i) width = Math.max(width, textContext.measureText(lines[i]).width); return width | 0 }; p.glyphLook = function(font, chr) { try { switch (chr) { case "1": return font.one; case "2": return font.two; case "3": return font.three; case "4": return font.four; case "5": return font.five; case "6": return font.six; case "7": return font.seven; case "8": return font.eight; case "9": return font.nine; case "0": return font.zero; case " ": return font.space; case "$": return font.dollar; case "!": return font.exclam; case '"': return font.quotedbl; case "#": return font.numbersign; case "%": return font.percent; case "&": return font.ampersand; case "'": return font.quotesingle; case "(": return font.parenleft; case ")": return font.parenright; case "*": return font.asterisk; case "+": return font.plus; case ",": return font.comma; case "-": return font.hyphen; case ".": return font.period; case "/": return font.slash; case "_": return font.underscore; case ":": return font.colon; case ";": return font.semicolon; case "<": return font.less; case "=": return font.equal; case ">": return font.greater; case "?": return font.question; case "@": return font.at; case "[": return font.bracketleft; case "\\": return font.backslash; case "]": return font.bracketright; case "^": return font.asciicircum; case "`": return font.grave; case "{": return font.braceleft; case "|": return font.bar; case "}": return font.braceright; case "~": return font.asciitilde; default: return font[chr] } } catch(e) { Processing.debug(e) } }; Drawing2D.prototype.text$line = function(str, x, y, z, align) { var textWidth = 0, xOffset = 0; if (!curTextFont.glyph) { if (str && "fillText" in curContext) { if (isFillDirty) { curContext.fillStyle = p.color.toString(currentFillColor); isFillDirty = false } if (align === 39 || align === 3) { textWidth = curTextFont.measureTextWidth(str); if (align === 39) xOffset = -textWidth; else xOffset = -textWidth / 2 } curContext.fillText(str, x + xOffset, y) } } else { var font = p.glyphTable[curFontName]; saveContext(); curContext.translate(x, y + curTextSize); if (align === 39 || align === 3) { textWidth = font.width(str); if (align === 39) xOffset = -textWidth; else xOffset = -textWidth / 2 } var upem = font.units_per_em, newScale = 1 / upem * curTextSize; curContext.scale(newScale, newScale); for (var i = 0, len = str.length; i < len; i++) try { p.glyphLook(font, str[i]).draw() } catch(e) { Processing.debug(e) } restoreContext() } }; Drawing3D.prototype.text$line = function(str, x, y, z, align) { if (textcanvas === undef) textcanvas = document.createElement("canvas"); var oldContext = curContext; curContext = textcanvas.getContext("2d"); curContext.font = curTextFont.css; var textWidth = curTextFont.measureTextWidth(str); textcanvas.width = textWidth; textcanvas.height = curTextSize; curContext = textcanvas.getContext("2d"); curContext.font = curTextFont.css; curContext.textBaseline = "top"; Drawing2D.prototype.text$line(str, 0, 0, 0, 37); var aspect = textcanvas.width / textcanvas.height; curContext = oldContext; curContext.bindTexture(curContext.TEXTURE_2D, textTex); curContext.texImage2D(curContext.TEXTURE_2D, 0, curContext.RGBA, curContext.RGBA, curContext.UNSIGNED_BYTE, textcanvas); curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_MAG_FILTER, curContext.LINEAR); curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_MIN_FILTER, curContext.LINEAR); curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_WRAP_T, curContext.CLAMP_TO_EDGE); curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_WRAP_S, curContext.CLAMP_TO_EDGE); var xOffset = 0; if (align === 39) xOffset = -textWidth; else if (align === 3) xOffset = -textWidth / 2; var model = new PMatrix3D; var scalefactor = curTextSize * 0.5; model.translate(x + xOffset - scalefactor / 2, y - scalefactor, z); model.scale(-aspect * scalefactor, -scalefactor, scalefactor); model.translate(-1, -1, -1); model.transpose(); var view = new PMatrix3D; view.scale(1, -1, 1); view.apply(modelView.array()); view.transpose(); curContext.useProgram(programObject2D); vertexAttribPointer("aVertex2d", programObject2D, "aVertex", 3, textBuffer); vertexAttribPointer("aTextureCoord2d", programObject2D, "aTextureCoord", 2, textureBuffer); uniformi("uSampler2d", programObject2D, "uSampler", [0]); uniformi("uIsDrawingText2d", programObject2D, "uIsDrawingText", true); uniformMatrix("uModel2d", programObject2D, "uModel", false, model.array()); uniformMatrix("uView2d", programObject2D, "uView", false, view.array()); uniformf("uColor2d", programObject2D, "uColor", fillStyle); curContext.bindBuffer(curContext.ELEMENT_ARRAY_BUFFER, indexBuffer); curContext.drawElements(curContext.TRIANGLES, 6, curContext.UNSIGNED_SHORT, 0) }; function text$4(str, x, y, z) { var lines, linesCount; if (str.indexOf("\n") < 0) { lines = [str]; linesCount = 1 } else { lines = str.split(/\r?\n/g); linesCount = lines.length } var yOffset = 0; if (verticalTextAlignment === 101) yOffset = curTextAscent + curTextDescent; else if (verticalTextAlignment === 3) yOffset = curTextAscent / 2 - (linesCount - 1) * curTextLeading / 2; else if (verticalTextAlignment === 102) yOffset = -(curTextDescent + (linesCount - 1) * curTextLeading); for (var i = 0; i < linesCount; ++i) { var line = lines[i]; drawing.text$line(line, x, y + yOffset, z, horizontalTextAlignment); yOffset += curTextLeading } } function text$6(str, x, y, width, height, z) { if (str.length === 0 || width === 0 || height === 0) return; if (curTextSize > height) return; var spaceMark = -1; var start = 0; var lineWidth = 0; var drawCommands = []; for (var charPos = 0, len = str.length; charPos < len; charPos++) { var currentChar = str[charPos]; var spaceChar = currentChar === " "; var letterWidth = curTextFont.measureTextWidth(currentChar); if (currentChar !== "\n" && lineWidth + letterWidth <= width) { if (spaceChar) spaceMark = charPos; lineWidth += letterWidth } else { if (spaceMark + 1 === start) if (charPos > 0) spaceMark = charPos; else return; if (currentChar === "\n") { drawCommands.push({ text: str.substring(start, charPos), width: lineWidth }); start = charPos + 1 } else { drawCommands.push({ text: str.substring(start, spaceMark + 1), width: lineWidth }); start = spaceMark + 1 } lineWidth = 0; charPos = start - 1 } } if (start < len) drawCommands.push({ text: str.substring(start), width: lineWidth }); var xOffset = 1, yOffset = curTextAscent; if (horizontalTextAlignment === 3) xOffset = width / 2; else if (horizontalTextAlignment === 39) xOffset = width; var linesCount = drawCommands.length, visibleLines = Math.min(linesCount, Math.floor(height / curTextLeading)); if (verticalTextAlignment === 101) yOffset = curTextAscent + curTextDescent; else if (verticalTextAlignment === 3) yOffset = height / 2 - curTextLeading * (visibleLines / 2 - 1); else if (verticalTextAlignment === 102) yOffset = curTextDescent + curTextLeading; var command, drawCommand, leading; for (command = 0; command < linesCount; command++) { leading = command * curTextLeading; if (yOffset + leading > height - curTextDescent) break; drawCommand = drawCommands[command]; drawing.text$line(drawCommand.text, x + xOffset, y + yOffset + leading, z, horizontalTextAlignment) } } p.text = function() { if (textMode === 5) return; if (arguments.length === 3) text$4(toP5String(arguments[0]), arguments[1], arguments[2], 0); else if (arguments.length === 4) text$4(toP5String(arguments[0]), arguments[1], arguments[2], arguments[3]); else if (arguments.length === 5) text$6(toP5String(arguments[0]), arguments[1], arguments[2], arguments[3], arguments[4], 0); else if (arguments.length === 6) text$6(toP5String(arguments[0]), arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]) }; p.textMode = function(mode) { textMode = mode }; p.loadGlyphs = function(url) { var x, y, cx, cy, nx, ny, d, a, lastCom, lenC, horiz_adv_x, getXY = "[0-9\\-]+", path; var regex = function(needle, hay) { var i = 0, results = [], latest, regexp = new RegExp(needle, "g"); latest = results[i] = regexp.exec(hay); while (latest) { i++; latest = results[i] = regexp.exec(hay) } return results }; var buildPath = function(d) { var c = regex("[A-Za-z][0-9\\- ]+|Z", d); var beforePathDraw = function() { saveContext(); return drawing.$ensureContext() }; var afterPathDraw = function() { executeContextFill(); executeContextStroke(); restoreContext() }; path = "return {draw:function(){var curContext=beforePathDraw();curContext.beginPath();"; x = 0; y = 0; cx = 0; cy = 0; nx = 0; ny = 0; d = 0; a = 0; lastCom = ""; lenC = c.length - 1; for (var j = 0; j < lenC; j++) { var com = c[j][0], xy = regex(getXY, com); switch (com[0]) { case "M": x = parseFloat(xy[0][0]); y = parseFloat(xy[1][0]); path += "curContext.moveTo(" + x + "," + -y + ");"; break; case "L": x = parseFloat(xy[0][0]); y = parseFloat(xy[1][0]); path += "curContext.lineTo(" + x + "," + -y + ");"; break; case "H": x = parseFloat(xy[0][0]); path += "curContext.lineTo(" + x + "," + -y + ");"; break; case "V": y = parseFloat(xy[0][0]); path += "curContext.lineTo(" + x + "," + -y + ");"; break; case "T": nx = parseFloat(xy[0][0]); ny = parseFloat(xy[1][0]); if (lastCom === "Q" || lastCom === "T") { d = Math.sqrt(Math.pow(x - cx, 2) + Math.pow(cy - y, 2)); a = Math.PI + Math.atan2(cx - x, cy - y); cx = x + Math.sin(a) * d; cy = y + Math.cos(a) * d } else { cx = x; cy = y } path += "curContext.quadraticCurveTo(" + cx + "," + -cy + "," + nx + "," + -ny + ");"; x = nx; y = ny; break; case "Q": cx = parseFloat(xy[0][0]); cy = parseFloat(xy[1][0]); nx = parseFloat(xy[2][0]); ny = parseFloat(xy[3][0]); path += "curContext.quadraticCurveTo(" + cx + "," + -cy + "," + nx + "," + -ny + ");"; x = nx; y = ny; break; case "Z": path += "curContext.closePath();"; break } lastCom = com[0] } path += "afterPathDraw();"; path += "curContext.translate(" + horiz_adv_x + ",0);"; path += "}}"; return (new Function("beforePathDraw", "afterPathDraw", path))(beforePathDraw, afterPathDraw) }; var parseSVGFont = function(svg) { var font = svg.getElementsByTagName("font"); p.glyphTable[url].horiz_adv_x = font[0].getAttribute("horiz-adv-x"); var font_face = svg.getElementsByTagName("font-face")[0]; p.glyphTable[url].units_per_em = parseFloat(font_face.getAttribute("units-per-em")); p.glyphTable[url].ascent = parseFloat(font_face.getAttribute("ascent")); p.glyphTable[url].descent = parseFloat(font_face.getAttribute("descent")); var glyph = svg.getElementsByTagName("glyph"), len = glyph.length; for (var i = 0; i < len; i++) { var unicode = glyph[i].getAttribute("unicode"); var name = glyph[i].getAttribute("glyph-name"); horiz_adv_x = glyph[i].getAttribute("horiz-adv-x"); if (horiz_adv_x === null) horiz_adv_x = p.glyphTable[url].horiz_adv_x; d = glyph[i].getAttribute("d"); if (d !== undef) { path = buildPath(d); p.glyphTable[url][name] = { name: name, unicode: unicode, horiz_adv_x: horiz_adv_x, draw: path.draw } } } }; var loadXML = function() { var xmlDoc; try { xmlDoc = document.implementation.createDocument("", "", null) } catch(e_fx_op) { Processing.debug(e_fx_op.message); return } try { xmlDoc.async = false; xmlDoc.load(url); parseSVGFont(xmlDoc.getElementsByTagName("svg")[0]) } catch(e_sf_ch) { Processing.debug(e_sf_ch); try { var xmlhttp = new window.XMLHttpRequest; xmlhttp.open("GET", url, false); xmlhttp.send(null); parseSVGFont(xmlhttp.responseXML.documentElement) } catch(e) { Processing.debug(e_sf_ch) } } }; p.glyphTable[url] = {}; loadXML(url); return p.glyphTable[url] }; p.param = function(name) { var attributeName = "data-processing-" + name; if (curElement.hasAttribute(attributeName)) return curElement.getAttribute(attributeName); for (var i = 0, len = curElement.childNodes.length; i < len; ++i) { var item = curElement.childNodes.item(i); if (item.nodeType !== 1 || item.tagName.toLowerCase() !== "param") continue; if (item.getAttribute("name") === name) return item.getAttribute("value") } if (curSketch.params.hasOwnProperty(name)) return curSketch.params[name]; return null }; function wireDimensionalFunctions(mode) { if (mode === "3D") drawing = new Drawing3D; else if (mode === "2D") drawing = new Drawing2D; else drawing = new DrawingPre; for (var i in DrawingPre.prototype) if (DrawingPre.prototype.hasOwnProperty(i) && i.indexOf("$") < 0) p[i] = drawing[i]; drawing.$init() } function createDrawingPreFunction(name) { return function() { wireDimensionalFunctions("2D"); return drawing[name].apply(this, arguments) } } DrawingPre.prototype.translate = createDrawingPreFunction("translate"); DrawingPre.prototype.transform = createDrawingPreFunction("transform"); DrawingPre.prototype.scale = createDrawingPreFunction("scale"); DrawingPre.prototype.pushMatrix = createDrawingPreFunction("pushMatrix"); DrawingPre.prototype.popMatrix = createDrawingPreFunction("popMatrix"); DrawingPre.prototype.resetMatrix = createDrawingPreFunction("resetMatrix"); DrawingPre.prototype.applyMatrix = createDrawingPreFunction("applyMatrix"); DrawingPre.prototype.rotate = createDrawingPreFunction("rotate"); DrawingPre.prototype.rotateZ = createDrawingPreFunction("rotateZ"); DrawingPre.prototype.shearX = createDrawingPreFunction("shearX"); DrawingPre.prototype.shearY = createDrawingPreFunction("shearY"); DrawingPre.prototype.redraw = createDrawingPreFunction("redraw"); DrawingPre.prototype.toImageData = createDrawingPreFunction("toImageData"); DrawingPre.prototype.ambientLight = createDrawingPreFunction("ambientLight"); DrawingPre.prototype.directionalLight = createDrawingPreFunction("directionalLight"); DrawingPre.prototype.lightFalloff = createDrawingPreFunction("lightFalloff"); DrawingPre.prototype.lightSpecular = createDrawingPreFunction("lightSpecular"); DrawingPre.prototype.pointLight = createDrawingPreFunction("pointLight"); DrawingPre.prototype.noLights = createDrawingPreFunction("noLights"); DrawingPre.prototype.spotLight = createDrawingPreFunction("spotLight"); DrawingPre.prototype.beginCamera = createDrawingPreFunction("beginCamera"); DrawingPre.prototype.endCamera = createDrawingPreFunction("endCamera"); DrawingPre.prototype.frustum = createDrawingPreFunction("frustum"); DrawingPre.prototype.box = createDrawingPreFunction("box"); DrawingPre.prototype.sphere = createDrawingPreFunction("sphere"); DrawingPre.prototype.ambient = createDrawingPreFunction("ambient"); DrawingPre.prototype.emissive = createDrawingPreFunction("emissive"); DrawingPre.prototype.shininess = createDrawingPreFunction("shininess"); DrawingPre.prototype.specular = createDrawingPreFunction("specular"); DrawingPre.prototype.fill = createDrawingPreFunction("fill"); DrawingPre.prototype.stroke = createDrawingPreFunction("stroke"); DrawingPre.prototype.strokeWeight = createDrawingPreFunction("strokeWeight"); DrawingPre.prototype.smooth = createDrawingPreFunction("smooth"); DrawingPre.prototype.noSmooth = createDrawingPreFunction("noSmooth"); DrawingPre.prototype.point = createDrawingPreFunction("point"); DrawingPre.prototype.vertex = createDrawingPreFunction("vertex"); DrawingPre.prototype.endShape = createDrawingPreFunction("endShape"); DrawingPre.prototype.bezierVertex = createDrawingPreFunction("bezierVertex"); DrawingPre.prototype.curveVertex = createDrawingPreFunction("curveVertex"); DrawingPre.prototype.curve = createDrawingPreFunction("curve"); DrawingPre.prototype.line = createDrawingPreFunction("line"); DrawingPre.prototype.bezier = createDrawingPreFunction("bezier"); DrawingPre.prototype.rect = createDrawingPreFunction("rect"); DrawingPre.prototype.ellipse = createDrawingPreFunction("ellipse"); DrawingPre.prototype.background = createDrawingPreFunction("background"); DrawingPre.prototype.image = createDrawingPreFunction("image"); DrawingPre.prototype.textWidth = createDrawingPreFunction("textWidth"); DrawingPre.prototype.text$line = createDrawingPreFunction("text$line"); DrawingPre.prototype.$ensureContext = createDrawingPreFunction("$ensureContext"); DrawingPre.prototype.$newPMatrix = createDrawingPreFunction("$newPMatrix"); DrawingPre.prototype.size = function(aWidth, aHeight, aMode) { wireDimensionalFunctions(aMode === 2 ? "3D" : "2D"); p.size(aWidth, aHeight, aMode) }; DrawingPre.prototype.$init = nop; Drawing2D.prototype.$init = function() { p.size(p.width, p.height); curContext.lineCap = "round"; p.noSmooth(); p.disableContextMenu() }; Drawing3D.prototype.$init = function() { p.use3DContext = true; p.disableContextMenu() }; DrawingShared.prototype.$ensureContext = function() { return curContext }; function calculateOffset(curElement, event) { var element = curElement, offsetX = 0, offsetY = 0; p.pmouseX = p.mouseX; p.pmouseY = p.mouseY; if (element.offsetParent) { do { offsetX += element.offsetLeft; offsetY += element.offsetTop } while ( !! (element = element.offsetParent)) } element = curElement; do { offsetX -= element.scrollLeft || 0; offsetY -= element.scrollTop || 0 } while ( !! (element = element.parentNode)); offsetX += stylePaddingLeft; offsetY += stylePaddingTop; offsetX += styleBorderLeft; offsetY += styleBorderTop; offsetX += window.pageXOffset; offsetY += window.pageYOffset; return { "X": offsetX, "Y": offsetY } } function updateMousePosition(curElement, event) { var offset = calculateOffset(curElement, event); p.mouseX = event.pageX - offset.X; p.mouseY = event.pageY - offset.Y } function addTouchEventOffset(t) { var offset = calculateOffset(t.changedTouches[0].target, t.changedTouches[0]), i; for (i = 0; i < t.touches.length; i++) { var touch = t.touches[i]; touch.offsetX = touch.pageX - offset.X; touch.offsetY = touch.pageY - offset.Y } for (i = 0; i < t.targetTouches.length; i++) { var targetTouch = t.targetTouches[i]; targetTouch.offsetX = targetTouch.pageX - offset.X; targetTouch.offsetY = targetTouch.pageY - offset.Y } for (i = 0; i < t.changedTouches.length; i++) { var changedTouch = t.changedTouches[i]; changedTouch.offsetX = changedTouch.pageX - offset.X; changedTouch.offsetY = changedTouch.pageY - offset.Y } return t } attachEventHandler(curElement, "touchstart", function(t) { curElement.setAttribute("style", "-webkit-user-select: none"); curElement.setAttribute("onclick", "void(0)"); curElement.setAttribute("style", "-webkit-tap-highlight-color:rgba(0,0,0,0)"); for (var i = 0, ehl = eventHandlers.length; i < ehl; i++) { var type = eventHandlers[i].type; if (type === "mouseout" || type === "mousemove" || type === "mousedown" || type === "mouseup" || type === "DOMMouseScroll" || type === "mousewheel" || type === "touchstart") detachEventHandler(eventHandlers[i]) } if (p.touchStart !== undef || p.touchMove !== undef || p.touchEnd !== undef || p.touchCancel !== undef) { attachEventHandler(curElement, "touchstart", function(t) { if (p.touchStart !== undef) { t = addTouchEventOffset(t); p.touchStart(t) } }); attachEventHandler(curElement, "touchmove", function(t) { if (p.touchMove !== undef) { t.preventDefault(); t = addTouchEventOffset(t); p.touchMove(t) } }); attachEventHandler(curElement, "touchend", function(t) { if (p.touchEnd !== undef) { t = addTouchEventOffset(t); p.touchEnd(t) } }); attachEventHandler(curElement, "touchcancel", function(t) { if (p.touchCancel !== undef) { t = addTouchEventOffset(t); p.touchCancel(t) } }) } else { attachEventHandler(curElement, "touchstart", function(e) { updateMousePosition(curElement, e.touches[0]); p.__mousePressed = true; p.mouseDragging = false; p.mouseButton = 37; if (typeof p.mousePressed === "function") p.mousePressed() }); attachEventHandler(curElement, "touchmove", function(e) { e.preventDefault(); updateMousePosition(curElement, e.touches[0]); if (typeof p.mouseMoved === "function" && !p.__mousePressed) p.mouseMoved(); if (typeof p.mouseDragged === "function" && p.__mousePressed) { p.mouseDragged(); p.mouseDragging = true } }); attachEventHandler(curElement, "touchend", function(e) { p.__mousePressed = false; if (typeof p.mouseClicked === "function" && !p.mouseDragging) p.mouseClicked(); if (typeof p.mouseReleased === "function") p.mouseReleased() }) } curElement.dispatchEvent(t) }); (function() { var enabled = true, contextMenu = function(e) { e.preventDefault(); e.stopPropagation() }; p.disableContextMenu = function() { if (!enabled) return; attachEventHandler(curElement, "contextmenu", contextMenu); enabled = false }; p.enableContextMenu = function() { if (enabled) return; detachEventHandler({ elem: curElement, type: "contextmenu", fn: contextMenu }); enabled = true } })(); attachEventHandler(curElement, "mousemove", function(e) { updateMousePosition(curElement, e); if (typeof p.mouseMoved === "function" && !p.__mousePressed) p.mouseMoved(); if (typeof p.mouseDragged === "function" && p.__mousePressed) { p.mouseDragged(); p.mouseDragging = true } }); attachEventHandler(curElement, "mouseout", function(e) { if (typeof p.mouseOut === "function") p.mouseOut() }); attachEventHandler(curElement, "mouseover", function(e) { updateMousePosition(curElement, e); if (typeof p.mouseOver === "function") p.mouseOver() }); curElement.onmousedown = function() { curElement.focus(); return false }; attachEventHandler(curElement, "mousedown", function(e) { p.__mousePressed = true; p.mouseDragging = false; switch (e.which) { case 1: p.mouseButton = 37; break; case 2: p.mouseButton = 3; break; case 3: p.mouseButton = 39; break } if (typeof p.mousePressed === "function") p.mousePressed() }); attachEventHandler(curElement, "mouseup", function(e) { p.__mousePressed = false; if (typeof p.mouseClicked === "function" && !p.mouseDragging) p.mouseClicked(); if (typeof p.mouseReleased === "function") p.mouseReleased() }); var mouseWheelHandler = function(e) { var delta = 0; if (e.wheelDelta) { delta = e.wheelDelta / 120; if (window.opera) delta = -delta } else if (e.detail) delta = -e.detail / 3; p.mouseScroll = delta; if (delta && typeof p.mouseScrolled === "function") p.mouseScrolled() }; attachEventHandler(document, "DOMMouseScroll", mouseWheelHandler); attachEventHandler(document, "mousewheel", mouseWheelHandler); if (!curElement.getAttribute("tabindex")) curElement.setAttribute("tabindex", 0); function getKeyCode(e) { var code = e.which || e.keyCode; switch (code) { case 13: return 10; case 91: case 93: case 224: return 157; case 57392: return 17; case 46: return 127; case 45: return 155 } return code } function getKeyChar(e) { var c = e.which || e.keyCode; var anyShiftPressed = e.shiftKey || e.ctrlKey || e.altKey || e.metaKey; switch (c) { case 13: c = anyShiftPressed ? 13 : 10; break; case 8: c = anyShiftPressed ? 127 : 8; break } return new Char(c) } function suppressKeyEvent(e) { if (typeof e.preventDefault === "function") e.preventDefault(); else if (typeof e.stopPropagation === "function") e.stopPropagation(); return false } function updateKeyPressed() { var ch; for (ch in pressedKeysMap) if (pressedKeysMap.hasOwnProperty(ch)) { p.__keyPressed = true; return } p.__keyPressed = false } function resetKeyPressed() { p.__keyPressed = false; pressedKeysMap = []; lastPressedKeyCode = null } function simulateKeyTyped(code, c) { pressedKeysMap[code] = c; lastPressedKeyCode = null; p.key = c; p.keyCode = code; p.keyPressed(); p.keyCode = 0; p.keyTyped(); updateKeyPressed() } function handleKeydown(e) { var code = getKeyCode(e); if (code === 127) { simulateKeyTyped(code, new Char(127)); return } if (codedKeys.indexOf(code) < 0) { lastPressedKeyCode = code; return } var c = new Char(65535); p.key = c; p.keyCode = code; pressedKeysMap[code] = c; p.keyPressed(); lastPressedKeyCode = null; updateKeyPressed(); return suppressKeyEvent(e) } function handleKeypress(e) { if (lastPressedKeyCode === null) return; var code = lastPressedKeyCode, c = getKeyChar(e); simulateKeyTyped(code, c); return suppressKeyEvent(e) } function handleKeyup(e) { var code = getKeyCode(e), c = pressedKeysMap[code]; if (c === undef) return; p.key = c; p.keyCode = code; p.keyReleased(); delete pressedKeysMap[code]; updateKeyPressed() } if (!pgraphicsMode) { if (aCode instanceof Processing.Sketch) curSketch = aCode; else if (typeof aCode === "function") curSketch = new Processing.Sketch(aCode); else if (!aCode) curSketch = new Processing.Sketch(function() {}); else curSketch = Processing.compile(aCode); p.externals.sketch = curSketch; wireDimensionalFunctions(); curElement.onfocus = function() { p.focused = true }; curElement.onblur = function() { p.focused = false; if (!curSketch.options.globalKeyEvents) resetKeyPressed() }; if (curSketch.options.pauseOnBlur) { attachEventHandler(window, "focus", function() { if (doLoop) p.loop() }); attachEventHandler(window, "blur", function() { if (doLoop && loopStarted) { p.noLoop(); doLoop = true } resetKeyPressed() }) } var keyTrigger = curSketch.options.globalKeyEvents ? window : curElement; attachEventHandler(keyTrigger, "keydown", handleKeydown); attachEventHandler(keyTrigger, "keypress", handleKeypress); attachEventHandler(keyTrigger, "keyup", handleKeyup); for (var i in Processing.lib) if (Processing.lib.hasOwnProperty(i)) if (Processing.lib[i].hasOwnProperty("attach")) Processing.lib[i].attach(p); else if (Processing.lib[i] instanceof Function) Processing.lib[i].call(this); var retryInterval = 100; var executeSketch = function(processing) { if (! (curSketch.imageCache.pending || PFont.preloading.pending(retryInterval))) { if (window.opera) { var link, element, operaCache = curSketch.imageCache.operaCache; for (link in operaCache) if (operaCache.hasOwnProperty(link)) { element = operaCache[link]; if (element !== null) document.body.removeChild(element); delete operaCache[link] } } curSketch.attach(processing, defaultScope); curSketch.onLoad(processing); if (processing.setup) { processing.setup(); processing.resetMatrix(); curSketch.onSetup() } resetContext(); if (processing.draw) if (!doLoop) processing.redraw(); else processing.loop() } else window.setTimeout(function() { executeSketch(processing) }, retryInterval) }; addInstance(this); executeSketch(p) } else { curSketch = new Processing.Sketch; wireDimensionalFunctions(); p.size = function(w, h, render) { if (render && render === 2) wireDimensionalFunctions("3D"); else wireDimensionalFunctions("2D"); p.size(w, h, render) } } }; Processing.debug = debug; Processing.prototype = defaultScope; function getGlobalMembers() { var names = ["abs", "acos", "alpha", "ambient", "ambientLight", "append", "applyMatrix", "arc", "arrayCopy", "asin", "atan", "atan2", "background", "beginCamera", "beginDraw", "beginShape", "bezier", "bezierDetail", "bezierPoint", "bezierTangent", "bezierVertex", "binary", "blend", "blendColor", "blit_resize", "blue", "box", "breakShape", "brightness", "camera", "ceil", "Character", "color", "colorMode", "concat", "constrain", "copy", "cos", "createFont", "createGraphics", "createImage", "cursor", "curve", "curveDetail", "curvePoint", "curveTangent", "curveTightness", "curveVertex", "day", "degrees", "directionalLight", "disableContextMenu", "dist", "draw", "ellipse", "ellipseMode", "emissive", "enableContextMenu", "endCamera", "endDraw", "endShape", "exit", "exp", "expand", "externals", "fill", "filter", "floor", "focused", "frameCount", "frameRate", "frustum", "get", "glyphLook", "glyphTable", "green", "height", "hex", "hint", "hour", "hue", "image", "imageMode", "intersect", "join", "key", "keyCode", "keyPressed", "keyReleased", "keyTyped", "lerp", "lerpColor", "lightFalloff", "lights", "lightSpecular", "line", "link", "loadBytes", "loadFont", "loadGlyphs", "loadImage", "loadPixels", "loadShape", "loadXML", "loadStrings", "log", "loop", "mag", "map", "match", "matchAll", "max", "millis", "min", "minute", "mix", "modelX", "modelY", "modelZ", "modes", "month", "mouseButton", "mouseClicked", "mouseDragged", "mouseMoved", "mouseOut", "mouseOver", "mousePressed", "mouseReleased", "mouseScroll", "mouseScrolled", "mouseX", "mouseY", "name", "nf", "nfc", "nfp", "nfs", "noCursor", "noFill", "noise", "noiseDetail", "noiseSeed", "noLights", "noLoop", "norm", "normal", "noSmooth", "noStroke", "noTint", "ortho", "param", "parseBoolean", "parseByte", "parseChar", "parseFloat", "parseInt", "peg", "perspective", "PImage", "pixels", "PMatrix2D", "PMatrix3D", "PMatrixStack", "pmouseX", "pmouseY", "point", "pointLight", "popMatrix", "popStyle", "pow", "print", "printCamera", "println", "printMatrix", "printProjection", "PShape", "PShapeSVG", "pushMatrix", "pushStyle", "quad", "radians", "random", "Random", "randomSeed", "rect", "rectMode", "red", "redraw", "requestImage", "resetMatrix", "reverse", "rotate", "rotateX", "rotateY", "rotateZ", "round", "saturation", "save", "saveFrame", "saveStrings", "scale", "screenX", "screenY", "screenZ", "second", "set", "setup", "shape", "shapeMode", "shared", "shearX", "shearY", "shininess", "shorten", "sin", "size", "smooth", "sort", "specular", "sphere", "sphereDetail", "splice", "split", "splitTokens", "spotLight", "sq", "sqrt", "status", "str", "stroke", "strokeCap", "strokeJoin", "strokeWeight", "subset", "tan", "text", "textAlign", "textAscent", "textDescent", "textFont", "textLeading", "textMode", "textSize", "texture", "textureMode", "textWidth", "tint", "toImageData", "touchCancel", "touchEnd", "touchMove", "touchStart", "translate", "transform", "triangle", "trim", "unbinary", "unhex", "updatePixels", "use3DContext", "vertex", "width", "XMLElement", "XML", "year", "__contains", "__equals", "__equalsIgnoreCase", "__frameRate", "__hashCode", "__int_cast", "__instanceof", "__keyPressed", "__mousePressed", "__printStackTrace", "__replace", "__replaceAll", "__replaceFirst", "__toCharArray", "__split", "__codePointAt", "__startsWith", "__endsWith", "__matches"]; var members = {}; var i, l; for (i = 0, l = names.length; i < l; ++i) members[names[i]] = null; for (var lib in Processing.lib) if (Processing.lib.hasOwnProperty(lib)) if (Processing.lib[lib].exports) { var exportedNames = Processing.lib[lib].exports; for (i = 0, l = exportedNames.length; i < l; ++i) members[exportedNames[i]] = null } return members } function parseProcessing(code) { var globalMembers = getGlobalMembers(); function splitToAtoms(code) { var atoms = []; var items = code.split(/([\{\[\(\)\]\}])/); var result = items[0]; var stack = []; for (var i = 1; i < items.length; i += 2) { var item = items[i]; if (item === "[" || item === "{" || item === "(") { stack.push(result); result = item } else if (item === "]" || item === "}" || item === ")") { var kind = item === "}" ? "A" : item === ")" ? "B" : "C"; var index = atoms.length; atoms.push(result + item); result = stack.pop() + '"' + kind + (index + 1) + '"' } result += items[i + 1] } atoms.unshift(result); return atoms } function injectStrings(code, strings) { return code.replace(/'(\d+)'/g, function(all, index) { var val = strings[index]; if (val.charAt(0) === "/") return val; return /^'((?:[^'\\\n])|(?:\\.[0-9A-Fa-f]*))'$/.test(val) ? "(new $p.Character(" + val + "))" : val }) } function trimSpaces(string) { var m1 = /^\s*/.exec(string), result; if (m1[0].length === string.length) result = { left: m1[0], middle: "", right: "" }; else { var m2 = /\s*$/.exec(string); result = { left: m1[0], middle: string.substring(m1[0].length, m2.index), right: m2[0] } } result.untrim = function(t) { return this.left + t + this.right }; return result } function trim(string) { return string.replace(/^\s+/, "").replace(/\s+$/, "") } function appendToLookupTable(table, array) { for (var i = 0, l = array.length; i < l; ++i) table[array[i]] = null; return table } function isLookupTableEmpty(table) { for (var i in table) if (table.hasOwnProperty(i)) return false; return true } function getAtomIndex(templ) { return templ.substring(2, templ.length - 1) } var codeWoExtraCr = code.replace(/\r\n?|\n\r/g, "\n"); var strings = []; var codeWoStrings = codeWoExtraCr.replace(/("(?:[^"\\\n]|\\.)*")|('(?:[^'\\\n]|\\.)*')|(([\[\(=|&!\^:?]\s*)(\/(?![*\/])(?:[^\/\\\n]|\\.)*\/[gim]*)\b)|(\/\/[^\n]*\n)|(\/\*(?:(?!\*\/)(?:.|\n))*\*\/)/g, function(all, quoted, aposed, regexCtx, prefix, regex, singleComment, comment) { var index; if (quoted || aposed) { index = strings.length; strings.push(all); return "'" + index + "'" } if (regexCtx) { index = strings.length; strings.push(regex); return prefix + "'" + index + "'" } return comment !== "" ? " " : "\n" }); codeWoStrings = codeWoStrings.replace(/__x([0-9A-F]{4})/g, function(all, hexCode) { return "__x005F_x" + hexCode }); codeWoStrings = codeWoStrings.replace(/\$/g, "__x0024"); var genericsWereRemoved; var codeWoGenerics = codeWoStrings; var replaceFunc = function(all, before, types, after) { if ( !! before || !!after) return all; genericsWereRemoved = true; return "" }; do { genericsWereRemoved = false; codeWoGenerics = codeWoGenerics.replace(/([<]?)<\s*((?:\?|[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)(?:\[\])*(?:\s+(?:extends|super)\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)?(?:\s*,\s*(?:\?|[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)(?:\[\])*(?:\s+(?:extends|super)\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)?)*)\s*>([=]?)/g, replaceFunc) } while (genericsWereRemoved); var atoms = splitToAtoms(codeWoGenerics); var replaceContext; var declaredClasses = {}, currentClassId, classIdSeed = 0; function addAtom(text, type) { var lastIndex = atoms.length; atoms.push(text); return '"' + type + lastIndex + '"' } function generateClassId() { return "class" + ++classIdSeed } function appendClass(class_, classId, scopeId) { class_.classId = classId; class_.scopeId = scopeId; declaredClasses[classId] = class_ } var transformClassBody, transformInterfaceBody, transformStatementsBlock, transformStatements, transformMain, transformExpression; var classesRegex = /\b((?:(?:public|private|final|protected|static|abstract)\s+)*)(class|interface)\s+([A-Za-z_$][\w$]*\b)(\s+extends\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*\b)*)?(\s+implements\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*\b)*)?\s*("A\d+")/g; var methodsRegex = /\b((?:(?:public|private|final|protected|static|abstract|synchronized)\s+)*)((?!(?:else|new|return|throw|function|public|private|protected)\b)[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*"C\d+")*)\s*([A-Za-z_$][\w$]*\b)\s*("B\d+")(\s*throws\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)*)?\s*("A\d+"|;)/g; var fieldTest = /^((?:(?:public|private|final|protected|static)\s+)*)((?!(?:else|new|return|throw)\b)[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*"C\d+")*)\s*([A-Za-z_$][\w$]*\b)\s*(?:"C\d+"\s*)*([=,]|$)/; var cstrsRegex = /\b((?:(?:public|private|final|protected|static|abstract)\s+)*)((?!(?:new|return|throw)\b)[A-Za-z_$][\w$]*\b)\s*("B\d+")(\s*throws\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)*)?\s*("A\d+")/g; var attrAndTypeRegex = /^((?:(?:public|private|final|protected|static)\s+)*)((?!(?:new|return|throw)\b)[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*"C\d+")*)\s*/; var functionsRegex = /\bfunction(?:\s+([A-Za-z_$][\w$]*))?\s*("B\d+")\s*("A\d+")/g; function extractClassesAndMethods(code) { var s = code; s = s.replace(classesRegex, function(all) { return addAtom(all, "E") }); s = s.replace(methodsRegex, function(all) { return addAtom(all, "D") }); s = s.replace(functionsRegex, function(all) { return addAtom(all, "H") }); return s } function extractConstructors(code, className) { var result = code.replace(cstrsRegex, function(all, attr, name, params, throws_, body) { if (name !== className) return all; return addAtom(all, "G") }); return result } function AstParam(name) { this.name = name } AstParam.prototype.toString = function() { return this.name }; function AstParams(params, methodArgsParam) { this.params = params; this.methodArgsParam = methodArgsParam } AstParams.prototype.getNames = function() { var names = []; for (var i = 0, l = this.params.length; i < l; ++i) names.push(this.params[i].name); return names }; AstParams.prototype.prependMethodArgs = function(body) { if (!this.methodArgsParam) return body; return "{\nvar " + this.methodArgsParam.name + " = Array.prototype.slice.call(arguments, " + this.params.length + ");\n" + body.substring(1) }; AstParams.prototype.toString = function() { if (this.params.length === 0) return "()"; var result = "("; for (var i = 0, l = this.params.length; i < l; ++i) result += this.params[i] + ", "; return result.substring(0, result.length - 2) + ")" }; function transformParams(params) { var paramsWoPars = trim(params.substring(1, params.length - 1)); var result = [], methodArgsParam = null; if (paramsWoPars !== "") { var paramList = paramsWoPars.split(","); for (var i = 0; i < paramList.length; ++i) { var param = /\b([A-Za-z_$][\w$]*\b)(\s*"[ABC][\d]*")*\s*$/.exec(paramList[i]); if (i === paramList.length - 1 && paramList[i].indexOf("...") >= 0) { methodArgsParam = new AstParam(param[1]); break } result.push(new AstParam(param[1])) } } return new AstParams(result, methodArgsParam) } function preExpressionTransform(expr) { var s = expr; s = s.replace(/\bnew\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)(?:\s*"C\d+")+\s*("A\d+")/g, function(all, type, init) { return init }); s = s.replace(/\bnew\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)(?:\s*"B\d+")\s*("A\d+")/g, function(all, type, init) { return addAtom(all, "F") }); s = s.replace(functionsRegex, function(all) { return addAtom(all, "H") }); s = s.replace(/\bnew\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)\s*("C\d+"(?:\s*"C\d+")*)/g, function(all, type, index) { var args = index.replace(/"C(\d+)"/g, function(all, j) { return atoms[j] }).replace(/\[\s*\]/g, "[null]").replace(/\s*\]\s*\[\s*/g, ", "); var arrayInitializer = "{" + args.substring(1, args.length - 1) + "}"; var createArrayArgs = "('" + type + "', " + addAtom(arrayInitializer, "A") + ")"; return "$p.createJavaArray" + addAtom(createArrayArgs, "B") }); s = s.replace(/(\.\s*length)\s*"B\d+"/g, "$1"); s = s.replace(/#([0-9A-Fa-f]{6})\b/g, function(all, digits) { return "0xFF" + digits }); s = s.replace(/"B(\d+)"(\s*(?:[\w$']|"B))/g, function(all, index, next) { var atom = atoms[index]; if (!/^\(\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*\s*(?:"C\d+"\s*)*\)$/.test(atom)) return all; if (/^\(\s*int\s*\)$/.test(atom)) return "(int)" + next; var indexParts = atom.split(/"C(\d+)"/g); if (indexParts.length > 1) if (!/^\[\s*\]$/.test(atoms[indexParts[1]])) return all; return "" + next }); s = s.replace(/\(int\)([^,\]\)\}\?\:\*\+\-\/\^\|\%\&\~<\>\=]+)/g, function(all, arg) { var trimmed = trimSpaces(arg); return trimmed.untrim("__int_cast(" + trimmed.middle + ")") }); s = s.replace(/\bsuper(\s*"B\d+")/g, "$$superCstr$1").replace(/\bsuper(\s*\.)/g, "$$super$1"); s = s.replace(/\b0+((\d*)(?:\.[\d*])?(?:[eE][\-\+]?\d+)?[fF]?)\b/, function(all, numberWo0, intPart) { if (numberWo0 === intPart) return all; return intPart === "" ? "0" + numberWo0 : numberWo0 }); s = s.replace(/\b(\.?\d+\.?)[fF]\b/g, "$1"); s = s.replace(/([^\s])%([^=\s])/g, "$1 % $2"); s = s.replace(/\b(frameRate|keyPressed|mousePressed)\b(?!\s*"B)/g, "__$1"); s = s.replace(/\b(boolean|byte|char|float|int)\s*"B/g, function(all, name) { return "parse" + name.substring(0, 1).toUpperCase() + name.substring(1) + '"B' }); s = s.replace(/\bpixels\b\s*(("C(\d+)")|\.length)?(\s*=(?!=)([^,\]\)\}]+))?/g, function(all, indexOrLength, index, atomIndex, equalsPart, rightSide) { if (index) { var atom = atoms[atomIndex]; if (equalsPart) return "pixels.setPixel" + addAtom("(" + atom.substring(1, atom.length - 1) + "," + rightSide + ")", "B"); return "pixels.getPixel" + addAtom("(" + atom.substring(1, atom.length - 1) + ")", "B") } if (indexOrLength) return "pixels.getLength" + addAtom("()", "B"); if (equalsPart) return "pixels.set" + addAtom("(" + rightSide + ")", "B"); return "pixels.toArray" + addAtom("()", "B") }); var repeatJavaReplacement; function replacePrototypeMethods(all, subject, method, atomIndex) { var atom = atoms[atomIndex]; repeatJavaReplacement = true; var trimmed = trimSpaces(atom.substring(1, atom.length - 1)); return "__" + method + (trimmed.middle === "" ? addAtom("(" + subject.replace(/\.\s*$/, "") + ")", "B") : addAtom("(" + subject.replace(/\.\s*$/, "") + "," + trimmed.middle + ")", "B")) } do { repeatJavaReplacement = false; s = s.replace(/((?:'\d+'|\b[A-Za-z_$][\w$]*\s*(?:"[BC]\d+")*)\s*\.\s*(?:[A-Za-z_$][\w$]*\s*(?:"[BC]\d+"\s*)*\.\s*)*)(replace|replaceAll|replaceFirst|contains|equals|equalsIgnoreCase|hashCode|toCharArray|printStackTrace|split|startsWith|endsWith|codePointAt|matches)\s*"B(\d+)"/g, replacePrototypeMethods) } while (repeatJavaReplacement); function replaceInstanceof(all, subject, type) { repeatJavaReplacement = true; return "__instanceof" + addAtom("(" + subject + ", " + type + ")", "B") } do { repeatJavaReplacement = false; s = s.replace(/((?:'\d+'|\b[A-Za-z_$][\w$]*\s*(?:"[BC]\d+")*)\s*(?:\.\s*[A-Za-z_$][\w$]*\s*(?:"[BC]\d+"\s*)*)*)instanceof\s+([A-Za-z_$][\w$]*\s*(?:\.\s*[A-Za-z_$][\w$]*)*)/g, replaceInstanceof) } while (repeatJavaReplacement); s = s.replace(/\bthis(\s*"B\d+")/g, "$$constr$1"); return s } function AstInlineClass(baseInterfaceName, body) { this.baseInterfaceName = baseInterfaceName; this.body = body; body.owner = this } AstInlineClass.prototype.toString = function() { return "new (" + this.body + ")" }; function transformInlineClass(class_) { var m = (new RegExp(/\bnew\s*([A-Za-z_$][\w$]*\s*(?:\.\s*[A-Za-z_$][\w$]*)*)\s*"B\d+"\s*"A(\d+)"/)).exec(class_); var oldClassId = currentClassId, newClassId = generateClassId(); currentClassId = newClassId; var uniqueClassName = m[1] + "$" + newClassId; var inlineClass = new AstInlineClass(uniqueClassName, transformClassBody(atoms[m[2]], uniqueClassName, "", "implements " + m[1])); appendClass(inlineClass, newClassId, oldClassId); currentClassId = oldClassId; return inlineClass } function AstFunction(name, params, body) { this.name = name; this.params = params; this.body = body } AstFunction.prototype.toString = function() { var oldContext = replaceContext; var names = appendToLookupTable({ "this": null }, this.params.getNames()); replaceContext = function(subject) { return names.hasOwnProperty(subject.name) ? subject.name : oldContext(subject) }; var result = "function"; if (this.name) result += " " + this.name; var body = this.params.prependMethodArgs(this.body.toString()); result += this.params + " " + body; replaceContext = oldContext; return result }; function transformFunction(class_) { var m = (new RegExp(/\b([A-Za-z_$][\w$]*)\s*"B(\d+)"\s*"A(\d+)"/)).exec(class_); return new AstFunction(m[1] !== "function" ? m[1] : null, transformParams(atoms[m[2]]), transformStatementsBlock(atoms[m[3]])) } function AstInlineObject(members) { this.members = members } AstInlineObject.prototype.toString = function() { var oldContext = replaceContext; replaceContext = function(subject) { return subject.name === "this" ? "this" : oldContext(subject) }; var result = ""; for (var i = 0, l = this.members.length; i < l; ++i) { if (this.members[i].label) result += this.members[i].label + ": "; result += this.members[i].value.toString() + ", " } replaceContext = oldContext; return result.substring(0, result.length - 2) }; function transformInlineObject(obj) { var members = obj.split(","); for (var i = 0; i < members.length; ++i) { var label = members[i].indexOf(":"); if (label < 0) members[i] = { value: transformExpression(members[i]) }; else members[i] = { label: trim(members[i].substring(0, label)), value: transformExpression(trim(members[i].substring(label + 1))) } } return new AstInlineObject(members) } function expandExpression(expr) { if (expr.charAt(0) === "(" || expr.charAt(0) === "[") return expr.charAt(0) + expandExpression(expr.substring(1, expr.length - 1)) + expr.charAt(expr.length - 1); if (expr.charAt(0) === "{") { if (/^\{\s*(?:[A-Za-z_$][\w$]*|'\d+')\s*:/.test(expr)) return "{" + addAtom(expr.substring(1, expr.length - 1), "I") + "}"; return "[" + expandExpression(expr.substring(1, expr.length - 1)) + "]" } var trimmed = trimSpaces(expr); var result = preExpressionTransform(trimmed.middle); result = result.replace(/"[ABC](\d+)"/g, function(all, index) { return expandExpression(atoms[index]) }); return trimmed.untrim(result) } function replaceContextInVars(expr) { return expr.replace(/(\.\s*)?((?:\b[A-Za-z_]|\$)[\w$]*)(\s*\.\s*([A-Za-z_$][\w$]*)(\s*\()?)?/g, function(all, memberAccessSign, identifier, suffix, subMember, callSign) { if (memberAccessSign) return all; var subject = { name: identifier, member: subMember, callSign: !!callSign }; return replaceContext(subject) + (suffix === undef ? "" : suffix) }) } function AstExpression(expr, transforms) { this.expr = expr; this.transforms = transforms } AstExpression.prototype.toString = function() { var transforms = this.transforms; var expr = replaceContextInVars(this.expr); return expr.replace(/"!(\d+)"/g, function(all, index) { return transforms[index].toString() }) }; transformExpression = function(expr) { var transforms = []; var s = expandExpression(expr); s = s.replace(/"H(\d+)"/g, function(all, index) { transforms.push(transformFunction(atoms[index])); return '"!' + (transforms.length - 1) + '"' }); s = s.replace(/"F(\d+)"/g, function(all, index) { transforms.push(transformInlineClass(atoms[index])); return '"!' + (transforms.length - 1) + '"' }); s = s.replace(/"I(\d+)"/g, function(all, index) { transforms.push(transformInlineObject(atoms[index])); return '"!' + (transforms.length - 1) + '"' }); return new AstExpression(s, transforms) }; function AstVarDefinition(name, value, isDefault) { this.name = name; this.value = value; this.isDefault = isDefault } AstVarDefinition.prototype.toString = function() { return this.name + " = " + this.value }; function transformVarDefinition(def, defaultTypeValue) { var eqIndex = def.indexOf("="); var name, value, isDefault; if (eqIndex < 0) { name = def; value = defaultTypeValue; isDefault = true } else { name = def.substring(0, eqIndex); value = transformExpression(def.substring(eqIndex + 1)); isDefault = false } return new AstVarDefinition(trim(name.replace(/(\s*"C\d+")+/g, "")), value, isDefault) } function getDefaultValueForType(type) { if (type === "int" || type === "float") return "0"; if (type === "boolean") return "false"; if (type === "color") return "0x00000000"; return "null" } function AstVar(definitions, varType) { this.definitions = definitions; this.varType = varType } AstVar.prototype.getNames = function() { var names = []; for (var i = 0, l = this.definitions.length; i < l; ++i) names.push(this.definitions[i].name); return names }; AstVar.prototype.toString = function() { return "var " + this.definitions.join(",") }; function AstStatement(expression) { this.expression = expression } AstStatement.prototype.toString = function() { return this.expression.toString() }; function transformStatement(statement) { if (fieldTest.test(statement)) { var attrAndType = attrAndTypeRegex.exec(statement); var definitions = statement.substring(attrAndType[0].length).split(","); var defaultTypeValue = getDefaultValueForType(attrAndType[2]); for (var i = 0; i < definitions.length; ++i) definitions[i] = transformVarDefinition(definitions[i], defaultTypeValue); return new AstVar(definitions, attrAndType[2]) } return new AstStatement(transformExpression(statement)) } function AstForExpression(initStatement, condition, step) { this.initStatement = initStatement; this.condition = condition; this.step = step } AstForExpression.prototype.toString = function() { return "(" + this.initStatement + "; " + this.condition + "; " + this.step + ")" }; function AstForInExpression(initStatement, container) { this.initStatement = initStatement; this.container = container } AstForInExpression.prototype.toString = function() { var init = this.initStatement.toString(); if (init.indexOf("=") >= 0) init = init.substring(0, init.indexOf("=")); return "(" + init + " in " + this.container + ")" }; function AstForEachExpression(initStatement, container) { this.initStatement = initStatement; this.container = container } AstForEachExpression.iteratorId = 0; AstForEachExpression.prototype.toString = function() { var init = this.initStatement.toString(); var iterator = "$it" + AstForEachExpression.iteratorId++; var variableName = init.replace(/^\s*var\s*/, "").split("=")[0]; var initIteratorAndVariable = "var " + iterator + " = new $p.ObjectIterator(" + this.container + "), " + variableName + " = void(0)"; var nextIterationCondition = iterator + ".hasNext() && ((" + variableName + " = " + iterator + ".next()) || true)"; return "(" + initIteratorAndVariable + "; " + nextIterationCondition + ";)" }; function transformForExpression(expr) { var content; if (/\bin\b/.test(expr)) { content = expr.substring(1, expr.length - 1).split(/\bin\b/g); return new AstForInExpression(transformStatement(trim(content[0])), transformExpression(content[1])) } if (expr.indexOf(":") >= 0 && expr.indexOf(";") < 0) { content = expr.substring(1, expr.length - 1).split(":"); return new AstForEachExpression(transformStatement(trim(content[0])), transformExpression(content[1])) } content = expr.substring(1, expr.length - 1).split(";"); return new AstForExpression(transformStatement(trim(content[0])), transformExpression(content[1]), transformExpression(content[2])) } function sortByWeight(array) { array.sort(function(a, b) { return b.weight - a.weight }) } function AstInnerInterface(name, body, isStatic) { this.name = name; this.body = body; this.isStatic = isStatic; body.owner = this } AstInnerInterface.prototype.toString = function() { return "" + this.body }; function AstInnerClass(name, body, isStatic) { this.name = name; this.body = body; this.isStatic = isStatic; body.owner = this } AstInnerClass.prototype.toString = function() { return "" + this.body }; function transformInnerClass(class_) { var m = classesRegex.exec(class_); classesRegex.lastIndex = 0; var isStatic = m[1].indexOf("static") >= 0; var body = atoms[getAtomIndex(m[6])], innerClass; var oldClassId = currentClassId, newClassId = generateClassId(); currentClassId = newClassId; if (m[2] === "interface") innerClass = new AstInnerInterface(m[3], transformInterfaceBody(body, m[3], m[4]), isStatic); else innerClass = new AstInnerClass(m[3], transformClassBody(body, m[3], m[4], m[5]), isStatic); appendClass(innerClass, newClassId, oldClassId); currentClassId = oldClassId; return innerClass } function AstClassMethod(name, params, body, isStatic) { this.name = name; this.params = params; this.body = body; this.isStatic = isStatic } AstClassMethod.prototype.toString = function() { var paramNames = appendToLookupTable({}, this.params.getNames()); var oldContext = replaceContext; replaceContext = function(subject) { return paramNames.hasOwnProperty(subject.name) ? subject.name : oldContext(subject) }; var body = this.params.prependMethodArgs(this.body.toString()); var result = "function " + this.methodId + this.params + " " + body + "\n"; replaceContext = oldContext; return result }; function transformClassMethod(method) { var m = methodsRegex.exec(method); methodsRegex.lastIndex = 0; var isStatic = m[1].indexOf("static") >= 0; var body = m[6] !== ";" ? atoms[getAtomIndex(m[6])] : "{}"; return new AstClassMethod(m[3], transformParams(atoms[getAtomIndex(m[4])]), transformStatementsBlock(body), isStatic) } function AstClassField(definitions, fieldType, isStatic) { this.definitions = definitions; this.fieldType = fieldType; this.isStatic = isStatic } AstClassField.prototype.getNames = function() { var names = []; for (var i = 0, l = this.definitions.length; i < l; ++i) names.push(this.definitions[i].name); return names }; AstClassField.prototype.toString = function() { var thisPrefix = replaceContext({ name: "[this]" }); if (this.isStatic) { var className = this.owner.name; var staticDeclarations = []; for (var i = 0, l = this.definitions.length; i < l; ++i) { var definition = this.definitions[i]; var name = definition.name, staticName = className + "." + name; var declaration = "if(" + staticName + " === void(0)) {\n" + " " + staticName + " = " + definition.value + "; }\n" + "$p.defineProperty(" + thisPrefix + ", " + "'" + name + "', { get: function(){return " + staticName + ";}, " + "set: function(val){" + staticName + " = val;} });\n"; staticDeclarations.push(declaration) } return staticDeclarations.join("") } return thisPrefix + "." + this.definitions.join("; " + thisPrefix + ".") }; function transformClassField(statement) { var attrAndType = attrAndTypeRegex.exec(statement); var isStatic = attrAndType[1].indexOf("static") >= 0; var definitions = statement.substring(attrAndType[0].length).split(/,\s*/g); var defaultTypeValue = getDefaultValueForType(attrAndType[2]); for (var i = 0; i < definitions.length; ++i) definitions[i] = transformVarDefinition(definitions[i], defaultTypeValue); return new AstClassField(definitions, attrAndType[2], isStatic) } function AstConstructor(params, body) { this.params = params; this.body = body } AstConstructor.prototype.toString = function() { var paramNames = appendToLookupTable({}, this.params.getNames()); var oldContext = replaceContext; replaceContext = function(subject) { return paramNames.hasOwnProperty(subject.name) ? subject.name : oldContext(subject) }; var prefix = "function $constr_" + this.params.params.length + this.params.toString(); var body = this.params.prependMethodArgs(this.body.toString()); if (!/\$(superCstr|constr)\b/.test(body)) body = "{\n$superCstr();\n" + body.substring(1); replaceContext = oldContext; return prefix + body + "\n" }; function transformConstructor(cstr) { var m = (new RegExp(/"B(\d+)"\s*"A(\d+)"/)).exec(cstr); var params = transformParams(atoms[m[1]]); return new AstConstructor(params, transformStatementsBlock(atoms[m[2]])) } function AstInterfaceBody(name, interfacesNames, methodsNames, fields, innerClasses, misc) { var i, l; this.name = name; this.interfacesNames = interfacesNames; this.methodsNames = methodsNames; this.fields = fields; this.innerClasses = innerClasses; this.misc = misc; for (i = 0, l = fields.length; i < l; ++i) fields[i].owner = this } AstInterfaceBody.prototype.getMembers = function(classFields, classMethods, classInners) { if (this.owner.base) this.owner.base.body.getMembers(classFields, classMethods, classInners); var i, j, l, m; for (i = 0, l = this.fields.length; i < l; ++i) { var fieldNames = this.fields[i].getNames(); for (j = 0, m = fieldNames.length; j < m; ++j) classFields[fieldNames[j]] = this.fields[i] } for (i = 0, l = this.methodsNames.length; i < l; ++i) { var methodName = this.methodsNames[i]; classMethods[methodName] = true } for (i = 0, l = this.innerClasses.length; i < l; ++i) { var innerClass = this.innerClasses[i]; classInners[innerClass.name] = innerClass } }; AstInterfaceBody.prototype.toString = function() { function getScopeLevel(p) { var i = 0; while (p) { ++i; p = p.scope } return i } var scopeLevel = getScopeLevel(this.owner); var className = this.name; var staticDefinitions = ""; var metadata = ""; var thisClassFields = {}, thisClassMethods = {}, thisClassInners = {}; this.getMembers(thisClassFields, thisClassMethods, thisClassInners); var i, l, j, m; if (this.owner.interfaces) { var resolvedInterfaces = [], resolvedInterface; for (i = 0, l = this.interfacesNames.length; i < l; ++i) { if (!this.owner.interfaces[i]) continue; resolvedInterface = replaceContext({ name: this.interfacesNames[i] }); resolvedInterfaces.push(resolvedInterface); staticDefinitions += "$p.extendInterfaceMembers(" + className + ", " + resolvedInterface + ");\n" } metadata += className + ".$interfaces = [" + resolvedInterfaces.join(", ") + "];\n" } metadata += className + ".$isInterface = true;\n"; metadata += className + ".$methods = ['" + this.methodsNames.join("', '") + "'];\n"; sortByWeight(this.innerClasses); for (i = 0, l = this.innerClasses.length; i < l; ++i) { var innerClass = this.innerClasses[i]; if (innerClass.isStatic) staticDefinitions += className + "." + innerClass.name + " = " + innerClass + ";\n" } for (i = 0, l = this.fields.length; i < l; ++i) { var field = this.fields[i]; if (field.isStatic) staticDefinitions += className + "." + field.definitions.join(";\n" + className + ".") + ";\n" } return "(function() {\n" + "function " + className + "() { throw 'Unable to create the interface'; }\n" + staticDefinitions + metadata + "return " + className + ";\n" + "})()" }; transformInterfaceBody = function(body, name, baseInterfaces) { var declarations = body.substring(1, body.length - 1); declarations = extractClassesAndMethods(declarations); declarations = extractConstructors(declarations, name); var methodsNames = [], classes = []; declarations = declarations.replace(/"([DE])(\d+)"/g, function(all, type, index) { if (type === "D") methodsNames.push(index); else if (type === "E") classes.push(index); return "" }); var fields = declarations.split(/;(?:\s*;)*/g); var baseInterfaceNames; var i, l; if (baseInterfaces !== undef) baseInterfaceNames = baseInterfaces.replace(/^\s*extends\s+(.+?)\s*$/g, "$1").split(/\s*,\s*/g); for (i = 0, l = methodsNames.length; i < l; ++i) { var method = transformClassMethod(atoms[methodsNames[i]]); methodsNames[i] = method.name } for (i = 0, l = fields.length - 1; i < l; ++i) { var field = trimSpaces(fields[i]); fields[i] = transformClassField(field.middle) } var tail = fields.pop(); for (i = 0, l = classes.length; i < l; ++i) classes[i] = transformInnerClass(atoms[classes[i]]); return new AstInterfaceBody(name, baseInterfaceNames, methodsNames, fields, classes, { tail: tail }) }; function AstClassBody(name, baseClassName, interfacesNames, functions, methods, fields, cstrs, innerClasses, misc) { var i, l; this.name = name; this.baseClassName = baseClassName; this.interfacesNames = interfacesNames; this.functions = functions; this.methods = methods; this.fields = fields; this.cstrs = cstrs; this.innerClasses = innerClasses; this.misc = misc; for (i = 0, l = fields.length; i < l; ++i) fields[i].owner = this } AstClassBody.prototype.getMembers = function(classFields, classMethods, classInners) { if (this.owner.base) this.owner.base.body.getMembers(classFields, classMethods, classInners); var i, j, l, m; for (i = 0, l = this.fields.length; i < l; ++i) { var fieldNames = this.fields[i].getNames(); for (j = 0, m = fieldNames.length; j < m; ++j) classFields[fieldNames[j]] = this.fields[i] } for (i = 0, l = this.methods.length; i < l; ++i) { var method = this.methods[i]; classMethods[method.name] = method } for (i = 0, l = this.innerClasses.length; i < l; ++i) { var innerClass = this.innerClasses[i]; classInners[innerClass.name] = innerClass } }; AstClassBody.prototype.toString = function() { function getScopeLevel(p) { var i = 0; while (p) { ++i; p = p.scope } return i } var scopeLevel = getScopeLevel(this.owner); var selfId = "$this_" + scopeLevel; var className = this.name; var result = "var " + selfId + " = this;\n"; var staticDefinitions = ""; var metadata = ""; var thisClassFields = {}, thisClassMethods = {}, thisClassInners = {}; this.getMembers(thisClassFields, thisClassMethods, thisClassInners); var oldContext = replaceContext; replaceContext = function(subject) { var name = subject.name; if (name === "this") return subject.callSign || !subject.member ? selfId + ".$self" : selfId; if (thisClassFields.hasOwnProperty(name)) return thisClassFields[name].isStatic ? className + "." + name : selfId + "." + name; if (thisClassInners.hasOwnProperty(name)) return selfId + "." + name; if (thisClassMethods.hasOwnProperty(name)) return thisClassMethods[name].isStatic ? className + "." + name : selfId + ".$self." + name; return oldContext(subject) }; var resolvedBaseClassName; if (this.baseClassName) { resolvedBaseClassName = oldContext({ name: this.baseClassName }); result += "var $super = { $upcast: " + selfId + " };\n"; result += "function $superCstr(){" + resolvedBaseClassName + ".apply($super,arguments);if(!('$self' in $super)) $p.extendClassChain($super)}\n"; metadata += className + ".$base = " + resolvedBaseClassName + ";\n" } else result += "function $superCstr(){$p.extendClassChain(" + selfId + ")}\n"; if (this.owner.base) staticDefinitions += "$p.extendStaticMembers(" + className + ", " + resolvedBaseClassName + ");\n"; var i, l, j, m; if (this.owner.interfaces) { var resolvedInterfaces = [], resolvedInterface; for (i = 0, l = this.interfacesNames.length; i < l; ++i) { if (!this.owner.interfaces[i]) continue; resolvedInterface = oldContext({ name: this.interfacesNames[i] }); resolvedInterfaces.push(resolvedInterface); staticDefinitions += "$p.extendInterfaceMembers(" + className + ", " + resolvedInterface + ");\n" } metadata += className + ".$interfaces = [" + resolvedInterfaces.join(", ") + "];\n" } if (this.functions.length > 0) result += this.functions.join("\n") + "\n"; sortByWeight(this.innerClasses); for (i = 0, l = this.innerClasses.length; i < l; ++i) { var innerClass = this.innerClasses[i]; if (innerClass.isStatic) { staticDefinitions += className + "." + innerClass.name + " = " + innerClass + ";\n"; result += selfId + "." + innerClass.name + " = " + className + "." + innerClass.name + ";\n" } else result += selfId + "." + innerClass.name + " = " + innerClass + ";\n" } for (i = 0, l = this.fields.length; i < l; ++i) { var field = this.fields[i]; if (field.isStatic) { staticDefinitions += className + "." + field.definitions.join(";\n" + className + ".") + ";\n"; for (j = 0, m = field.definitions.length; j < m; ++j) { var fieldName = field.definitions[j].name, staticName = className + "." + fieldName; result += "$p.defineProperty(" + selfId + ", '" + fieldName + "', {" + "get: function(){return " + staticName + "}, " + "set: function(val){" + staticName + " = val}});\n" } } else result += selfId + "." + field.definitions.join(";\n" + selfId + ".") + ";\n" } var methodOverloads = {}; for (i = 0, l = this.methods.length; i < l; ++i) { var method = this.methods[i]; var overload = methodOverloads[method.name]; var methodId = method.name + "$" + method.params.params.length; var hasMethodArgs = !!method.params.methodArgsParam; if (overload) { ++overload; methodId += "_" + overload } else overload = 1; method.methodId = methodId; methodOverloads[method.name] = overload; if (method.isStatic) { staticDefinitions += method; staticDefinitions += "$p.addMethod(" + className + ", '" + method.name + "', " + methodId + ", " + hasMethodArgs + ");\n"; result += "$p.addMethod(" + selfId + ", '" + method.name + "', " + methodId + ", " + hasMethodArgs + ");\n" } else { result += method; result += "$p.addMethod(" + selfId + ", '" + method.name + "', " + methodId + ", " + hasMethodArgs + ");\n" } } result += trim(this.misc.tail); if (this.cstrs.length > 0) result += this.cstrs.join("\n") + "\n"; result += "function $constr() {\n"; var cstrsIfs = []; for (i = 0, l = this.cstrs.length; i < l; ++i) { var paramsLength = this.cstrs[i].params.params.length; var methodArgsPresent = !!this.cstrs[i].params.methodArgsParam; cstrsIfs.push("if(arguments.length " + (methodArgsPresent ? ">=" : "===") + " " + paramsLength + ") { " + "$constr_" + paramsLength + ".apply(" + selfId + ", arguments); }") } if (cstrsIfs.length > 0) result += cstrsIfs.join(" else ") + " else "; result += "$superCstr();\n}\n"; result += "$constr.apply(null, arguments);\n"; replaceContext = oldContext; return "(function() {\n" + "function " + className + "() {\n" + result + "}\n" + staticDefinitions + metadata + "return " + className + ";\n" + "})()" }; transformClassBody = function(body, name, baseName, interfaces) { var declarations = body.substring(1, body.length - 1); declarations = extractClassesAndMethods(declarations); declarations = extractConstructors(declarations, name); var methods = [], classes = [], cstrs = [], functions = []; declarations = declarations.replace(/"([DEGH])(\d+)"/g, function(all, type, index) { if (type === "D") methods.push(index); else if (type === "E") classes.push(index); else if (type === "H") functions.push(index); else cstrs.push(index); return "" }); var fields = declarations.replace(/^(?:\s*;)+/, "").split(/;(?:\s*;)*/g); var baseClassName, interfacesNames; var i; if (baseName !== undef) baseClassName = baseName.replace(/^\s*extends\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)\s*$/g, "$1"); if (interfaces !== undef) interfacesNames = interfaces.replace(/^\s*implements\s+(.+?)\s*$/g, "$1").split(/\s*,\s*/g); for (i = 0; i < functions.length; ++i) functions[i] = transformFunction(atoms[functions[i]]); for (i = 0; i < methods.length; ++i) methods[i] = transformClassMethod(atoms[methods[i]]); for (i = 0; i < fields.length - 1; ++i) { var field = trimSpaces(fields[i]); fields[i] = transformClassField(field.middle) } var tail = fields.pop(); for (i = 0; i < cstrs.length; ++i) cstrs[i] = transformConstructor(atoms[cstrs[i]]); for (i = 0; i < classes.length; ++i) classes[i] = transformInnerClass(atoms[classes[i]]); return new AstClassBody(name, baseClassName, interfacesNames, functions, methods, fields, cstrs, classes, { tail: tail }) }; function AstInterface(name, body) { this.name = name; this.body = body; body.owner = this } AstInterface.prototype.toString = function() { return "var " + this.name + " = " + this.body + ";\n" + "$p." + this.name + " = " + this.name + ";\n" }; function AstClass(name, body) { this.name = name; this.body = body; body.owner = this } AstClass.prototype.toString = function() { return "var " + this.name + " = " + this.body + ";\n" + "$p." + this.name + " = " + this.name + ";\n" }; function transformGlobalClass(class_) { var m = classesRegex.exec(class_); classesRegex.lastIndex = 0; var body = atoms[getAtomIndex(m[6])]; var oldClassId = currentClassId, newClassId = generateClassId(); currentClassId = newClassId; var globalClass; if (m[2] === "interface") globalClass = new AstInterface(m[3], transformInterfaceBody(body, m[3], m[4])); else globalClass = new AstClass(m[3], transformClassBody(body, m[3], m[4], m[5])); appendClass(globalClass, newClassId, oldClassId); currentClassId = oldClassId; return globalClass } function AstMethod(name, params, body) { this.name = name; this.params = params; this.body = body } AstMethod.prototype.toString = function() { var paramNames = appendToLookupTable({}, this.params.getNames()); var oldContext = replaceContext; replaceContext = function(subject) { return paramNames.hasOwnProperty(subject.name) ? subject.name : oldContext(subject) }; var body = this.params.prependMethodArgs(this.body.toString()); var result = "function " + this.name + this.params + " " + body + "\n" + "$p." + this.name + " = " + this.name + ";"; replaceContext = oldContext; return result }; function transformGlobalMethod(method) { var m = methodsRegex.exec(method); var result = methodsRegex.lastIndex = 0; return new AstMethod(m[3], transformParams(atoms[getAtomIndex(m[4])]), transformStatementsBlock(atoms[getAtomIndex(m[6])])) } function preStatementsTransform(statements) { var s = statements; s = s.replace(/\b(catch\s*"B\d+"\s*"A\d+")(\s*catch\s*"B\d+"\s*"A\d+")+/g, "$1"); return s } function AstForStatement(argument, misc) { this.argument = argument; this.misc = misc } AstForStatement.prototype.toString = function() { return this.misc.prefix + this.argument.toString() }; function AstCatchStatement(argument, misc) { this.argument = argument; this.misc = misc } AstCatchStatement.prototype.toString = function() { return this.misc.prefix + this.argument.toString() }; function AstPrefixStatement(name, argument, misc) { this.name = name; this.argument = argument; this.misc = misc } AstPrefixStatement.prototype.toString = function() { var result = this.misc.prefix; if (this.argument !== undef) result += this.argument.toString(); return result }; function AstSwitchCase(expr) { this.expr = expr } AstSwitchCase.prototype.toString = function() { return "case " + this.expr + ":" }; function AstLabel(label) { this.label = label } AstLabel.prototype.toString = function() { return this.label }; transformStatements = function(statements, transformMethod, transformClass) { var nextStatement = new RegExp(/\b(catch|for|if|switch|while|with)\s*"B(\d+)"|\b(do|else|finally|return|throw|try|break|continue)\b|("[ADEH](\d+)")|\b(case)\s+([^:]+):|\b([A-Za-z_$][\w$]*\s*:)|(;)/g); var res = []; statements = preStatementsTransform(statements); var lastIndex = 0, m, space; while ((m = nextStatement.exec(statements)) !== null) { if (m[1] !== undef) { var i = statements.lastIndexOf('"B', nextStatement.lastIndex); var statementsPrefix = statements.substring(lastIndex, i); if (m[1] === "for") res.push(new AstForStatement(transformForExpression(atoms[m[2]]), { prefix: statementsPrefix })); else if (m[1] === "catch") res.push(new AstCatchStatement(transformParams(atoms[m[2]]), { prefix: statementsPrefix })); else res.push(new AstPrefixStatement(m[1], transformExpression(atoms[m[2]]), { prefix: statementsPrefix })) } else if (m[3] !== undef) res.push(new AstPrefixStatement(m[3], undef, { prefix: statements.substring(lastIndex, nextStatement.lastIndex) })); else if (m[4] !== undef) { space = statements.substring(lastIndex, nextStatement.lastIndex - m[4].length); if (trim(space).length !== 0) continue; res.push(space); var kind = m[4].charAt(1), atomIndex = m[5]; if (kind === "D") res.push(transformMethod(atoms[atomIndex])); else if (kind === "E") res.push(transformClass(atoms[atomIndex])); else if (kind === "H") res.push(transformFunction(atoms[atomIndex])); else res.push(transformStatementsBlock(atoms[atomIndex])) } else if (m[6] !== undef) res.push(new AstSwitchCase(transformExpression(trim(m[7])))); else if (m[8] !== undef) { space = statements.substring(lastIndex, nextStatement.lastIndex - m[8].length); if (trim(space).length !== 0) continue; res.push(new AstLabel(statements.substring(lastIndex, nextStatement.lastIndex))) } else { var statement = trimSpaces(statements.substring(lastIndex, nextStatement.lastIndex - 1)); res.push(statement.left); res.push(transformStatement(statement.middle)); res.push(statement.right + ";") } lastIndex = nextStatement.lastIndex } var statementsTail = trimSpaces(statements.substring(lastIndex)); res.push(statementsTail.left); if (statementsTail.middle !== "") { res.push(transformStatement(statementsTail.middle)); res.push(";" + statementsTail.right) } return res }; function getLocalNames(statements) { var localNames = []; for (var i = 0, l = statements.length; i < l; ++i) { var statement = statements[i]; if (statement instanceof AstVar) localNames = localNames.concat(statement.getNames()); else if (statement instanceof AstForStatement && statement.argument.initStatement instanceof AstVar) localNames = localNames.concat(statement.argument.initStatement.getNames()); else if (statement instanceof AstInnerInterface || statement instanceof AstInnerClass || statement instanceof AstInterface || statement instanceof AstClass || statement instanceof AstMethod || statement instanceof AstFunction) localNames.push(statement.name) } return appendToLookupTable({}, localNames) } function AstStatementsBlock(statements) { this.statements = statements } AstStatementsBlock.prototype.toString = function() { var localNames = getLocalNames(this.statements); var oldContext = replaceContext; if (!isLookupTableEmpty(localNames)) replaceContext = function(subject) { return localNames.hasOwnProperty(subject.name) ? subject.name : oldContext(subject) }; var result = "{\n" + this.statements.join("") + "\n}"; replaceContext = oldContext; return result }; transformStatementsBlock = function(block) { var content = trimSpaces(block.substring(1, block.length - 1)); return new AstStatementsBlock(transformStatements(content.middle)) }; function AstRoot(statements) { this.statements = statements } AstRoot.prototype.toString = function() { var classes = [], otherStatements = [], statement; for (var i = 0, len = this.statements.length; i < len; ++i) { statement = this.statements[i]; if (statement instanceof AstClass || statement instanceof AstInterface) classes.push(statement); else otherStatements.push(statement) } sortByWeight(classes); var localNames = getLocalNames(this.statements); replaceContext = function(subject) { var name = subject.name; if (localNames.hasOwnProperty(name)) return name; if (globalMembers.hasOwnProperty(name) || PConstants.hasOwnProperty(name) || defaultScope.hasOwnProperty(name)) return "$p." + name; return name }; var result = "// this code was autogenerated from PJS\n" + "(function($p) {\n" + classes.join("") + "\n" + otherStatements.join("") + "\n})"; replaceContext = null; return result }; transformMain = function() { var statements = extractClassesAndMethods(atoms[0]); statements = statements.replace(/\bimport\s+[^;]+;/g, ""); return new AstRoot(transformStatements(statements, transformGlobalMethod, transformGlobalClass)) }; function generateMetadata(ast) { var globalScope = {}; var id, class_; for (id in declaredClasses) if (declaredClasses.hasOwnProperty(id)) { class_ = declaredClasses[id]; var scopeId = class_.scopeId, name = class_.name; if (scopeId) { var scope = declaredClasses[scopeId]; class_.scope = scope; if (scope.inScope === undef) scope.inScope = {}; scope.inScope[name] = class_ } else globalScope[name] = class_ } function findInScopes(class_, name) { var parts = name.split("."); var currentScope = class_.scope, found; while (currentScope) { if (currentScope.hasOwnProperty(parts[0])) { found = currentScope[parts[0]]; break } currentScope = currentScope.scope } if (found === undef) found = globalScope[parts[0]]; for (var i = 1, l = parts.length; i < l && found; ++i) found = found.inScope[parts[i]]; return found } for (id in declaredClasses) if (declaredClasses.hasOwnProperty(id)) { class_ = declaredClasses[id]; var baseClassName = class_.body.baseClassName; if (baseClassName) { var parent = findInScopes(class_, baseClassName); if (parent) { class_.base = parent; if (!parent.derived) parent.derived = []; parent.derived.push(class_) } } var interfacesNames = class_.body.interfacesNames, interfaces = [], i, l; if (interfacesNames && interfacesNames.length > 0) { for (i = 0, l = interfacesNames.length; i < l; ++i) { var interface_ = findInScopes(class_, interfacesNames[i]); interfaces.push(interface_); if (!interface_) continue; if (!interface_.derived) interface_.derived = []; interface_.derived.push(class_) } if (interfaces.length > 0) class_.interfaces = interfaces } } } function setWeight(ast) { var queue = [], tocheck = {}; var id, scopeId, class_; for (id in declaredClasses) if (declaredClasses.hasOwnProperty(id)) { class_ = declaredClasses[id]; if (!class_.inScope && !class_.derived) { queue.push(id); class_.weight = 0 } else { var dependsOn = []; if (class_.inScope) for (scopeId in class_.inScope) if (class_.inScope.hasOwnProperty(scopeId)) dependsOn.push(class_.inScope[scopeId]); if (class_.derived) dependsOn = dependsOn.concat(class_.derived); tocheck[id] = dependsOn } } function removeDependentAndCheck(targetId, from) { var dependsOn = tocheck[targetId]; if (!dependsOn) return false; var i = dependsOn.indexOf(from); if (i < 0) return false; dependsOn.splice(i, 1); if (dependsOn.length > 0) return false; delete tocheck[targetId]; return true } while (queue.length > 0) { id = queue.shift(); class_ = declaredClasses[id]; if (class_.scopeId && removeDependentAndCheck(class_.scopeId, class_)) { queue.push(class_.scopeId); declaredClasses[class_.scopeId].weight = class_.weight + 1 } if (class_.base && removeDependentAndCheck(class_.base.classId, class_)) { queue.push(class_.base.classId); class_.base.weight = class_.weight + 1 } if (class_.interfaces) { var i, l; for (i = 0, l = class_.interfaces.length; i < l; ++i) { if (!class_.interfaces[i] || !removeDependentAndCheck(class_.interfaces[i].classId, class_)) continue; queue.push(class_.interfaces[i].classId); class_.interfaces[i].weight = class_.weight + 1 } } } } var transformed = transformMain(); generateMetadata(transformed); setWeight(transformed); var redendered = transformed.toString(); redendered = redendered.replace(/\s*\n(?:[\t ]*\n)+/g, "\n\n"); redendered = redendered.replace(/__x([0-9A-F]{4})/g, function(all, hexCode) { return String.fromCharCode(parseInt(hexCode, 16)) }); return injectStrings(redendered, strings) } function preprocessCode(aCode, sketch) { var dm = (new RegExp(/\/\*\s*@pjs\s+((?:[^\*]|\*+[^\*\/])*)\*\//g)).exec(aCode); if (dm && dm.length === 2) { var jsonItems = [], directives = dm.splice(1, 2)[0].replace(/\{([\s\S]*?)\}/g, function() { return function(all, item) { jsonItems.push(item); return "{" + (jsonItems.length - 1) + "}" } }()).replace("\n", "").replace("\r", "").split(";"); var clean = function(s) { return s.replace(/^\s*["']?/, "").replace(/["']?\s*$/, "") }; for (var i = 0, dl = directives.length; i < dl; i++) { var pair = directives[i].split("="); if (pair && pair.length === 2) { var key = clean(pair[0]), value = clean(pair[1]), list = []; if (key === "preload") { list = value.split(","); for (var j = 0, jl = list.length; j < jl; j++) { var imageName = clean(list[j]); sketch.imageCache.add(imageName) } } else if (key === "font") { list = value.split(","); for (var x = 0, xl = list.length; x < xl; x++) { var fontName = clean(list[x]), index = /^\{(\d*?)\}$/.exec(fontName); PFont.preloading.add(index ? JSON.parse("{" + jsonItems[index[1]] + "}") : fontName) } } else if (key === "pauseOnBlur") sketch.options.pauseOnBlur = value === "true"; else if (key === "globalKeyEvents") sketch.options.globalKeyEvents = value === "true"; else if (key.substring(0, 6) === "param-") sketch.params[key.substring(6)] = value; else sketch.options[key] = value } } } return aCode } Processing.compile = function(pdeCode) { var sketch = new Processing.Sketch; var code = preprocessCode(pdeCode, sketch); var compiledPde = parseProcessing(code); sketch.sourceCode = compiledPde; return sketch }; var tinylogLite = function() { var tinylogLite = {}, undef = "undefined", func = "function", False = !1, True = !0, logLimit = 512, log = "log"; if (typeof tinylog !== undef && typeof tinylog[log] === func) tinylogLite[log] = tinylog[log]; else if (typeof document !== undef && !document.fake)(function() { var doc = document, $div = "div", $style = "style", $title = "title", containerStyles = { zIndex: 1E4, position: "fixed", bottom: "0px", width: "100%", height: "15%", fontFamily: "sans-serif", color: "#ccc", backgroundColor: "black" }, outputStyles = { position: "relative", fontFamily: "monospace", overflow: "auto", height: "100%", paddingTop: "5px" }, resizerStyles = { height: "5px", marginTop: "-5px", cursor: "n-resize", backgroundColor: "darkgrey" }, closeButtonStyles = { position: "absolute", top: "5px", right: "20px", color: "#111", MozBorderRadius: "4px", webkitBorderRadius: "4px", borderRadius: "4px", cursor: "pointer", fontWeight: "normal", textAlign: "center", padding: "3px 5px", backgroundColor: "#333", fontSize: "12px" }, entryStyles = { minHeight: "16px" }, entryTextStyles = { fontSize: "12px", margin: "0 8px 0 8px", maxWidth: "100%", whiteSpace: "pre-wrap", overflow: "auto" }, view = doc.defaultView, docElem = doc.documentElement, docElemStyle = docElem[$style], setStyles = function() { var i = arguments.length, elemStyle, styles, style; while (i--) { styles = arguments[i--]; elemStyle = arguments[i][$style]; for (style in styles) if (styles.hasOwnProperty(style)) elemStyle[style] = styles[style] } }, observer = function(obj, event, handler) { if (obj.addEventListener) obj.addEventListener(event, handler, False); else if (obj.attachEvent) obj.attachEvent("on" + event, handler); return [obj, event, handler] }, unobserve = function(obj, event, handler) { if (obj.removeEventListener) obj.removeEventListener(event, handler, False); else if (obj.detachEvent) obj.detachEvent("on" + event, handler) }, clearChildren = function(node) { var children = node.childNodes, child = children.length; while (child--) node.removeChild(children.item(0)) }, append = function(to, elem) { return to.appendChild(elem) }, createElement = function(localName) { return doc.createElement(localName) }, createTextNode = function(text) { return doc.createTextNode(text) }, createLog = tinylogLite[log] = function(message) { var uninit, originalPadding = docElemStyle.paddingBottom, container = createElement($div), containerStyle = container[$style], resizer = append(container, createElement($div)), output = append(container, createElement($div)), closeButton = append(container, createElement($div)), resizingLog = False, previousHeight = False, previousScrollTop = False, messages = 0, updateSafetyMargin = function() { docElemStyle.paddingBottom = container.clientHeight + "px" }, setContainerHeight = function(height) { var viewHeight = view.innerHeight, resizerHeight = resizer.clientHeight; if (height < 0) height = 0; else if (height + resizerHeight > viewHeight) height = viewHeight - resizerHeight; containerStyle.height = height / viewHeight * 100 + "%"; updateSafetyMargin() }, observers = [observer(doc, "mousemove", function(evt) { if (resizingLog) { setContainerHeight(view.innerHeight - evt.clientY); output.scrollTop = previousScrollTop } }), observer(doc, "mouseup", function() { if (resizingLog) resizingLog = previousScrollTop = False }), observer(resizer, "dblclick", function(evt) { evt.preventDefault(); if (previousHeight) { setContainerHeight(previousHeight); previousHeight = False } else { previousHeight = container.clientHeight; containerStyle.height = "0px" } }), observer(resizer, "mousedown", function(evt) { evt.preventDefault(); resizingLog = True; previousScrollTop = output.scrollTop }), observer(resizer, "contextmenu", function() { resizingLog = False }), observer(closeButton, "click", function() { uninit() })]; uninit = function() { var i = observers.length; while (i--) unobserve.apply(tinylogLite, observers[i]); docElem.removeChild(container); docElemStyle.paddingBottom = originalPadding; clearChildren(output); clearChildren(container); tinylogLite[log] = createLog }; setStyles(container, containerStyles, output, outputStyles, resizer, resizerStyles, closeButton, closeButtonStyles); closeButton[$title] = "Close Log"; append(closeButton, createTextNode("\u2716")); resizer[$title] = "Double-click to toggle log minimization"; docElem.insertBefore(container, docElem.firstChild); tinylogLite[log] = function(message) { if (messages === logLimit) output.removeChild(output.firstChild); else messages++; var entry = append(output, createElement($div)), entryText = append(entry, createElement($div)); entry[$title] = (new Date).toLocaleTimeString(); setStyles(entry, entryStyles, entryText, entryTextStyles); append(entryText, createTextNode(message)); output.scrollTop = output.scrollHeight }; tinylogLite[log](message); updateSafetyMargin() } })(); else if (typeof print === func) tinylogLite[log] = print; return tinylogLite }(); Processing.logger = tinylogLite; Processing.version = "1.4.1"; Processing.lib = {}; Processing.registerLibrary = function(name, desc) { Processing.lib[name] = desc; if (desc.hasOwnProperty("init")) desc.init(defaultScope) }; Processing.instances = processingInstances; Processing.getInstanceById = function(name) { return processingInstances[processingInstanceIds[name]] }; Processing.Sketch = function(attachFunction) { this.attachFunction = attachFunction; this.options = { pauseOnBlur: false, globalKeyEvents: false }; this.onLoad = nop; this.onSetup = nop; this.onPause = nop; this.onLoop = nop; this.onFrameStart = nop; this.onFrameEnd = nop; this.onExit = nop; this.params = {}; this.imageCache = { pending: 0, images: {}, operaCache: {}, add: function(href, img) { if (this.images[href]) return; if (!isDOMPresent) this.images[href] = null; if (!img) { img = new Image; img.onload = function(owner) { return function() { owner.pending-- } }(this); this.pending++; img.src = href } this.images[href] = img; if (window.opera) { var div = document.createElement("div"); div.appendChild(img); div.style.position = "absolute"; div.style.opacity = 0; div.style.width = "1px"; div.style.height = "1px"; if (!this.operaCache[href]) { document.body.appendChild(div); this.operaCache[href] = div } } } }; this.sourceCode = undefined; this.attach = function(processing) { if (typeof this.attachFunction === "function") this.attachFunction(processing); else if (this.sourceCode) { var func = (new Function("return (" + this.sourceCode + ");"))(); func(processing); this.attachFunction = func } else throw "Unable to attach sketch to the processing instance"; }; this.toString = function() { var i; var code = "((function(Sketch) {\n"; code += "var sketch = new Sketch(\n" + this.sourceCode + ");\n"; for (i in this.options) if (this.options.hasOwnProperty(i)) { var value = this.options[i]; code += "sketch.options." + i + " = " + (typeof value === "string" ? '"' + value + '"' : "" + value) + ";\n" } for (i in this.imageCache) if (this.options.hasOwnProperty(i)) code += 'sketch.imageCache.add("' + i + '");\n'; code += "return sketch;\n})(Processing.Sketch))"; return code } }; var loadSketchFromSources = function(canvas, sources) { var code = [], errors = [], sourcesCount = sources.length, loaded = 0; function ajaxAsync(url, callback) { var xhr = new XMLHttpRequest; xhr.onreadystatechange = function() { if (xhr.readyState === 4) { var error; if (xhr.status !== 200 && xhr.status !== 0) error = "Invalid XHR status " + xhr.status; else if (xhr.responseText === "") if ("withCredentials" in new XMLHttpRequest && (new XMLHttpRequest).withCredentials === false && window.location.protocol === "file:") error = "XMLHttpRequest failure, possibly due to a same-origin policy violation. You can try loading this page in another browser, or load it from http://localhost using a local webserver. See the Processing.js README for a more detailed explanation of this problem and solutions."; else error = "File is empty."; callback(xhr.responseText, error) } }; xhr.open("GET", url, true); if (xhr.overrideMimeType) xhr.overrideMimeType("application/json"); xhr.setRequestHeader("If-Modified-Since", "Fri, 01 Jan 1960 00:00:00 GMT"); xhr.send(null) } function loadBlock(index, filename) { function callback(block, error) { code[index] = block; ++loaded; if (error) errors.push(filename + " ==> " + error); if (loaded === sourcesCount) if (errors.length === 0) try { return new Processing(canvas, code.join("\n")) } catch(e) { throw "Processing.js: Unable to execute pjs sketch: " + e; } else throw "Processing.js: Unable to load pjs sketch files: " + errors.join("\n"); } if (filename.charAt(0) === "#") { var scriptElement = document.getElementById(filename.substring(1)); if (scriptElement) callback(scriptElement.text || scriptElement.textContent); else callback("", "Unable to load pjs sketch: element with id '" + filename.substring(1) + "' was not found"); return } ajaxAsync(filename, callback) } for (var i = 0; i < sourcesCount; ++i) loadBlock(i, sources[i]) }; var init = function() { document.removeEventListener("DOMContentLoaded", init, false); processingInstances = []; var canvas = document.getElementsByTagName("canvas"), filenames; for (var i = 0, l = canvas.length; i < l; i++) { var processingSources = canvas[i].getAttribute("data-processing-sources"); if (processingSources === null) { processingSources = canvas[i].getAttribute("data-src"); if (processingSources === null) processingSources = canvas[i].getAttribute("datasrc") } if (processingSources) { filenames = processingSources.split(/\s+/g); for (var j = 0; j < filenames.length;) if (filenames[j]) j++; else filenames.splice(j, 1); loadSketchFromSources(canvas[i], filenames) } } var s, last, source, instance, nodelist = document.getElementsByTagName("script"), scripts = []; for (s = nodelist.length - 1; s >= 0; s--) scripts.push(nodelist[s]); for (s = 0, last = scripts.length; s < last; s++) { var script = scripts[s]; if (!script.getAttribute) continue; var type = script.getAttribute("type"); if (type && (type.toLowerCase() === "text/processing" || type.toLowerCase() === "application/processing")) { var target = script.getAttribute("data-processing-target"); canvas = undef; if (target) canvas = document.getElementById(target); else { var nextSibling = script.nextSibling; while (nextSibling && nextSibling.nodeType !== 1) nextSibling = nextSibling.nextSibling; if (nextSibling && nextSibling.nodeName.toLowerCase() === "canvas") canvas = nextSibling } if (canvas) { if (script.getAttribute("src")) { filenames = script.getAttribute("src").split(/\s+/); loadSketchFromSources(canvas, filenames); continue } source = script.textContent || script.text; instance = new Processing(canvas, source) } } } }; Processing.reload = function() { if (processingInstances.length > 0) for (var i = processingInstances.length - 1; i >= 0; i--) if (processingInstances[i]) processingInstances[i].exit(); init() }; Processing.loadSketchFromSources = loadSketchFromSources; Processing.disableInit = function() { if (isDOMPresent) document.removeEventListener("DOMContentLoaded", init, false) }; if (isDOMPresent) { window["Processing"] = Processing; document.addEventListener("DOMContentLoaded", init, false) } else this.Processing = Processing })(window, window.document, Math);
JavaScript
$(document).ready(function(){ $(".flip").click(function(){ $(".panel").slideToggle("slow"); }); }); $(document).ready(function(){ $("p.box2").hide(); }); $(document).ready(function(){ $("#box").mouseenter(function(){ $("p.box2").show("slow"); }); }); $(document).ready(function(){ $("#box").mouseleave(function(){ $("p.box2").hide("slow"); }); });
JavaScript
$(document).ready(function(){ $("img.small").mouseover(function(){ $("img.small").css("height","80px"); }); }); $(document).ready(function(){ $("img.small").mouseout(function(){ $("img.small").css("height","50px"); }); });
JavaScript
/*! * jQuery blockUI plugin * Version 2.53 (01-NOV-2012) * @requires jQuery v1.3 or later * * Examples at: http://malsup.com/jquery/block/ * Copyright (c) 2007-2012 M. Alsup * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Thanks to Amir-Hossein Sobhi for some excellent contributions! */ ;(function() { "use strict"; function setup($) { if (/^1\.(0|1|2)/.test($.fn.jquery)) { /*global alert:true */ alert('blockUI requires jQuery v1.3 or later! You are using v' + $.fn.jquery); return; } $.fn._fadeIn = $.fn.fadeIn; var noOp = $.noop || function() {}; // this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle // retarded userAgent strings on Vista) var msie = /MSIE/.test(navigator.userAgent); var ie6 = /MSIE 6.0/.test(navigator.userAgent); var mode = document.documentMode || 0; // var setExpr = msie && (($.browser.version < 8 && !mode) || mode < 8); var setExpr = $.isFunction( document.createElement('div').style.setExpression ); // global $ methods for blocking/unblocking the entire page $.blockUI = function(opts) { install(window, opts); }; $.unblockUI = function(opts) { remove(window, opts); SynClean();}; // convenience method for quick growl-like notifications (http://www.google.com/search?q=growl) $.growlUI = function(title, message, timeout, onClose) { var $m = $('<div class="growlUI"></div>'); if (title) $m.append('<h1>'+title+'</h1>'); if (message) $m.append('<h2>'+message+'</h2>'); if (timeout === undefined) timeout = 3000; $.blockUI({ message: $m, fadeIn: 700, fadeOut: 1000, centerY: false, timeout: timeout, showOverlay: false, onUnblock: onClose, css: $.blockUI.defaults.growlCSS }); }; // plugin method for blocking element content $.fn.block = function(opts) { var fullOpts = $.extend({}, $.blockUI.defaults, opts || {}); this.each(function() { var $el = $(this); if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked')) return; $el.unblock({ fadeOut: 0 }); }); return this.each(function() { if ($.css(this,'position') == 'static') this.style.position = 'relative'; this.style.zoom = 1; // force 'hasLayout' in ie install(this, opts); }); }; // plugin method for unblocking element content $.fn.unblock = function(opts) { return this.each(function() { remove(this, opts); }); }; $.blockUI.version = 2.53; // 2nd generation blocking at no extra cost! // override these in your code to change the default behavior and style $.blockUI.defaults = { // message displayed when blocking (use null for no message) message: '<h1>Please wait...</h1>', title: null, // title string; only used when theme == true draggable: true, // only used when theme == true (requires jquery-ui.js to be loaded) theme: false, // set to true to use with jQuery UI themes // styles for the message when blocking; if you wish to disable // these and use an external stylesheet then do this in your code: // $.blockUI.defaults.css = {}; css: { padding: 0, margin: 0, width: '30%', top: '40%', left: '35%', textAlign: 'center', color: '#000', border: '3px solid #aaa', backgroundColor:'#fff', cursor: 'wait' }, // minimal style set used when themes are used themedCSS: { width: '30%', top: '40%', left: '35%' }, // styles for the overlay overlayCSS: { backgroundColor: '#000', opacity: 0.6, cursor: 'wait' }, // style to replace wait cursor before unblocking to correct issue // of lingering wait cursor cursorReset: 'default', // styles applied when using $.growlUI growlCSS: { width: '350px', top: '10px', left: '', right: '10px', border: 'none', padding: '5px', opacity: 0.6, cursor: 'default', color: '#fff', backgroundColor: '#000', '-webkit-border-radius':'10px', '-moz-border-radius': '10px', 'border-radius': '10px' }, // IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w // (hat tip to Jorge H. N. de Vasconcelos) /*jshint scripturl:true */ iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', // force usage of iframe in non-IE browsers (handy for blocking applets) forceIframe: false, // z-index for the blocking overlay baseZ: 1000, // set these to true to have the message automatically centered centerX: true, // <-- only effects element blocking (page block controlled via css above) centerY: true, // allow body element to be stetched in ie6; this makes blocking look better // on "short" pages. disable if you wish to prevent changes to the body height allowBodyStretch: true, // enable if you want key and mouse events to be disabled for content that is blocked bindEvents: true, // be default blockUI will supress tab navigation from leaving blocking content // (if bindEvents is true) constrainTabKey: true, // fadeIn time in millis; set to 0 to disable fadeIn on block fadeIn: 200, // fadeOut time in millis; set to 0 to disable fadeOut on unblock fadeOut: 400, // time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock timeout: 0, // disable if you don't want to show the overlay showOverlay: true, // if true, focus will be placed in the first available input field when // page blocking focusInput: true, // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity) // no longer needed in 2012 // applyPlatformOpacityRules: true, // callback method invoked when fadeIn has completed and blocking message is visible onBlock: null, // callback method invoked when unblocking has completed; the callback is // passed the element that has been unblocked (which is the window object for page // blocks) and the options that were passed to the unblock call: // onUnblock(element, options) onUnblock: null, // callback method invoked when the overlay area is clicked. // setting this will turn the cursor to a pointer, otherwise cursor defined in overlayCss will be used. onOverlayClick: null, // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493 quirksmodeOffsetHack: 4, // class name of the message block blockMsgClass: 'blockMsg', // if it is already blocked, then ignore it (don't unblock and reblock) ignoreIfBlocked: false }; // private data and functions follow... var pageBlock = null; var pageBlockEls = []; function install(el, opts) { var css, themedCSS; var full = (el == window); var msg = (opts && opts.message !== undefined ? opts.message : undefined); opts = $.extend({}, $.blockUI.defaults, opts || {}); if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked')) return; opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {}); css = $.extend({}, $.blockUI.defaults.css, opts.css || {}); if (opts.onOverlayClick) opts.overlayCSS.cursor = 'pointer'; themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {}); msg = msg === undefined ? opts.message : msg; // remove the current block (if there is one) if (full && pageBlock) remove(window, {fadeOut:0}); // if an existing element is being used as the blocking content then we capture // its current place in the DOM (and current display style) so we can restore // it when we unblock if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) { var node = msg.jquery ? msg[0] : msg; var data = {}; $(el).data('blockUI.history', data); data.el = node; data.parent = node.parentNode; data.display = node.style.display; data.position = node.style.position; if (data.parent) data.parent.removeChild(node); } $(el).data('blockUI.onUnblock', opts.onUnblock); var z = opts.baseZ; // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform; // layer1 is the iframe layer which is used to supress bleed through of underlying content // layer2 is the overlay layer which has opacity and a wait cursor (by default) // layer3 is the message content that is displayed while blocking var lyr1, lyr2, lyr3, s; if (msie || opts.forceIframe) lyr1 = $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>'); else lyr1 = $('<div class="blockUI" style="display:none"></div>'); if (opts.theme) lyr2 = $('<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:'+ (z++) +';display:none"></div>'); else lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>'); if (opts.theme && full) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:fixed">'; if ( opts.title ) { s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>'; } s += '<div class="ui-widget-content ui-dialog-content"></div>'; s += '</div>'; } else if (opts.theme) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:absolute">'; if ( opts.title ) { s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>'; } s += '<div class="ui-widget-content ui-dialog-content"></div>'; s += '</div>'; } else if (full) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage" style="z-index:'+(z+10)+';display:none;position:fixed"></div>'; } else { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement" style="z-index:'+(z+10)+';display:none;position:absolute"></div>'; } lyr3 = $(s); // if we have a message, style it if (msg) { if (opts.theme) { lyr3.css(themedCSS); lyr3.addClass('ui-widget-content'); } else lyr3.css(css); } // style the overlay if (!opts.theme /*&& (!opts.applyPlatformOpacityRules)*/) lyr2.css(opts.overlayCSS); lyr2.css('position', full ? 'fixed' : 'absolute'); // make iframe layer transparent in IE if (msie || opts.forceIframe) lyr1.css('opacity',0.0); //$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el); var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el); $.each(layers, function() { this.appendTo($par); }); if (opts.theme && opts.draggable && $.fn.draggable) { lyr3.draggable({ handle: '.ui-dialog-titlebar', cancel: 'li' }); } // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling) var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0); if (ie6 || expr) { // give body 100% height if (full && opts.allowBodyStretch && $.support.boxModel) $('html,body').css('height','100%'); // fix ie6 issue when blocked element has a border width if ((ie6 || !$.support.boxModel) && !full) { var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth'); var fixT = t ? '(0 - '+t+')' : 0; var fixL = l ? '(0 - '+l+')' : 0; } // simulate fixed position $.each(layers, function(i,o) { var s = o[0].style; s.position = 'absolute'; if (i < 2) { if (full) s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"'); else s.setExpression('height','this.parentNode.offsetHeight + "px"'); if (full) s.setExpression('width','jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"'); else s.setExpression('width','this.parentNode.offsetWidth + "px"'); if (fixL) s.setExpression('left', fixL); if (fixT) s.setExpression('top', fixT); } else if (opts.centerY) { if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"'); s.marginTop = 0; } else if (!opts.centerY && full) { var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0; var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"'; s.setExpression('top',expression); } }); } // show the message if (msg) { if (opts.theme) lyr3.find('.ui-widget-content').append(msg); else lyr3.append(msg); if (msg.jquery || msg.nodeType) $(msg).show(); } if ((msie || opts.forceIframe) && opts.showOverlay) lyr1.show(); // opacity is zero if (opts.fadeIn) { var cb = opts.onBlock ? opts.onBlock : noOp; var cb1 = (opts.showOverlay && !msg) ? cb : noOp; var cb2 = msg ? cb : noOp; if (opts.showOverlay) lyr2._fadeIn(opts.fadeIn, cb1); if (msg) lyr3._fadeIn(opts.fadeIn, cb2); } else { if (opts.showOverlay) lyr2.show(); if (msg) lyr3.show(); if (opts.onBlock) opts.onBlock(); } // bind key and mouse events bind(1, el, opts); if (full) { pageBlock = lyr3[0]; pageBlockEls = $(':input:enabled:visible',pageBlock); if (opts.focusInput) setTimeout(focus, 20); } else center(lyr3[0], opts.centerX, opts.centerY); if (opts.timeout) { // auto-unblock var to = setTimeout(function() { if (full) $.unblockUI(opts); else $(el).unblock(opts); }, opts.timeout); $(el).data('blockUI.timeout', to); } } // remove the block function remove(el, opts) { var full = (el == window); var $el = $(el); var data = $el.data('blockUI.history'); var to = $el.data('blockUI.timeout'); if (to) { clearTimeout(to); $el.removeData('blockUI.timeout'); } opts = $.extend({}, $.blockUI.defaults, opts || {}); bind(0, el, opts); // unbind events if (opts.onUnblock === null) { opts.onUnblock = $el.data('blockUI.onUnblock'); $el.removeData('blockUI.onUnblock'); } var els; if (full) // crazy selector to handle odd field errors in ie6/7 els = $('body').children().filter('.blockUI').add('body > .blockUI'); else els = $el.find('>.blockUI'); // fix cursor issue if ( opts.cursorReset ) { if ( els.length > 1 ) els[1].style.cursor = opts.cursorReset; if ( els.length > 2 ) els[2].style.cursor = opts.cursorReset; } if (full) pageBlock = pageBlockEls = null; if (opts.fadeOut) { els.fadeOut(opts.fadeOut); setTimeout(function() { reset(els,data,opts,el); }, opts.fadeOut); } else reset(els, data, opts, el); } // move blocking element back into the DOM where it started function reset(els,data,opts,el) { els.each(function(i,o) { // remove via DOM calls so we don't lose event handlers if (this.parentNode) this.parentNode.removeChild(this); }); if (data && data.el) { data.el.style.display = data.display; data.el.style.position = data.position; if (data.parent) data.parent.appendChild(data.el); $(el).removeData('blockUI.history'); } if (typeof opts.onUnblock == 'function') opts.onUnblock(el,opts); // fix issue in Safari 6 where block artifacts remain until reflow var body = $(document.body), w = body.width(), cssW = body[0].style.width; body.width(w-1).width(w); body[0].style.width = cssW; } // bind/unbind the handler function bind(b, el, opts) { var full = el == window, $el = $(el); // don't bother unbinding if there is nothing to unbind if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked'))) return; $el.data('blockUI.isBlocked', b); // don't bind events when overlay is not in use or if bindEvents is false if (!opts.bindEvents || (b && !opts.showOverlay)) return; // bind anchors and inputs for mouse and key events var events = 'mousedown mouseup keydown keypress touchstart touchend touchmove'; if (b) $(document).bind(events, opts, handler); else $(document).unbind(events, handler); // former impl... // var $e = $('a,:input'); // b ? $e.bind(events, opts, handler) : $e.unbind(events, handler); } // event handler to suppress keyboard/mouse events when blocking function handler(e) { // allow tab navigation (conditionally) if (e.keyCode && e.keyCode == 9) { if (pageBlock && e.data.constrainTabKey) { var els = pageBlockEls; var fwd = !e.shiftKey && e.target === els[els.length-1]; var back = e.shiftKey && e.target === els[0]; if (fwd || back) { setTimeout(function(){focus(back);},10); return false; } } } var opts = e.data; var target = $(e.target); if (target.hasClass('blockOverlay') && opts.onOverlayClick) opts.onOverlayClick(); // allow events within the message content if (target.parents('div.' + opts.blockMsgClass).length > 0) return true; // allow events for content that is not being blocked return target.parents().children().filter('div.blockUI').length === 0; } function focus(back) { if (!pageBlockEls) return; var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0]; if (e) e.focus(); } function center(el, x, y) { var p = el.parentNode, s = el.style; var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth'); var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth'); if (x) s.left = l > 0 ? (l+'px') : '0'; if (y) s.top = t > 0 ? (t+'px') : '0'; } function sz(el, p) { return parseInt($.css(el,p),10)||0; } } /*global define:true */ if (typeof define === 'function' && define.amd && define.amd.jQuery) { define(['jquery'], setup); } else { setup(jQuery); } })();
JavaScript
/** * impress.js * * impress.js is a presentation tool based on the power of CSS3 transforms and transitions * in modern browsers and inspired by the idea behind prezi.com. * * * Copyright 2011-2012 Bartek Szopka (@bartaz) * * Released under the MIT and GPL Licenses. * * ------------------------------------------------ * author: Bartek Szopka * version: 0.5.1 * url: http://bartaz.github.com/impress.js/ * source: http://github.com/bartaz/impress.js/ */ /*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, latedef:true, newcap:true, noarg:true, noempty:true, undef:true, strict:true, browser:true */ (function ( document, window ) { 'use strict'; // HELPER FUNCTIONS var pfx = (function () { var style = document.createElement('dummy').style, prefixes = 'Webkit Moz O ms Khtml'.split(' '), memory = {}; return function ( prop ) { if ( typeof memory[ prop ] === "undefined" ) { var ucProp = prop.charAt(0).toUpperCase() + prop.substr(1), props = (prop + ' ' + prefixes.join(ucProp + ' ') + ucProp).split(' '); memory[ prop ] = null; for ( var i in props ) { if ( style[ props[i] ] !== undefined ) { memory[ prop ] = props[i]; break; } } } return memory[ prop ]; }; })(); var arrayify = function ( a ) { return [].slice.call( a ); }; var css = function ( el, props ) { var key, pkey; for ( key in props ) { if ( props.hasOwnProperty(key) ) { pkey = pfx(key); if ( pkey !== null ) { el.style[pkey] = props[key]; } } } return el; }; var toNumber = function (numeric, fallback) { return isNaN(numeric) ? (fallback || 0) : Number(numeric); }; var byId = function ( id ) { return document.getElementById(id); }; var $ = function ( selector, context ) { context = context || document; return context.querySelector(selector); }; var $$ = function ( selector, context ) { context = context || document; return arrayify( context.querySelectorAll(selector) ); }; var triggerEvent = function (el, eventName, detail) { var event = document.createEvent("CustomEvent"); event.initCustomEvent(eventName, true, true, detail); el.dispatchEvent(event); }; var translate = function ( t ) { return " translate3d(" + t.x + "px," + t.y + "px," + t.z + "px) "; }; var rotate = function ( r, revert ) { var rX = " rotateX(" + r.x + "deg) ", rY = " rotateY(" + r.y + "deg) ", rZ = " rotateZ(" + r.z + "deg) "; return revert ? rZ+rY+rX : rX+rY+rZ; }; var scale = function ( s ) { return " scale(" + s + ") "; }; var perspective = function ( p ) { return " perspective(" + p + "px) "; }; var getElementFromUrl = function () { // get id from url # by removing `#` or `#/` from the beginning, // so both "fallback" `#slide-id` and "enhanced" `#/slide-id` will work return byId( window.location.hash.replace(/^#\/?/,"") ); }; var computeWindowScale = function ( config ) { var hScale = window.innerHeight / config.height, wScale = window.innerWidth / config.width, scale = hScale > wScale ? wScale : hScale; if (config.maxScale && scale > config.maxScale) { scale = config.maxScale; } if (config.minScale && scale < config.minScale) { scale = config.minScale; } return scale; }; // CHECK SUPPORT var body = document.body; var ua = navigator.userAgent.toLowerCase(); var impressSupported = ( pfx("perspective") !== null ) && ( body.classList ) && ( body.dataset ) && ( ua.search(/(iphone)|(ipod)|(android)/) === -1 ); if (!impressSupported) { // we can't be sure that `classList` is supported body.className += " impress-not-supported "; } else { body.classList.remove("impress-not-supported"); body.classList.add("impress-supported"); } // cross-browser transitionEnd event name // based on https://developer.mozilla.org/en/CSS/CSS_transitions var transitionEnd = ({ 'transition':'transitionEnd', 'OTransition':'oTransitionEnd', 'msTransition':'MSTransitionEnd', // who knows how it will end up? 'MozTransition':'transitionend', 'WebkitTransition':'webkitTransitionEnd' })[pfx("transition")]; var roots = {}; var defaults = { width: 1024, height: 768, maxScale: 1, minScale: 0, perspective: 1000, transitionDuration: 1000 }; var empty = function () { return false; }; var impress = window.impress = function ( rootId ) { // if impress.js is not supported by the browser return a dummy API // it may not be a perfect solution but we return early and avoid // running code that may use features not implemented in the browser if (!impressSupported) { return { init: empty, goto: empty, prev: empty, next: empty }; } rootId = rootId || "impress"; // if already initialized just return the API if (roots["impress-root-" + rootId]) { return roots["impress-root-" + rootId]; } // data of all presentation steps var stepsData = {}; // element of currently active step var activeStep = null; // current state (position, rotation and scale) of the presentation var currentState = null; // array of step elements var steps = null; // configuration options var config = null; // scale factor of the browser window var windowScale = null; // root presentation elements var root = byId( rootId ); var canvas = document.createElement("div"); var initialized = false; // step events var lastEntered = null; var onStepEnter = function (step) { if (lastEntered !== step) { triggerEvent(step, "impress:stepenter"); lastEntered = step; } }; var onStepLeave = function (step) { if (lastEntered === step) { triggerEvent(step, "impress:stepleave"); lastEntered = null; } }; // transitionEnd event handler var expectedTransitionTarget = null; var onTransitionEnd = function (event) { // we only care about transitions on `root` and `canvas` elements if (event.target === expectedTransitionTarget) { onStepEnter(activeStep); event.stopPropagation(); // prevent propagation from `canvas` to `root` } }; var initStep = function ( el, idx ) { var data = el.dataset, step = { translate: { x: toNumber(data.x), y: toNumber(data.y), z: toNumber(data.z) }, rotate: { x: toNumber(data.rotateX), y: toNumber(data.rotateY), z: toNumber(data.rotateZ || data.rotate) }, scale: toNumber(data.scale, 1), el: el }; if ( !el.id ) { el.id = "step-" + (idx + 1); } stepsData["impress-" + el.id] = step; css(el, { position: "absolute", transform: "translate(-50%,-50%)" + translate(step.translate) + rotate(step.rotate) + scale(step.scale), transformStyle: "preserve-3d" }); }; var init = function () { if (initialized) { return; } // setup viewport for mobile devices var meta = $("meta[name='viewport']") || document.createElement("meta"); meta.content = "width=device-width, minimum-scale=1, maximum-scale=1, user-scalable=no"; if (meta.parentNode !== document.head) { meta.name = 'viewport'; document.head.appendChild(meta); } // initialize configuration object var rootData = root.dataset; config = { width: toNumber( rootData.width, defaults.width ), height: toNumber( rootData.height, defaults.height ), maxScale: toNumber( rootData.maxScale, defaults.maxScale ), minScale: toNumber( rootData.minScale, defaults.minScale ), perspective: toNumber( rootData.perspective, defaults.perspective ), transitionDuration: toNumber( rootData.transitionDuration, defaults.transitionDuration ) }; windowScale = computeWindowScale( config ); // wrap steps with "canvas" element arrayify( root.childNodes ).forEach(function ( el ) { canvas.appendChild( el ); }); root.appendChild(canvas); // set initial styles document.documentElement.style.height = "100%"; css(body, { height: "100%", overflow: "hidden" }); var rootStyles = { position: "absolute", transformOrigin: "top left", transition: "all 0s ease-in-out", transformStyle: "preserve-3d" }; css(root, rootStyles); css(root, { top: "50%", left: "50%", transform: perspective( config.perspective/windowScale ) + scale( windowScale ) }); css(canvas, rootStyles); root.addEventListener(transitionEnd, onTransitionEnd, false); canvas.addEventListener(transitionEnd, onTransitionEnd, false); body.classList.remove("impress-disabled"); body.classList.add("impress-enabled"); // get and init steps steps = $$(".step", root); steps.forEach( initStep ); currentState = { translate: { x: 0, y: 0, z: 0 }, rotate: { x: 0, y: 0, z: 0 }, scale: 1 }; initialized = true; triggerEvent(root, "impress:init", { api: roots[ "impress-root-" + rootId ] }); }; var getStep = function ( step ) { if (typeof step === "number") { step = step < 0 ? steps[ steps.length + step] : steps[ step ]; } else if (typeof step === "string") { step = byId(step); } return (step && step.id && stepsData["impress-" + step.id]) ? step : null; }; var goto = function ( el, duration ) { if ( !initialized || !(el = getStep(el)) ) { // presentation not initialized or given element is not a step return false; } // Sometimes it's possible to trigger focus on first link with some keyboard action. // Browser in such a case tries to scroll the page to make this element visible // (even that body overflow is set to hidden) and it breaks our careful positioning. // // So, as a lousy (and lazy) workaround we will make the page scroll back to the top // whenever slide is selected // // If you are reading this and know any better way to handle it, I'll be glad to hear about it! window.scrollTo(0, 0); var step = stepsData["impress-" + el.id]; if ( activeStep ) { activeStep.classList.remove("active"); body.classList.remove("impress-on-" + activeStep.id); } el.classList.add("active"); body.classList.add("impress-on-" + el.id); var target = { rotate: { x: -step.rotate.x, y: -step.rotate.y, z: -step.rotate.z }, translate: { x: -step.translate.x, y: -step.translate.y, z: -step.translate.z }, scale: 1 / step.scale }; // check if the transition is zooming in or not var zoomin = target.scale >= currentState.scale; duration = toNumber(duration, config.transitionDuration); var delay = (duration / 2); if (el === activeStep) { windowScale = computeWindowScale(config); } var targetScale = target.scale * windowScale; expectedTransitionTarget = target.scale > currentState.scale ? root : canvas; if (activeStep && activeStep !== el) { onStepLeave(activeStep); } css(root, { // to keep the perspective look similar for different scales // we need to 'scale' the perspective, too transform: perspective( config.perspective / targetScale ) + scale( targetScale ), transitionDuration: duration + "ms", transitionDelay: (zoomin ? delay : 0) + "ms" }); css(canvas, { transform: rotate(target.rotate, true) + translate(target.translate), transitionDuration: duration + "ms", transitionDelay: (zoomin ? 0 : delay) + "ms" }); currentState = target; activeStep = el; if (duration === 0) { onStepEnter(activeStep); } return el; }; var prev = function () { var prev = steps.indexOf( activeStep ) - 1; prev = prev >= 0 ? steps[ prev ] : steps[ steps.length-1 ]; return goto(prev); }; var next = function () { var next = steps.indexOf( activeStep ) + 1; next = next < steps.length ? steps[ next ] : steps[ 0 ]; return goto(next); }; root.addEventListener("impress:init", function(){ // STEP CLASSES steps.forEach(function (step) { step.classList.add("future"); }); root.addEventListener("impress:stepenter", function (event) { event.target.classList.remove("past"); event.target.classList.remove("future"); event.target.classList.add("present"); }, false); root.addEventListener("impress:stepleave", function (event) { event.target.classList.remove("present"); event.target.classList.add("past"); }, false); }, false); root.addEventListener("impress:init", function(){ // HASH CHANGE var lastHash = ""; // `#/step-id` is used instead of `#step-id` to prevent default browser // scrolling to element in hash // // and it has to be set after animation finishes, because in Chrome it // causes transtion being laggy // BUG: http://code.google.com/p/chromium/issues/detail?id=62820 root.addEventListener("impress:stepenter", function (event) { window.location.hash = lastHash = "#/" + event.target.id; }, false); window.addEventListener("hashchange", function () { // don't go twice to same element if (window.location.hash !== lastHash) { goto( getElementFromUrl() ); } }, false); // START // by selecting step defined in url or first step of the presentation goto(getElementFromUrl() || steps[0], 0); }, false); body.classList.add("impress-disabled"); return (roots[ "impress-root-" + rootId ] = { init: init, goto: goto, next: next, prev: prev }); }; impress.supported = impressSupported; })(document, window); // EVENTS (function ( document, window ) { 'use strict'; // throttling function calls, by Remy Sharp // http://remysharp.com/2010/07/21/throttling-function-calls/ var throttle = function (fn, delay) { var timer = null; return function () { var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { fn.apply(context, args); }, delay); }; }; document.addEventListener("impress:init", function (event) { var api = event.detail.api; // keyboard navigation handlers // prevent default keydown action when one of supported key is pressed document.addEventListener("keydown", function ( event ) { if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) { event.preventDefault(); } }, false); // trigger impress action on keyup document.addEventListener("keyup", function ( event ) { if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) { switch( event.keyCode ) { case 33: // pg up case 37: // left case 38: // up api.prev(); break; case 9: // tab case 32: // space case 34: // pg down case 39: // right case 40: // down api.next(); break; } event.preventDefault(); } }, false); // delegated handler for clicking on the links to presentation steps document.addEventListener("click", function ( event ) { // event delegation with "bubbling" // check if event target (or any of its parents is a link) var target = event.target; while ( (target.tagName !== "A") && (target !== document.documentElement) ) { target = target.parentNode; } if ( target.tagName === "A" ) { var href = target.getAttribute("href"); // if it's a link to presentation step, target this step if ( href && href[0] === '#' ) { target = document.getElementById( href.slice(1) ); } } if ( api.goto(target) ) { event.stopImmediatePropagation(); event.preventDefault(); } }, false); // delegated handler for clicking on step elements document.addEventListener("click", function ( event ) { var target = event.target; // find closest step element that is not active while ( !(target.classList.contains("step") && !target.classList.contains("active")) && (target !== document.documentElement) ) { target = target.parentNode; } if ( api.goto(target) ) { event.preventDefault(); } }, false); // touch handler to detect taps on the left and right side of the screen document.addEventListener("touchstart", function ( event ) { if (event.touches.length === 1) { var x = event.touches[0].clientX, width = window.innerWidth * 0.3, result = null; if ( x < width ) { result = api.prev(); } else if ( x > window.innerWidth - width ) { result = api.next(); } if (result) { event.preventDefault(); } } }, false); // rescale presentation when window is resized window.addEventListener("resize", throttle(function () { // force going to active step again, to trigger rescaling api.goto( document.querySelector(".active"), 500 ); }, 250), false); }, false); })(document, window);
JavaScript
var xmlHttp var at function Showchat(name,str,atti) { xmlHttp=GetXmlHttpObject() if (xmlHttp==null) { alert ("Browser does not support HTTP Request") return } var url="Chat/GetChat.php" url=url+"?q="+str url=url+"&n="+name url=url+"&a="+atti url=url+"&sid="+Math.random() //document.write(url); xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true) xmlHttp.send(null) at=atti } function stateChanged() { //document.write(xmlHttp.readyState); //document.write(xmlHttp.readyState); if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById("Chatdata").innerHTML=xmlHttp.responseText setTimeout("Showchat('','',at)",2000); var div = document.getElementById('Chatdata'); div.scrollTop = div.scrollHeight; } } function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }
JavaScript
var xmlHttpskill var nam function Showskills(name) { xmlHttpskill=GetXmlHttpObject() if (xmlHttpskill==null) { alert ("Browser does not support HTTP Request") return } var url="Ajax/GetSkills.php" url=url+"?name="+name url=url+"&sid="+Math.random() //document.write(url); xmlHttpskill.onreadystatechange=stateChangedskill xmlHttpskill.open("GET",url,true) xmlHttpskill.send(null) nam=name } function stateChangedskill() { //document.write(xmlHttp.readyState); //document.write(xmlHttp.readyState); if (xmlHttpskill.readyState==4 || xmlHttpskill.readyState=="complete") { document.getElementById("Skills").innerHTML=xmlHttpskill.responseText SHH(); SH(); } } function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }
JavaScript
var xmlHttpintelligence function Showintelligence() { xmlHttpintelligence=GetXmlHttpObject() if (xmlHttpintelligence==null) { alert ("Browser does not support HTTP Request") return } var url="Ajax/GetIntelligence.php" url=url+"?sid="+Math.random() //document.write(url); xmlHttpintelligence.onreadystatechange=stateChangedintelligence xmlHttpintelligence.open("GET",url,true) xmlHttpintelligence.send(null) } function stateChangedintelligence() { //document.write(xmlHttp.readyState); //document.write(xmlHttp.readyState); if (xmlHttpintelligence.readyState==4 || xmlHttpintelligence.readyState=="complete") { document.getElementById("IntelligenceInterface").innerHTML=xmlHttpintelligence.responseText } }
JavaScript
function DeHeHS() { document.getElementById("DeHeH").style.display='inline' } function DeHeHH() { document.getElementById("DeHeH").style.display='none' } function DeArHS() { document.getElementById("DeArH").style.display='inline' } function DeArHH() { document.getElementById("DeArH").style.display='none' } function DeShHS() { document.getElementById("DeShH").style.display='inline' } function DeShHH() { document.getElementById("DeShH").style.display='none' } function TranHS() { document.getElementById("TranH").style.display='inline' } function TranHH() { document.getElementById("TranH").style.display='none' } function TrHS() { document.getElementById("TrH").style.display='inline' } function TrHH() { document.getElementById("TrH").style.display='none' } function AHS() { document.getElementById("AH").style.display='inline' } function AHH() { document.getElementById("AH").style.display='none' } function WHS() { document.getElementById("WH").style.display='inline' } function WHH() { document.getElementById("WH").style.display='none' } function DeHeS() { document.getElementById("DeHe").style.display='inline' } function DeHeH() { document.getElementById("DeHe").style.display='none' } function DeArS() { document.getElementById("DeAr").style.display='inline' } function DeArH() { document.getElementById("DeAr").style.display='none' } function DeShS() { document.getElementById("DeSh").style.display='inline' } function DeShH() { document.getElementById("DeSh").style.display='none' } function TranS() { document.getElementById("Tran").style.display='inline' } function TranH() { document.getElementById("Tran").style.display='none' } function TrS() { document.getElementById("Tr").style.display='inline' } function TrH() { document.getElementById("Tr").style.display='none' } function AS() { document.getElementById("A").style.display='inline' } function AH() { document.getElementById("A").style.display='none' } function WS() { document.getElementById("W").style.display='inline' } function WH() { document.getElementById("W").style.display='none' } function Bag1HS() { document.getElementById("Bag1H").style.display='inline' } function Bag1HH() { document.getElementById("Bag1H").style.display='none' } function Bag2HS() { document.getElementById("Bag2H").style.display='inline' } function Bag2HH() { document.getElementById("Bag2H").style.display='none' } function Bag3HS() { document.getElementById("Bag3H").style.display='inline' } function Bag3HH() { document.getElementById("Bag3H").style.display='none' } function Bag4HS() { document.getElementById("Bag4H").style.display='inline' } function Bag4HH() { document.getElementById("Bag4H").style.display='none' } function Bag5HS() { document.getElementById("Bag5H").style.display='inline' } function Bag5HH() { document.getElementById("Bag5H").style.display='none' } function Bag1S() { document.getElementById("Bag1").style.display='inline' } function Bag1H() { document.getElementById("Bag1").style.display='none' } function Bag2S() { document.getElementById("Bag2").style.display='inline' } function Bag2H() { document.getElementById("Bag2").style.display='none' } function Bag3S() { document.getElementById("Bag3").style.display='inline' } function Bag3H() { document.getElementById("Bag3").style.display='none' } function Bag4S() { document.getElementById("Bag4").style.display='inline' } function Bag4H() { document.getElementById("Bag4").style.display='none' } function Bag5S() { document.getElementById("Bag5").style.display='inline' } function Bag5H() { document.getElementById("Bag5").style.display='none' } function S1S() { document.getElementById("S1").style.display='inline' } function S1H() { document.getElementById("S1").style.display='none' } function S2S() { document.getElementById("S2").style.display='inline' } function S2H() { document.getElementById("S2").style.display='none' } function S3S() { document.getElementById("S3").style.display='inline' } function S3H() { document.getElementById("S3").style.display='none' } function S4S() { document.getElementById("S4").style.display='inline' } function S4H() { document.getElementById("S4").style.display='none' } function S5S() { document.getElementById("S5").style.display='inline' } function S5H() { document.getElementById("S5").style.display='none' } function S6S() { document.getElementById("S6").style.display='inline' } function S6H() { document.getElementById("S6").style.display='none' } function S7S() { document.getElementById("S7").style.display='inline' } function S7H() { document.getElementById("S7").style.display='none' } function S8S() { document.getElementById("S8").style.display='inline' } function S8H() { document.getElementById("S8").style.display='none' } function S9S() { document.getElementById("S9").style.display='inline' } function S9H() { document.getElementById("S9").style.display='none' } function S10S() { document.getElementById("S10").style.display='inline' } function S10H() { document.getElementById("S10").style.display='none' } function S11S() { document.getElementById("S11").style.display='inline' } function S11H() { document.getElementById("S11").style.display='none' } function S12S() { document.getElementById("S12").style.display='inline' } function S12H() { document.getElementById("S12").style.display='none' } function S13S() { document.getElementById("S13").style.display='inline' } function S13H() { document.getElementById("S13").style.display='none' } function S14S() { document.getElementById("S14").style.display='inline' } function S14H() { document.getElementById("S14").style.display='none' } function S15S() { document.getElementById("S15").style.display='inline' } function S15H() { document.getElementById("S15").style.display='none' } function S1HS() { document.getElementById("S1H").style.display='inline' } function S1HH() { document.getElementById("S1H").style.display='none' } function S2HS() { document.getElementById("S2H").style.display='inline' } function S2HH() { document.getElementById("S2H").style.display='none' } function S3HS() { document.getElementById("S3H").style.display='inline' } function S3HH() { document.getElementById("S3H").style.display='none' } function S4HS() { document.getElementById("S4H").style.display='inline' } function S4HH() { document.getElementById("S4H").style.display='none' } function S5HS() { document.getElementById("S5H").style.display='inline' } function S5HH() { document.getElementById("S5H").style.display='none' } function S6HS() { document.getElementById("S6H").style.display='inline' } function S6HH() { document.getElementById("S6H").style.display='none' } function S7HS() { document.getElementById("S7H").style.display='inline' } function S7HH() { document.getElementById("S7H").style.display='none' } function S8HS() { document.getElementById("S8H").style.display='inline' } function S8HH() { document.getElementById("S8H").style.display='none' } function S9HS() { document.getElementById("S9H").style.display='inline' } function S9HH() { document.getElementById("S9H").style.display='none' } function S10HS() { document.getElementById("S10H").style.display='inline' } function S10HH() { document.getElementById("S10H").style.display='none' } function S11HS() { document.getElementById("S11H").style.display='inline' } function S11HH() { document.getElementById("S11H").style.display='none' } function S12HS() { document.getElementById("S12H").style.display='inline' } function S12HH() { document.getElementById("S12H").style.display='none' } function S13HS() { document.getElementById("S13H").style.display='inline' } function S13HH() { document.getElementById("S13H").style.display='none' } function S14HS() { document.getElementById("S14H").style.display='inline' } function S14HH() { document.getElementById("S14H").style.display='none' } function S15HS() { document.getElementById("S15H").style.display='inline' } function S15HH() { document.getElementById("S15H").style.display='none' } function SHH() { S1HH(); S2HH(); S3HH(); S4HH(); S5HH(); S6HH(); S7HH(); S8HH(); S9HH(); S10HH(); S11HH(); S12HH(); S13HH(); S14HH(); S15HH(); } function SS() { S1S(); S2S(); S3S(); S4S(); S5S(); S6S(); S7S(); S8S(); S9S(); S10S(); S11S(); S12S(); S13S(); S14S(); S15S(); } function SH() { S1H(); S2H(); S3H(); S4H(); S5H(); S6H(); S7H(); S8H(); S9H(); S10H(); S11H(); S12H(); S13H(); S14H(); S15H(); } var xmlHttpresoperation function stateChangedresoperation() { //document.write(xmlHttp.readyState); //document.write(xmlHttp.readyState); if (xmlHttpresoperation.readyState==4 || xmlHttpresoperation.readyState=="complete") { Showresinfo(nam); Showroleinfo(nam); //document.getElementById("Resdata").innerHTML=xmlHttpres.responseText; if(xmlHttpresoperation.responseText=='full') alert('背包已满!'); } } function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } function Drop(id) { xmlHttpresoperation=GetXmlHttpObject() if (xmlHttpresoperation==null) { alert ("Browser does not support HTTP Request") return } var url="Ajax/Resoperation.php" url=url+"?dropid="+id url=url+"&sid="+Math.random() //document.write(url); xmlHttpresoperation.onreadystatechange=stateChangedresoperation xmlHttpresoperation.open("GET",url,true) xmlHttpresoperation.send(null) } function Use(id) { xmlHttpresoperation=GetXmlHttpObject() if (xmlHttpresoperation==null) { alert ("Browser does not support HTTP Request") return } var url="Ajax/Resoperation.php" url=url+"?useid="+id url=url+"&sid="+Math.random() //document.write(url); xmlHttpresoperation.onreadystatechange=stateChangedresoperation xmlHttpresoperation.open("GET",url,true) xmlHttpresoperation.send(null) } function Unequip(id) { xmlHttpresoperation=GetXmlHttpObject() if (xmlHttpresoperation==null) { alert ("Browser does not support HTTP Request") return } var url="Ajax/Resoperation.php" url=url+"?unequipid="+id url=url+"&sid="+Math.random() //document.write(url); xmlHttpresoperation.onreadystatechange=stateChangedresoperation xmlHttpresoperation.open("GET",url,true) xmlHttpresoperation.send(null) }
JavaScript
var Lastmove; var Lastsearch; function Showlocation(lo) { switch(lo){ case 1: allhide() alllocationnone(); document.getElementById("L1").style.display='none'; document.getElementById("L1H").style.display='inline'; break; case 2: allhide() alllocationnone(); document.getElementById("L2").style.display='none'; document.getElementById("L2H").style.display='inline'; break; case 3: allhide() alllocationnone(); document.getElementById("L3").style.display='none'; document.getElementById("L3H").style.display='inline'; break; case 4: allhide() alllocationnone(); document.getElementById("L4").style.display='none'; document.getElementById("L4H").style.display='inline'; break; case 5: allhide() alllocationnone(); document.getElementById("L5").style.display='none'; document.getElementById("L5H").style.display='inline'; break; case 6: allhide() alllocationnone(); document.getElementById("L6").style.display='none'; document.getElementById("L6H").style.display='inline'; break; case 7: allhide() alllocationnone(); document.getElementById("L7").style.display='none'; document.getElementById("L7H").style.display='inline'; break; case 8: allhide() alllocationnone(); document.getElementById("L8").style.display='none'; document.getElementById("L8H").style.display='inline'; break; case 9: allhide() alllocationnone(); document.getElementById("L9").style.display='none'; document.getElementById("L9H").style.display='inline'; break; case 10: allhide() alllocationnone(); document.getElementById("L10").style.display='none'; document.getElementById("L10H").style.display='inline'; break; case 11: allhide() alllocationnone(); document.getElementById("L11").style.display='none'; document.getElementById("L11H").style.display='inline'; break; case 12: allhide() alllocationnone(); document.getElementById("L12").style.display='none'; document.getElementById("L12H").style.display='inline'; break; case 13: allhide() alllocationnone(); document.getElementById("L13").style.display='none'; document.getElementById("L13H").style.display='inline'; break; case 14: allhide() alllocationnone(); document.getElementById("L14").style.display='none'; document.getElementById("L14H").style.display='inline'; break; default: allhide() alllocationnone(); } } function alllocationnone() { document.getElementById("L1").style.display='inline'; document.getElementById("L2").style.display='inline'; document.getElementById("L3").style.display='inline'; document.getElementById("L4").style.display='inline'; document.getElementById("L5").style.display='inline'; document.getElementById("L6").style.display='inline'; document.getElementById("L7").style.display='inline'; document.getElementById("L8").style.display='inline'; document.getElementById("L9").style.display='inline'; document.getElementById("L10").style.display='inline'; document.getElementById("L11").style.display='inline'; document.getElementById("L12").style.display='inline'; document.getElementById("L13").style.display='inline'; document.getElementById("L14").style.display='inline'; } function allhide() { document.getElementById("L1H").style.display='none'; document.getElementById("L2H").style.display='none'; document.getElementById("L3H").style.display='none'; document.getElementById("L4H").style.display='none'; document.getElementById("L5H").style.display='none'; document.getElementById("L6H").style.display='none'; document.getElementById("L7H").style.display='none'; document.getElementById("L8H").style.display='none'; document.getElementById("L9H").style.display='none'; document.getElementById("L10H").style.display='none'; document.getElementById("L11H").style.display='none'; document.getElementById("L12H").style.display='none'; document.getElementById("L13H").style.display='none'; document.getElementById("L14H").style.display='none'; } function locationchange(lo) { var now=Date.parse(new Date()); if(now-Lastmove<60) { return false; } xmlHttplocation=GetXmlHttpObject() if (xmlHttplocation==null) { alert ("Browser does not support HTTP Request") return } var url="Ajax/Location.php" url=url+"?locationid="+lo url=url+"&sid="+Math.random() //document.write(url); xmlHttplocation.onreadystatechange=stateChangedlocation xmlHttplocation.open("GET",url,true) xmlHttplocation.send(null) } function stateChangedlocation() { //document.write(xmlHttp.readyState); //document.write(xmlHttp.readyState); if (xmlHttplocation.readyState==4 || xmlHttplocation.readyState=="complete") { var newlocation; newlocation= xmlHttplocation.responseText; newlocation=trim(newlocation); locationvalue=newlocation-0; if(locationvalue>0) { Lastmove = Date.parse(new Date()); Showlocation(locationvalue); Movecd(); } } } function trim(str){ //删除左右两端的空格    return str.replace(/(^\s*)|(\s*$)/g, "");    } function ltrim(str){ //删除左边的空格    return str.replace(/(^\s*)/g,"");    } function rtrim(str){ //删除右边的空格    return str.replace(/(\s*$)/g,"");    } function Movecd() { var Nowstamp = Date.parse(new Date()); var Betweenstamp=Nowstamp-Lastmove; var stamp=60000-Betweenstamp stamp=stamp/1000; document.getElementById('Movecd').innerHTML="移动冷却时间<br />"+stamp+" 秒" if(stamp) { t=setTimeout('Movecd()',900) } } function Searchcd() { var Nowstamp = Date.parse(new Date()); var Betweenstamp=Nowstamp-Lastsearch; var stamp=5000-Betweenstamp stamp=stamp/1000; document.getElementById('Searchcd').innerHTML="探索冷却时间<br />"+stamp+" 秒" if(stamp) { t=setTimeout('Searchcd()',900) } }
JavaScript