7 * Contact: Gareth Watts (gareth@splunk.com)
8 * http://omnipotent.net/jquery.sparkline/
10 * Generates inline sparkline charts from data supplied either to the method
13 * Compatible with Internet Explorer 6.0+ and modern browsers equipped with the canvas tag
14 * (Firefox 2.0+, Safari, Opera, etc)
16 * License: New BSD License
18 * Copyright (c) 2012, Splunk Inc.
19 * All rights reserved.
21 * Redistribution and use in source and binary forms, with or without modification,
22 * are permitted provided that the following conditions are met:
24 * * Redistributions of source code must retain the above copyright notice,
25 * this list of conditions and the following disclaimer.
26 * * Redistributions in binary form must reproduce the above copyright notice,
27 * this list of conditions and the following disclaimer in the documentation
28 * and/or other materials provided with the distribution.
29 * * Neither the name of Splunk Inc nor the names of its contributors may
30 * be used to endorse or promote products derived from this software without
31 * specific prior written permission.
33 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
34 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
36 * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
37 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
38 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
40 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
41 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 * $(selector).sparkline(values, options)
47 * If values is undefined or set to 'html' then the data values are read from the specified tag:
48 * <p>Sparkline: <span class="sparkline">1,4,6,6,8,5,3,5</span></p>
49 * $('.sparkline').sparkline();
50 * There must be no spaces in the enclosed data set
52 * Otherwise values must be an array of numbers or null values
53 * <p>Sparkline: <span id="sparkline1">This text replaced if the browser is compatible</span></p>
54 * $('#sparkline1').sparkline([1,4,6,6,8,5,3,5])
55 * $('#sparkline2').sparkline([1,4,6,null,null,5,3,5])
57 * Values can also be specified in an HTML comment, or as a values attribute:
58 * <p>Sparkline: <span class="sparkline"><!--1,4,6,6,8,5,3,5 --></span></p>
59 * <p>Sparkline: <span class="sparkline" values="1,4,6,6,8,5,3,5"></span></p>
60 * $('.sparkline').sparkline();
62 * By default, options should be passed in as teh second argument to the sparkline function:
63 * $('.sparkline').sparkline([1,2,3,4], {type: 'bar'})
65 * Options can also be set by passing them on the tag itself. This feature is disabled by default though
66 * as there's a slight performance overhead:
67 * $('.sparkline').sparkline([1,2,3,4], {enableTagOptions: true})
68 * <p>Sparkline: <span class="sparkline" sparkType="bar" sparkBarColor="red">loading</span></p>
69 * Prefix all options supplied as tag attribute with "spark" (configurable by setting tagOptionPrefix)
72 * lineColor - Color of the line used for the chart
73 * fillColor - Color used to fill in the chart - Set to '' or false for a transparent chart
74 * width - Width of the chart - Defaults to 3 times the number of values in pixels
75 * height - Height of the chart - Defaults to the height of the containing element
76 * chartRangeMin - Specify the minimum value to use for the Y range of the chart - Defaults to the minimum value supplied
77 * chartRangeMax - Specify the maximum value to use for the Y range of the chart - Defaults to the maximum value supplied
78 * chartRangeClip - Clip out of range values to the max/min specified by chartRangeMin and chartRangeMax
79 * chartRangeMinX - Specify the minimum value to use for the X range of the chart - Defaults to the minimum value supplied
80 * chartRangeMaxX - Specify the maximum value to use for the X range of the chart - Defaults to the maximum value supplied
81 * composite - If true then don't erase any existing chart attached to the tag, but draw
82 * another chart over the top - Note that width and height are ignored if an
83 * existing chart is detected.
84 * tagValuesAttribute - Name of tag attribute to check for data values - Defaults to 'values'
85 * enableTagOptions - Whether to check tags for sparkline options
86 * tagOptionPrefix - Prefix used for options supplied as tag attributes - Defaults to 'spark'
87 * disableHiddenCheck - If set to true, then the plugin will assume that charts will never be drawn into a
88 * hidden dom element, avoding a browser reflow
89 * disableInteraction - If set to true then all mouseover/click interaction behaviour will be disabled,
90 * making the plugin perform much like it did in 1.x
91 * disableTooltips - If set to true then tooltips will be disabled - Defaults to false (tooltips enabled)
92 * disableHighlight - If set to true then highlighting of selected chart elements on mouseover will be disabled
93 * defaults to false (highlights enabled)
94 * highlightLighten - Factor to lighten/darken highlighted chart values by - Defaults to 1.4 for a 40% increase
95 * tooltipContainer - Specify which DOM element the tooltip should be rendered into - defaults to document.body
96 * tooltipClassname - Optional CSS classname to apply to tooltips - If not specified then a default style will be applied
97 * tooltipOffsetX - How many pixels away from the mouse pointer to render the tooltip on the X axis
98 * tooltipOffsetY - How many pixels away from the mouse pointer to render the tooltip on the r axis
99 * tooltipFormatter - Optional callback that allows you to override the HTML displayed in the tooltip
100 * callback is given arguments of (sparkline, options, fields)
101 * tooltipChartTitle - If specified then the tooltip uses the string specified by this setting as a title
102 * tooltipFormat - A format string or SPFormat object (or an array thereof for multiple entries)
103 * to control the format of the tooltip
104 * tooltipPrefix - A string to prepend to each field displayed in a tooltip
105 * tooltipSuffix - A string to append to each field displayed in a tooltip
106 * tooltipSkipNull - If true then null values will not have a tooltip displayed (defaults to true)
107 * tooltipValueLookups - An object or range map to map field values to tooltip strings
108 * (eg. to map -1 to "Lost", 0 to "Draw", and 1 to "Win")
109 * numberFormatter - Optional callback for formatting numbers in tooltips
110 * numberDigitGroupSep - Character to use for group separator in numbers "1,234" - Defaults to ","
111 * numberDecimalMark - Character to use for the decimal point when formatting numbers - Defaults to "."
112 * numberDigitGroupCount - Number of digits between group separator - Defaults to 3
114 * There is 1 type of sparkline, selected by supplying a "type" option of 'bar' (default),
116 * bar - Bar chart. Options:
117 * barColor - Color of bars for postive values
118 * negBarColor - Color of bars for negative values
119 * zeroColor - Color of bars with zero values
120 * nullColor - Color of bars with null values - Defaults to omitting the bar entirely
121 * barWidth - Width of bars in pixels
122 * colorMap - Optional mappnig of values to colors to override the *BarColor values above
123 * can be an Array of values to control the color of individual bars or a range map
124 * to specify colors for individual ranges of values
125 * barSpacing - Gap between bars in pixels
126 * zeroAxis - Centers the y-axis around zero if true
134 * $('#sparkline1').sparkline(myvalues, { lineColor: '#f00', fillColor: false });
135 * $('.barsparks').sparkline('html', { type:'bar', height:'40px', barWidth:5 });
138 /*jslint regexp: true, browser: true, jquery: true, white: true, nomen: false, plusplus: false, maxerr: 500, indent: 4 */
140 (function(document, Math, undefined) { // performance/minified-size optimization
142 if(typeof define === 'function' && define.amd) {
143 define(['jquery'], factory);
144 } else if (jQuery && !jQuery.fn.sparkline) {
151 var UNSET_OPTION = {},
152 getDefaults, createClass, SPFormat, clipval, quartile, normalizeValue, normalizeValues,
153 remove, isNumber, all, sum, addCSS, ensureArray, formatNumber, RangeMap,
154 MouseHandler, Tooltip, barHighlightMixin,
155 bar, defaultStyles, initStyles,
156 VShape, VCanvas_base, VCanvas_canvas, VCanvas_vml, pending, shapeCount = 0;
159 * Default configuration settings
161 getDefaults = function () {
163 // Settings common to most/all chart types
168 defaultPixelsPerValue: 3,
172 tagValuesAttribute: 'values',
173 tagOptionsPrefix: 'spark',
174 enableTagOptions: false,
175 enableHighlight: true,
176 highlightLighten: 1.4,
177 tooltipSkipNull: true,
180 disableHiddenCheck: false,
181 numberFormatter: false,
182 numberDigitGroupCount: 3,
183 numberDigitGroupSep: ',',
184 numberDecimalMark: '.',
185 disableTooltips: false,
186 disableInteraction: false
188 // Defaults for bar charts
192 stackedBarColor: ['#3366cc', '#dc3912', '#ff9900', '#109618', '#66aa00',
193 '#dd4477', '#0099c6', '#990099'],
194 zeroColor: undefined,
195 nullColor: undefined,
199 chartRangeMax: undefined,
200 chartRangeMin: undefined,
201 chartRangeClip: false,
203 tooltipFormat: new SPFormat('<span style="color: {{color}}">●</span> {{prefix}}{{value}}{{suffix}}')
208 // You can have tooltips use a css class other than jqstooltip by specifying tooltipClassname
209 defaultStyles = '.jqstooltip { ' +
210 'position: absolute;' +
213 'visibility: hidden;' +
214 'background: rgb(0, 0, 0) transparent;' +
215 'background-color: rgba(0,0,0,0.6);' +
216 'filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);' +
217 '-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";' +
219 'font: 10px arial, san serif;' +
220 'text-align: left;' +
221 'white-space: nowrap;' +
223 'border: 1px solid white;' +
228 'font: 10px arial, san serif;' +
229 'text-align: left;' +
236 createClass = function (/* [baseclass, [mixin, ...]], definition */) {
238 Class = function () {
239 this.init.apply(this, arguments);
241 if (arguments.length > 1) {
243 Class.prototype = $.extend(new arguments[0](), arguments[arguments.length - 1]);
244 Class._super = arguments[0].prototype;
246 Class.prototype = arguments[arguments.length - 1];
248 if (arguments.length > 2) {
249 args = Array.prototype.slice.call(arguments, 1, -1);
250 args.unshift(Class.prototype);
251 $.extend.apply($, args);
254 Class.prototype = arguments[0];
256 Class.prototype.cls = Class;
261 * Wraps a format string for tooltips
266 $.SPFormatClass = SPFormat = createClass({
267 fre: /\{\{([\w.]+?)(:(.+?))?\}\}/g,
268 precre: /(\w+)\.(\d+)/,
270 init: function (format, fclass) {
271 this.format = format;
272 this.fclass = fclass;
275 render: function (fieldset, lookups, options) {
278 match, token, lookupkey, fieldvalue, prec;
279 return this.format.replace(this.fre, function () {
281 token = arguments[1];
282 lookupkey = arguments[3];
283 match = self.precre.exec(token);
290 fieldvalue = fields[token];
291 if (fieldvalue === undefined) {
294 if (lookupkey && lookups && lookups[lookupkey]) {
295 lookup = lookups[lookupkey];
296 if (lookup.get) { // RangeMap
297 return lookups[lookupkey].get(fieldvalue) || fieldvalue;
299 return lookups[lookupkey][fieldvalue] || fieldvalue;
302 if (isNumber(fieldvalue)) {
303 if (options.get('numberFormatter')) {
304 fieldvalue = options.get('numberFormatter')(fieldvalue);
306 fieldvalue = formatNumber(fieldvalue, prec,
307 options.get('numberDigitGroupCount'),
308 options.get('numberDigitGroupSep'),
309 options.get('numberDecimalMark'));
317 // convience method to avoid needing the new operator
318 $.spformat = function(format, fclass) {
319 return new SPFormat(format, fclass);
322 clipval = function (val, min, max) {
332 quartile = function (values, q) {
335 vl = Math.floor(values.length / 2);
336 return values.length % 2 ? values[vl] : (values[vl-1] + values[vl]) / 2;
338 if (values.length % 2 ) { // odd
339 vl = (values.length * q + q) / 4;
340 return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1];
342 vl = (values.length * q + 2) / 4;
343 return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1];
349 normalizeValue = function (val) {
365 nf = parseFloat(val);
373 normalizeValues = function (vals) {
375 for (i = vals.length; i--;) {
376 result[i] = normalizeValue(vals[i]);
381 remove = function (vals, filter) {
382 var i, vl, result = [];
383 for (i = 0, vl = vals.length; i < vl; i++) {
384 if (vals[i] !== filter) {
385 result.push(vals[i]);
391 isNumber = function (num) {
392 return !isNaN(parseFloat(num)) && isFinite(num);
395 formatNumber = function (num, prec, groupsize, groupsep, decsep) {
397 num = (prec === false ? parseFloat(num).toString() : num.toFixed(prec)).split('');
398 p = (p = $.inArray('.', num)) < 0 ? num.length : p;
399 if (p < num.length) {
402 for (i = p - groupsize; i > 0; i -= groupsize) {
403 num.splice(i, 0, groupsep);
408 // determine if all values of an array match a value
409 // returns true if the array is empty
410 all = function (val, arr, ignoreNull) {
412 for (i = arr.length; i--; ) {
413 if (ignoreNull && arr[i] === null) continue;
414 if (arr[i] !== val) {
421 // sums the numeric values in an array, ignoring other values
422 sum = function (vals) {
424 for (i = vals.length; i--;) {
425 total += typeof vals[i] === 'number' ? vals[i] : 0;
430 ensureArray = function (val) {
431 return $.isArray(val) ? val : [val];
434 // http://paulirish.com/2008/bookmarklet-inject-new-css-rules/
435 addCSS = function(css) {
437 //if ('\v' == 'v') /* ie only */ {
438 if (document.createStyleSheet) {
439 document.createStyleSheet().cssText = css;
441 tag = document.createElement('style');
442 tag.type = 'text/css';
443 document.getElementsByTagName('head')[0].appendChild(tag);
444 tag[(typeof document.body.style.WebkitAppearance == 'string') /* webkit only */ ? 'innerText' : 'innerHTML'] = css;
448 // Provide a cross-browser interface to a few simple drawing primitives
449 $.fn.simpledraw = function (width, height, useExisting, interact) {
450 var target, mhandler;
451 if (useExisting && (target = this.data('_jqs_vcanvas'))) {
455 if ($.fn.sparkline.canvas === false) {
456 // We've already determined that neither Canvas nor VML are available
459 } else if ($.fn.sparkline.canvas === undefined) {
460 // No function defined yet -- need to see if we support Canvas or VML
461 var el = document.createElement('canvas');
462 if (!!(el.getContext && el.getContext('2d'))) {
463 // Canvas is available
464 $.fn.sparkline.canvas = function(width, height, target, interact) {
465 return new VCanvas_canvas(width, height, target, interact);
467 } else if (document.namespaces && !document.namespaces.v) {
469 document.namespaces.add('v', 'urn:schemas-microsoft-com:vml', '#default#VML');
470 $.fn.sparkline.canvas = function(width, height, target, interact) {
471 return new VCanvas_vml(width, height, target);
474 // Neither Canvas nor VML are available
475 $.fn.sparkline.canvas = false;
480 if (width === undefined) {
481 width = $(this).innerWidth();
483 if (height === undefined) {
484 height = $(this).innerHeight();
487 target = $.fn.sparkline.canvas(width, height, this, interact);
489 mhandler = $(this).data('_jqs_mhandler');
491 mhandler.registerCanvas(target);
496 $.fn.cleardraw = function () {
497 var target = this.data('_jqs_vcanvas');
503 $.RangeMapClass = RangeMap = createClass({
504 init: function (map) {
505 var key, range, rangelist = [];
507 if (map.hasOwnProperty(key) && typeof key === 'string' && key.indexOf(':') > -1) {
508 range = key.split(':');
509 range[0] = range[0].length === 0 ? -Infinity : parseFloat(range[0]);
510 range[1] = range[1].length === 0 ? Infinity : parseFloat(range[1]);
512 rangelist.push(range);
516 this.rangelist = rangelist || false;
519 get: function (value) {
520 var rangelist = this.rangelist,
522 if ((result = this.map[value]) !== undefined) {
526 for (i = rangelist.length; i--;) {
527 range = rangelist[i];
528 if (range[0] <= value && range[1] >= value) {
537 // Convenience function
538 $.range_map = function(map) {
539 return new RangeMap(map);
542 MouseHandler = createClass({
543 init: function (el, options) {
546 this.options = options;
547 this.currentPageX = 0;
548 this.currentPageY = 0;
553 this.displayTooltips = !options.get('disableTooltips');
554 this.highlightEnabled = !options.get('disableHighlight');
557 registerSparkline: function (sp) {
558 this.splist.push(sp);
560 this.updateDisplay();
564 registerCanvas: function (canvas) {
565 var $canvas = $(canvas.canvas);
566 this.canvas = canvas;
567 this.$canvas = $canvas;
568 $canvas.mouseenter($.proxy(this.mouseenter, this));
569 $canvas.mouseleave($.proxy(this.mouseleave, this));
570 $canvas.click($.proxy(this.mouseclick, this));
573 reset: function (removeTooltip) {
575 if (this.tooltip && removeTooltip) {
576 this.tooltip.remove();
577 this.tooltip = undefined;
581 mouseclick: function (e) {
582 var clickEvent = $.Event('sparklineClick');
583 clickEvent.originalEvent = e;
584 clickEvent.sparklines = this.splist;
585 this.$el.trigger(clickEvent);
588 mouseenter: function (e) {
589 $(document.body).unbind('mousemove.jqs');
590 $(document.body).bind('mousemove.jqs', $.proxy(this.mousemove, this));
592 this.currentPageX = e.pageX;
593 this.currentPageY = e.pageY;
594 this.currentEl = e.target;
595 if (!this.tooltip && this.displayTooltips) {
596 this.tooltip = new Tooltip(this.options);
597 this.tooltip.updatePosition(e.pageX, e.pageY);
599 this.updateDisplay();
602 mouseleave: function () {
603 $(document.body).unbind('mousemove.jqs');
604 var splist = this.splist,
605 spcount = splist.length,
606 needsRefresh = false,
609 this.currentEl = null;
612 this.tooltip.remove();
616 for (i = 0; i < spcount; i++) {
618 if (sp.clearRegionHighlight()) {
624 this.canvas.render();
628 mousemove: function (e) {
629 this.currentPageX = e.pageX;
630 this.currentPageY = e.pageY;
631 this.currentEl = e.target;
633 this.tooltip.updatePosition(e.pageX, e.pageY);
635 this.updateDisplay();
638 updateDisplay: function () {
639 var splist = this.splist,
640 spcount = splist.length,
641 needsRefresh = false,
642 offset = this.$canvas.offset(),
643 localX = this.currentPageX - offset.left,
644 localY = this.currentPageY - offset.top,
645 tooltiphtml, sp, i, result, changeEvent;
649 for (i = 0; i < spcount; i++) {
651 result = sp.setRegionHighlight(this.currentEl, localX, localY);
657 changeEvent = $.Event('sparklineRegionChange');
658 changeEvent.sparklines = this.splist;
659 this.$el.trigger(changeEvent);
662 for (i = 0; i < spcount; i++) {
664 tooltiphtml += sp.getCurrentRegionTooltip();
666 this.tooltip.setContent(tooltiphtml);
668 if (!this.disableHighlight) {
669 this.canvas.render();
672 if (result === null) {
679 Tooltip = createClass({
680 sizeStyle: 'position: static !important;' +
681 'display: block !important;' +
682 'visibility: hidden !important;' +
683 'float: left !important;',
685 init: function (options) {
686 var tooltipClassname = options.get('tooltipClassname', 'jqstooltip'),
687 sizetipStyle = this.sizeStyle,
689 this.container = options.get('tooltipContainer') || document.body;
690 this.tooltipOffsetX = options.get('tooltipOffsetX', 10);
691 this.tooltipOffsetY = options.get('tooltipOffsetY', 12);
692 // remove any previous lingering tooltip
693 $('#jqssizetip').remove();
694 $('#jqstooltip').remove();
695 this.sizetip = $('<div/>', {
698 'class': tooltipClassname
700 this.tooltip = $('<div/>', {
702 'class': tooltipClassname
703 }).appendTo(this.container);
704 // account for the container's location
705 offset = this.tooltip.offset();
706 this.offsetLeft = offset.left;
707 this.offsetTop = offset.top;
709 $(window).unbind('resize.jqs scroll.jqs');
710 $(window).bind('resize.jqs scroll.jqs', $.proxy(this.updateWindowDims, this));
711 this.updateWindowDims();
714 updateWindowDims: function () {
715 this.scrollTop = $(window).scrollTop();
716 this.scrollLeft = $(window).scrollLeft();
717 this.scrollRight = this.scrollLeft + $(window).width();
718 this.updatePosition();
721 getSize: function (content) {
722 this.sizetip.html(content).appendTo(this.container);
723 this.width = this.sizetip.width() + 1;
724 this.height = this.sizetip.height();
725 this.sizetip.remove();
728 setContent: function (content) {
730 this.tooltip.css('visibility', 'hidden');
734 this.getSize(content);
735 this.tooltip.html(content)
738 'height': this.height,
739 'visibility': 'visible'
743 this.updatePosition();
747 updatePosition: function (x, y) {
748 if (x === undefined) {
749 if (this.mousex === undefined) {
752 x = this.mousex - this.offsetLeft;
753 y = this.mousey - this.offsetTop;
756 this.mousex = x = x - this.offsetLeft;
757 this.mousey = y = y - this.offsetTop;
759 if (!this.height || !this.width || this.hidden) {
763 y -= this.height + this.tooltipOffsetY;
764 x += this.tooltipOffsetX;
766 if (y < this.scrollTop) {
769 if (x < this.scrollLeft) {
771 } else if (x + this.width > this.scrollRight) {
772 x = this.scrollRight - this.width;
781 remove: function () {
782 this.tooltip.remove();
783 this.sizetip.remove();
784 this.sizetip = this.tooltip = undefined;
785 $(window).unbind('resize.jqs scroll.jqs');
789 initStyles = function() {
790 addCSS(defaultStyles);
796 $.fn.sparkline = function (userValues, userOptions) {
797 return this.each(function () {
798 var options = new $.fn.sparkline.options(this, userOptions),
801 render = function () {
802 var values, width, height, tmp, mhandler, sp, vals;
803 if (userValues === 'html' || userValues === undefined) {
804 vals = this.getAttribute(options.get('tagValuesAttribute'));
805 if (vals === undefined || vals === null) {
808 values = vals.replace(/(^\s*<!--)|(-->\s*$)|\s+/g, '').split(',');
813 width = options.get('width') === 'auto' ? values.length * options.get('defaultPixelsPerValue') : options.get('width');
814 if (options.get('height') === 'auto') {
815 if (!options.get('composite') || !$.data(this, '_jqs_vcanvas')) {
816 // must be a better way to get the line height
817 tmp = document.createElement('span');
820 height = $(tmp).innerHeight() || $(tmp).height();
825 height = options.get('height');
828 if (!options.get('disableInteraction')) {
829 mhandler = $.data(this, '_jqs_mhandler');
831 mhandler = new MouseHandler(this, options);
832 $.data(this, '_jqs_mhandler', mhandler);
833 } else if (!options.get('composite')) {
840 if (options.get('composite') && !$.data(this, '_jqs_vcanvas')) {
841 if (!$.data(this, '_jqs_errnotify')) {
842 alert('Attempted to attach a composite sparkline to an element with no existing sparkline');
843 $.data(this, '_jqs_errnotify', true);
848 sp = new $.fn.sparkline[options.get('type')](this, values, options, width, height);
853 mhandler.registerSparkline(sp);
856 if (($(this).html() && !options.get('disableHiddenCheck') && $(this).is(':hidden')) || !$(this).parents('body').length) {
857 if (!options.get('composite') && $.data(this, '_jqs_pending')) {
858 // remove any existing references to the element
859 for (i = pending.length; i; i--) {
860 if (pending[i - 1][0] == this) {
861 pending.splice(i - 1, 1);
865 pending.push([this, render]);
866 $.data(this, '_jqs_pending', true);
873 $.fn.sparkline.defaults = getDefaults();
876 $.sparkline_display_visible = function () {
879 for (i = 0, pl = pending.length; i < pl; i++) {
881 if ($(el).is(':visible') && !$(el).parents().is(':hidden')) {
882 pending[i][1].call(el);
883 $.data(pending[i][0], '_jqs_pending', false);
885 } else if (!$(el).closest('html').length && !$.data(el, '_jqs_pending')) {
886 // element has been inserted and removed from the DOM
887 // If it was not yet inserted into the dom then the .data request
889 // removing from the dom causes the data to be removed.
890 $.data(pending[i][0], '_jqs_pending', false);
894 for (i = done.length; i; i--) {
895 pending.splice(done[i - 1], 1);
901 * User option handler
903 $.fn.sparkline.options = createClass({
904 init: function (tag, userOptions) {
905 var extendedOptions, defaults, base, tagOptionType;
906 this.userOptions = userOptions = userOptions || {};
908 this.tagValCache = {};
909 defaults = $.fn.sparkline.defaults;
910 base = defaults.common;
911 this.tagOptionsPrefix = userOptions.enableTagOptions && (userOptions.tagOptionsPrefix || base.tagOptionsPrefix);
913 tagOptionType = this.getTagSetting('type');
914 if (tagOptionType === UNSET_OPTION) {
915 extendedOptions = defaults[userOptions.type || base.type];
917 extendedOptions = defaults[tagOptionType];
919 this.mergedOptions = $.extend({}, base, extendedOptions, userOptions);
923 getTagSetting: function (key) {
924 var prefix = this.tagOptionsPrefix,
925 val, i, pairs, keyval;
926 if (prefix === false || prefix === undefined) {
929 if (this.tagValCache.hasOwnProperty(key)) {
930 val = this.tagValCache.key;
932 val = this.tag.getAttribute(prefix + key);
933 if (val === undefined || val === null) {
935 } else if (val.substr(0, 1) === '[') {
936 val = val.substr(1, val.length - 2).split(',');
937 for (i = val.length; i--;) {
938 val[i] = normalizeValue(val[i].replace(/(^\s*)|(\s*$)/g, ''));
940 } else if (val.substr(0, 1) === '{') {
941 pairs = val.substr(1, val.length - 2).split(',');
943 for (i = pairs.length; i--;) {
944 keyval = pairs[i].split(':', 2);
945 val[keyval[0].replace(/(^\s*)|(\s*$)/g, '')] = normalizeValue(keyval[1].replace(/(^\s*)|(\s*$)/g, ''));
948 val = normalizeValue(val);
950 this.tagValCache.key = val;
955 get: function (key, defaultval) {
956 var tagOption = this.getTagSetting(key),
958 if (tagOption !== UNSET_OPTION) {
961 return (result = this.mergedOptions[key]) === undefined ? defaultval : result;
966 $.fn.sparkline._base = createClass({
969 init: function (el, values, options, width, height) {
972 this.values = values;
973 this.options = options;
975 this.height = height;
976 this.currentRegion = undefined;
982 initTarget: function () {
983 var interactive = !this.options.get('disableInteraction');
984 if (!(this.target = this.$el.simpledraw(this.width, this.height, this.options.get('composite'), interactive))) {
985 this.disabled = true;
987 this.canvasWidth = this.target.pixelWidth;
988 this.canvasHeight = this.target.pixelHeight;
993 * Actually render the chart to the canvas
995 render: function () {
997 this.el.innerHTML = '';
1004 * Return a region id for a given x/y co-ordinate
1006 getRegion: function (x, y) {
1010 * Highlight an item based on the moused-over x,y co-ordinate
1012 setRegionHighlight: function (el, x, y) {
1013 var currentRegion = this.currentRegion,
1014 highlightEnabled = !this.options.get('disableHighlight'),
1016 if (x > this.canvasWidth || y > this.canvasHeight || x < 0 || y < 0) {
1019 newRegion = this.getRegion(el, x, y);
1020 if (currentRegion !== newRegion) {
1021 if (currentRegion !== undefined && highlightEnabled) {
1022 this.removeHighlight();
1024 this.currentRegion = newRegion;
1025 if (newRegion !== undefined && highlightEnabled) {
1026 this.renderHighlight();
1034 * Reset any currently highlighted item
1036 clearRegionHighlight: function () {
1037 if (this.currentRegion !== undefined) {
1038 this.removeHighlight();
1039 this.currentRegion = undefined;
1045 renderHighlight: function () {
1046 this.changeHighlight(true);
1049 removeHighlight: function () {
1050 this.changeHighlight(false);
1053 changeHighlight: function (highlight) {},
1056 * Fetch the HTML to display as a tooltip
1058 getCurrentRegionTooltip: function () {
1059 var options = this.options,
1062 fields, formats, formatlen, fclass, text, i,
1063 showFields, showFieldsKey, newFields, fv,
1064 formatter, format, fieldlen, j;
1065 if (this.currentRegion === undefined) {
1068 fields = this.getCurrentRegionFields();
1069 formatter = options.get('tooltipFormatter');
1071 return formatter(this, options, fields);
1073 if (options.get('tooltipChartTitle')) {
1074 header += '<div class="jqs jqstitle">' + options.get('tooltipChartTitle') + '</div>\n';
1076 formats = this.options.get('tooltipFormat');
1080 if (!$.isArray(formats)) {
1081 formats = [formats];
1083 if (!$.isArray(fields)) {
1086 showFields = this.options.get('tooltipFormatFieldlist');
1087 showFieldsKey = this.options.get('tooltipFormatFieldlistKey');
1088 if (showFields && showFieldsKey) {
1089 // user-selected ordering of fields
1091 for (i = fields.length; i--;) {
1092 fv = fields[i][showFieldsKey];
1093 if ((j = $.inArray(fv, showFields)) != -1) {
1094 newFields[j] = fields[i];
1099 formatlen = formats.length;
1100 fieldlen = fields.length;
1101 for (i = 0; i < formatlen; i++) {
1102 format = formats[i];
1103 if (typeof format === 'string') {
1104 format = new SPFormat(format);
1106 fclass = format.fclass || 'jqsfield';
1107 for (j = 0; j < fieldlen; j++) {
1108 if (!fields[j].isNull || !options.get('tooltipSkipNull')) {
1109 $.extend(fields[j], {
1110 prefix: options.get('tooltipPrefix'),
1111 suffix: options.get('tooltipSuffix')
1113 text = format.render(fields[j], options.get('tooltipValueLookups'), options);
1114 entries.push('<div class="' + fclass + '">' + text + '</div>');
1118 if (entries.length) {
1119 return header + entries.join('\n');
1124 getCurrentRegionFields: function () {},
1126 calcHighlightColor: function (color, options) {
1127 var highlightColor = options.get('highlightColor'),
1128 lighten = options.get('highlightLighten'),
1129 parse, mult, rgbnew, i;
1130 if (highlightColor) {
1131 return highlightColor;
1134 // extract RGB values
1135 parse = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(color) || /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color);
1138 mult = color.length === 4 ? 16 : 1;
1139 for (i = 0; i < 3; i++) {
1140 rgbnew[i] = clipval(Math.round(parseInt(parse[i + 1], 16) * mult * lighten), 0, 255);
1142 return 'rgb(' + rgbnew.join(',') + ')';
1151 barHighlightMixin = {
1152 changeHighlight: function (highlight) {
1153 var currentRegion = this.currentRegion,
1154 target = this.target,
1155 shapeids = this.regionShapes[currentRegion],
1157 // will be null if the region value was null
1159 newShapes = this.renderRegion(currentRegion, highlight);
1160 if ($.isArray(newShapes) || $.isArray(shapeids)) {
1161 target.replaceWithShapes(shapeids, newShapes);
1162 this.regionShapes[currentRegion] = $.map(newShapes, function (newShape) {
1166 target.replaceWithShape(shapeids, newShapes);
1167 this.regionShapes[currentRegion] = newShapes.id;
1172 render: function () {
1173 var values = this.values,
1174 target = this.target,
1175 regionShapes = this.regionShapes,
1178 if (!this.cls._super.render.call(this)) {
1181 for (i = values.length; i--;) {
1182 shapes = this.renderRegion(i);
1184 if ($.isArray(shapes)) {
1186 for (j = shapes.length; j--;) {
1188 ids.push(shapes[j].id);
1190 regionShapes[i] = ids;
1193 regionShapes[i] = shapes.id; // store just the shapeid
1197 regionShapes[i] = null;
1207 $.fn.sparkline.bar = bar = createClass($.fn.sparkline._base, barHighlightMixin, {
1210 init: function (el, values, options, width, height) {
1211 var barWidth = parseInt(options.get('barWidth'), 10),
1212 barSpacing = parseInt(options.get('barSpacing'), 10),
1213 chartRangeMin = options.get('chartRangeMin'),
1214 chartRangeMax = options.get('chartRangeMax'),
1215 chartRangeClip = options.get('chartRangeClip'),
1216 stackMin = Infinity,
1217 stackMax = -Infinity,
1218 isStackString, groupMin, groupMax, stackRanges,
1219 numValues, i, vlen, range, zeroAxis, xaxisOffset, min, max, clipMin, clipMax,
1220 stacked, vlist, j, slen, svals, val, yoffset, yMaxCalc, canvasHeightEf;
1221 bar._super.init.call(this, el, values, options, width, height);
1223 // scan values to determine whether to stack bars
1224 for (i = 0, vlen = values.length; i < vlen; i++) {
1226 isStackString = typeof(val) === 'string' && val.indexOf(':') > -1;
1227 if (isStackString || $.isArray(val)) {
1229 if (isStackString) {
1230 val = values[i] = normalizeValues(val.split(':'));
1232 val = remove(val, null); // min/max will treat null as zero
1233 groupMin = Math.min.apply(Math, val);
1234 groupMax = Math.max.apply(Math, val);
1235 if (groupMin < stackMin) {
1236 stackMin = groupMin;
1238 if (groupMax > stackMax) {
1239 stackMax = groupMax;
1244 this.stacked = stacked;
1245 this.regionShapes = {};
1246 this.barWidth = barWidth;
1247 this.barSpacing = barSpacing;
1248 this.totalBarWidth = barWidth + barSpacing;
1249 this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing);
1253 if (chartRangeClip) {
1254 clipMin = chartRangeMin === undefined ? -Infinity : chartRangeMin;
1255 clipMax = chartRangeMax === undefined ? Infinity : chartRangeMax;
1259 stackRanges = stacked ? [] : numValues;
1260 var stackTotals = [];
1261 var stackRangesNeg = [];
1262 for (i = 0, vlen = values.length; i < vlen; i++) {
1265 values[i] = svals = [];
1267 stackRanges[i] = stackRangesNeg[i] = 0;
1268 for (j = 0, slen = vlist.length; j < slen; j++) {
1269 val = svals[j] = chartRangeClip ? clipval(vlist[j], clipMin, clipMax) : vlist[j];
1272 stackTotals[i] += val;
1274 if (stackMin < 0 && stackMax > 0) {
1276 stackRangesNeg[i] += Math.abs(val);
1278 stackRanges[i] += val;
1281 stackRanges[i] += Math.abs(val - (val < 0 ? stackMax : stackMin));
1283 numValues.push(val);
1287 val = chartRangeClip ? clipval(values[i], clipMin, clipMax) : values[i];
1288 val = values[i] = normalizeValue(val);
1290 numValues.push(val);
1294 this.max = max = Math.max.apply(Math, numValues);
1295 this.min = min = Math.min.apply(Math, numValues);
1296 this.stackMax = stackMax = stacked ? Math.max.apply(Math, stackTotals) : max;
1297 this.stackMin = stackMin = stacked ? Math.min.apply(Math, numValues) : min;
1299 if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < min)) {
1300 min = options.get('chartRangeMin');
1302 if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > max)) {
1303 max = options.get('chartRangeMax');
1306 this.zeroAxis = zeroAxis = options.get('zeroAxis', true);
1307 if (min <= 0 && max >= 0 && zeroAxis) {
1309 } else if (zeroAxis == false) {
1311 } else if (min > 0) {
1316 this.xaxisOffset = xaxisOffset;
1318 range = stacked ? (Math.max.apply(Math, stackRanges) + Math.max.apply(Math, stackRangesNeg)) : max - min;
1320 // as we plot zero/min values a single pixel line, we add a pixel to all other
1321 // values - Reduce the effective canvas size to suit
1322 this.canvasHeightEf = (zeroAxis && min < 0) ? this.canvasHeight - 2 : this.canvasHeight - 1;
1324 if (min < xaxisOffset) {
1325 yMaxCalc = (stacked && max >= 0) ? stackMax : max;
1326 yoffset = (yMaxCalc - xaxisOffset) / range * this.canvasHeight;
1327 if (yoffset !== Math.ceil(yoffset)) {
1328 this.canvasHeightEf -= 2;
1329 yoffset = Math.ceil(yoffset);
1332 yoffset = this.canvasHeight;
1334 this.yoffset = yoffset;
1336 if ($.isArray(options.get('colorMap'))) {
1337 this.colorMapByIndex = options.get('colorMap');
1338 this.colorMapByValue = null;
1340 this.colorMapByIndex = null;
1341 this.colorMapByValue = options.get('colorMap');
1342 if (this.colorMapByValue && this.colorMapByValue.get === undefined) {
1343 this.colorMapByValue = new RangeMap(this.colorMapByValue);
1350 getRegion: function (el, x, y) {
1351 var result = Math.floor(x / this.totalBarWidth);
1352 return (result < 0 || result >= this.values.length) ? undefined : result;
1355 getCurrentRegionFields: function () {
1356 var currentRegion = this.currentRegion,
1357 values = ensureArray(this.values[currentRegion]),
1360 for (i = values.length; i--;) {
1363 isNull: value === null,
1365 color: this.calcColor(i, value, currentRegion),
1366 offset: currentRegion
1372 calcColor: function (stacknum, value, valuenum) {
1373 var colorMapByIndex = this.colorMapByIndex,
1374 colorMapByValue = this.colorMapByValue,
1375 options = this.options,
1378 color = options.get('stackedBarColor');
1380 color = (value < 0) ? options.get('negBarColor') : options.get('barColor');
1382 if (value === 0 && options.get('zeroColor') !== undefined) {
1383 color = options.get('zeroColor');
1385 if (colorMapByValue && (newColor = colorMapByValue.get(value))) {
1387 } else if (colorMapByIndex && colorMapByIndex.length > valuenum) {
1388 color = colorMapByIndex[valuenum];
1390 return $.isArray(color) ? color[stacknum % color.length] : color;
1394 * Render bar(s) for a region
1396 renderRegion: function (valuenum, highlight) {
1397 var vals = this.values[valuenum],
1398 options = this.options,
1399 xaxisOffset = this.xaxisOffset,
1402 stacked = this.stacked,
1403 target = this.target,
1404 x = valuenum * this.totalBarWidth,
1405 canvasHeightEf = this.canvasHeightEf,
1406 yoffset = this.yoffset,
1407 y, height, color, isNull, yoffsetNeg, i, valcount, val, minPlotted, allMin;
1409 vals = $.isArray(vals) ? vals : [vals];
1410 valcount = vals.length;
1412 isNull = all(null, vals);
1413 allMin = all(xaxisOffset, vals, true);
1416 if (options.get('nullColor')) {
1417 color = highlight ? options.get('nullColor') : this.calcHighlightColor(options.get('nullColor'), options);
1418 y = (yoffset > 0) ? yoffset - 1 : yoffset;
1419 return target.drawRect(x, y, this.barWidth - 1, 0, color, color);
1424 yoffsetNeg = yoffset;
1425 for (i = 0; i < valcount; i++) {
1428 if (stacked && val === xaxisOffset) {
1429 if (!allMin || minPlotted) {
1436 height = Math.floor(canvasHeightEf * ((Math.abs(val - xaxisOffset) / range))) + 1;
1440 if (val < xaxisOffset || (val === xaxisOffset && yoffset === 0)) {
1442 yoffsetNeg += height;
1444 y = yoffset - height;
1447 color = this.calcColor(i, val, valuenum);
1449 color = this.calcHighlightColor(color, options);
1451 result.push(target.drawRect(x, y, this.barWidth - 1, height - 1, color, color));
1453 if (result.length === 1) {
1460 // Setup a very simple "virtual canvas" to make drawing the few shapes we need easier
1461 // This is accessible as $(foo).simpledraw()
1463 VShape = createClass({
1464 init: function (target, id, type, args) {
1465 this.target = target;
1470 append: function () {
1471 this.target.appendShape(this);
1476 VCanvas_base = createClass({
1477 _pxregex: /(\d+)(px)?\s*$/i,
1479 init: function (width, height, target) {
1484 this.height = height;
1485 this.target = target;
1486 this.lastShapeId = null;
1490 $.data(target, '_jqs_vcanvas', this);
1493 drawLine: function (x1, y1, x2, y2, lineColor, lineWidth) {
1494 return this.drawShape([[x1, y1], [x2, y2]], lineColor, lineWidth);
1497 drawShape: function (path, lineColor, fillColor, lineWidth) {
1498 return this._genShape('Shape', [path, lineColor, fillColor, lineWidth]);
1501 drawCircle: function (x, y, radius, lineColor, fillColor, lineWidth) {
1502 return this._genShape('Circle', [x, y, radius, lineColor, fillColor, lineWidth]);
1505 drawPieSlice: function (x, y, radius, startAngle, endAngle, lineColor, fillColor) {
1506 return this._genShape('PieSlice', [x, y, radius, startAngle, endAngle, lineColor, fillColor]);
1509 drawRect: function (x, y, width, height, lineColor, fillColor) {
1510 return this._genShape('Rect', [x, y, width, height, lineColor, fillColor]);
1513 getElement: function () {
1518 * Return the most recently inserted shape id
1520 getLastShapeId: function () {
1521 return this.lastShapeId;
1525 * Clear and reset the canvas
1527 reset: function () {
1528 alert('reset not implemented');
1531 _insert: function (el, target) {
1536 * Calculate the pixel dimensions of the canvas
1538 _calculatePixelDims: function (width, height, canvas) {
1539 // XXX This should probably be a configurable option
1541 match = this._pxregex.exec(height);
1543 this.pixelHeight = match[1];
1545 this.pixelHeight = $(canvas).height();
1547 match = this._pxregex.exec(width);
1549 this.pixelWidth = match[1];
1551 this.pixelWidth = $(canvas).width();
1556 * Generate a shape object and id for later rendering
1558 _genShape: function (shapetype, shapeargs) {
1559 var id = shapeCount++;
1560 shapeargs.unshift(id);
1561 return new VShape(this, id, shapetype, shapeargs);
1565 * Add a shape to the end of the render queue
1567 appendShape: function (shape) {
1568 alert('appendShape not implemented');
1572 * Replace one shape with another
1574 replaceWithShape: function (shapeid, shape) {
1575 alert('replaceWithShape not implemented');
1579 * Insert one shape after another in the render queue
1581 insertAfterShape: function (shapeid, shape) {
1582 alert('insertAfterShape not implemented');
1586 * Remove a shape from the queue
1588 removeShapeId: function (shapeid) {
1589 alert('removeShapeId not implemented');
1593 * Find a shape at the specified x/y co-ordinates
1595 getShapeAt: function (el, x, y) {
1596 alert('getShapeAt not implemented');
1600 * Render all queued shapes onto the canvas
1602 render: function () {
1603 alert('render not implemented');
1607 VCanvas_canvas = createClass(VCanvas_base, {
1608 init: function (width, height, target, interact) {
1609 VCanvas_canvas._super.init.call(this, width, height, target);
1610 this.canvas = document.createElement('canvas');
1614 $.data(target, '_jqs_vcanvas', this);
1615 $(this.canvas).css({ display: 'inline-block', width: width, height: height, verticalAlign: 'top' });
1616 this._insert(this.canvas, target);
1617 this._calculatePixelDims(width, height, this.canvas);
1618 this.canvas.width = this.pixelWidth;
1619 this.canvas.height = this.pixelHeight;
1620 this.interact = interact;
1623 this.currentTargetShapeId = undefined;
1624 $(this.canvas).css({width: this.pixelWidth, height: this.pixelHeight});
1627 _getContext: function (lineColor, fillColor, lineWidth) {
1628 var context = this.canvas.getContext('2d');
1629 if (lineColor !== undefined) {
1630 context.strokeStyle = lineColor;
1632 context.lineWidth = lineWidth === undefined ? 1 : lineWidth;
1633 if (fillColor !== undefined) {
1634 context.fillStyle = fillColor;
1639 reset: function () {
1640 var context = this._getContext();
1641 context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
1644 this.currentTargetShapeId = undefined;
1647 _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) {
1648 var context = this._getContext(lineColor, fillColor, lineWidth),
1650 context.beginPath();
1651 context.moveTo(path[0][0] + 0.5, path[0][1] + 0.5);
1652 for (i = 1, plen = path.length; i < plen; i++) {
1653 context.lineTo(path[i][0] + 0.5, path[i][1] + 0.5); // the 0.5 offset gives us crisp pixel-width lines
1655 if (lineColor !== undefined) {
1658 if (fillColor !== undefined) {
1661 if (this.targetX !== undefined && this.targetY !== undefined &&
1662 context.isPointInPath(this.targetX, this.targetY)) {
1663 this.currentTargetShapeId = shapeid;
1667 _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) {
1668 var context = this._getContext(lineColor, fillColor, lineWidth);
1669 context.beginPath();
1670 context.arc(x, y, radius, 0, 2 * Math.PI, false);
1671 if (this.targetX !== undefined && this.targetY !== undefined &&
1672 context.isPointInPath(this.targetX, this.targetY)) {
1673 this.currentTargetShapeId = shapeid;
1675 if (lineColor !== undefined) {
1678 if (fillColor !== undefined) {
1683 _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) {
1684 var context = this._getContext(lineColor, fillColor);
1685 context.beginPath();
1686 context.moveTo(x, y);
1687 context.arc(x, y, radius, startAngle, endAngle, false);
1688 context.lineTo(x, y);
1689 context.closePath();
1690 if (lineColor !== undefined) {
1696 if (this.targetX !== undefined && this.targetY !== undefined &&
1697 context.isPointInPath(this.targetX, this.targetY)) {
1698 this.currentTargetShapeId = shapeid;
1702 _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) {
1703 return this._drawShape(shapeid, [[x, y], [x + width, y], [x + width, y + height], [x, y + height], [x, y]], lineColor, fillColor);
1706 appendShape: function (shape) {
1707 this.shapes[shape.id] = shape;
1708 this.shapeseq.push(shape.id);
1709 this.lastShapeId = shape.id;
1713 replaceWithShape: function (shapeid, shape) {
1714 var shapeseq = this.shapeseq,
1716 this.shapes[shape.id] = shape;
1717 for (i = shapeseq.length; i--;) {
1718 if (shapeseq[i] == shapeid) {
1719 shapeseq[i] = shape.id;
1722 delete this.shapes[shapeid];
1725 replaceWithShapes: function (shapeids, shapes) {
1726 var shapeseq = this.shapeseq,
1730 for (i = shapeids.length; i--;) {
1731 shapemap[shapeids[i]] = true;
1733 for (i = shapeseq.length; i--;) {
1735 if (shapemap[sid]) {
1736 shapeseq.splice(i, 1);
1737 delete this.shapes[sid];
1741 for (i = shapes.length; i--;) {
1742 shapeseq.splice(first, 0, shapes[i].id);
1743 this.shapes[shapes[i].id] = shapes[i];
1748 insertAfterShape: function (shapeid, shape) {
1749 var shapeseq = this.shapeseq,
1751 for (i = shapeseq.length; i--;) {
1752 if (shapeseq[i] === shapeid) {
1753 shapeseq.splice(i + 1, 0, shape.id);
1754 this.shapes[shape.id] = shape;
1760 removeShapeId: function (shapeid) {
1761 var shapeseq = this.shapeseq,
1763 for (i = shapeseq.length; i--;) {
1764 if (shapeseq[i] === shapeid) {
1765 shapeseq.splice(i, 1);
1769 delete this.shapes[shapeid];
1772 getShapeAt: function (el, x, y) {
1776 return this.currentTargetShapeId;
1779 render: function () {
1780 var shapeseq = this.shapeseq,
1781 shapes = this.shapes,
1782 shapeCount = shapeseq.length,
1783 context = this._getContext(),
1785 context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
1786 for (i = 0; i < shapeCount; i++) {
1787 shapeid = shapeseq[i];
1788 shape = shapes[shapeid];
1789 this['_draw' + shape.type].apply(this, shape.args);
1791 if (!this.interact) {
1792 // not interactive so no need to keep the shapes array
1800 VCanvas_vml = createClass(VCanvas_base, {
1801 init: function (width, height, target) {
1803 VCanvas_vml._super.init.call(this, width, height, target);
1807 $.data(target, '_jqs_vcanvas', this);
1808 this.canvas = document.createElement('span');
1809 $(this.canvas).css({ display: 'inline-block', position: 'relative', overflow: 'hidden', width: width, height: height, margin: '0px', padding: '0px', verticalAlign: 'top'});
1810 this._insert(this.canvas, target);
1811 this._calculatePixelDims(width, height, this.canvas);
1812 this.canvas.width = this.pixelWidth;
1813 this.canvas.height = this.pixelHeight;
1814 groupel = '<v:group coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '"' +
1815 ' style="position:absolute;top:0;left:0;width:' + this.pixelWidth + 'px;height=' + this.pixelHeight + 'px;"></v:group>';
1816 this.canvas.insertAdjacentHTML('beforeEnd', groupel);
1817 this.group = $(this.canvas).children()[0];
1818 this.rendered = false;
1819 this.prerender = '';
1822 _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) {
1824 initial, stroke, fill, closed, vel, plen, i;
1825 for (i = 0, plen = path.length; i < plen; i++) {
1826 vpath[i] = '' + (path[i][0]) + ',' + (path[i][1]);
1828 initial = vpath.splice(0, 1);
1829 lineWidth = lineWidth === undefined ? 1 : lineWidth;
1830 stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" ';
1831 fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
1832 closed = vpath[0] === vpath[vpath.length - 1] ? 'x ' : '';
1833 vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' +
1834 ' id="jqsshape' + shapeid + '" ' +
1837 ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' +
1838 ' path="m ' + initial + ' l ' + vpath.join(', ') + ' ' + closed + 'e">' +
1843 _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) {
1844 var stroke, fill, vel;
1847 stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" ';
1848 fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
1850 ' id="jqsshape' + shapeid + '" ' +
1853 ' style="position:absolute;top:' + y + 'px; left:' + x + 'px; width:' + (radius * 2) + 'px; height:' + (radius * 2) + 'px"></v:oval>';
1858 _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) {
1859 var vpath, startx, starty, endx, endy, stroke, fill, vel;
1860 if (startAngle === endAngle) {
1861 return ''; // VML seems to have problem when start angle equals end angle.
1863 if ((endAngle - startAngle) === (2 * Math.PI)) {
1864 startAngle = 0.0; // VML seems to have a problem when drawing a full circle that doesn't start 0
1865 endAngle = (2 * Math.PI);
1868 startx = x + Math.round(Math.cos(startAngle) * radius);
1869 starty = y + Math.round(Math.sin(startAngle) * radius);
1870 endx = x + Math.round(Math.cos(endAngle) * radius);
1871 endy = y + Math.round(Math.sin(endAngle) * radius);
1873 if (startx === endx && starty === endy) {
1874 if ((endAngle - startAngle) < Math.PI) {
1875 // Prevent very small slices from being mistaken as a whole pie
1878 // essentially going to be the entire circle, so ignore startAngle
1879 startx = endx = x + radius;
1883 if (startx === endx && starty === endy && (endAngle - startAngle) < Math.PI) {
1887 vpath = [x - radius, y - radius, x + radius, y + radius, startx, starty, endx, endy];
1888 stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="1px" strokeColor="' + lineColor + '" ';
1889 fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
1890 vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' +
1891 ' id="jqsshape' + shapeid + '" ' +
1894 ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' +
1895 ' path="m ' + x + ',' + y + ' wa ' + vpath.join(', ') + ' x e">' +
1900 _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) {
1901 return this._drawShape(shapeid, [[x, y], [x, y + height], [x + width, y + height], [x + width, y], [x, y]], lineColor, fillColor);
1904 reset: function () {
1905 this.group.innerHTML = '';
1908 appendShape: function (shape) {
1909 var vel = this['_draw' + shape.type].apply(this, shape.args);
1910 if (this.rendered) {
1911 this.group.insertAdjacentHTML('beforeEnd', vel);
1913 this.prerender += vel;
1915 this.lastShapeId = shape.id;
1919 replaceWithShape: function (shapeid, shape) {
1920 var existing = $('#jqsshape' + shapeid),
1921 vel = this['_draw' + shape.type].apply(this, shape.args);
1922 existing[0].outerHTML = vel;
1925 replaceWithShapes: function (shapeids, shapes) {
1926 // replace the first shapeid with all the new shapes then toast the remaining old shapes
1927 var existing = $('#jqsshape' + shapeids[0]),
1929 slen = shapes.length,
1931 for (i = 0; i < slen; i++) {
1932 replace += this['_draw' + shapes[i].type].apply(this, shapes[i].args);
1934 existing[0].outerHTML = replace;
1935 for (i = 1; i < shapeids.length; i++) {
1936 $('#jqsshape' + shapeids[i]).remove();
1940 insertAfterShape: function (shapeid, shape) {
1941 var existing = $('#jqsshape' + shapeid),
1942 vel = this['_draw' + shape.type].apply(this, shape.args);
1943 existing[0].insertAdjacentHTML('afterEnd', vel);
1946 removeShapeId: function (shapeid) {
1947 var existing = $('#jqsshape' + shapeid);
1948 this.group.removeChild(existing[0]);
1951 getShapeAt: function (el, x, y) {
1952 var shapeid = el.id.substr(8);
1956 render: function () {
1957 if (!this.rendered) {
1958 // batch the intial render into a single repaint
1959 this.group.innerHTML = this.prerender;
1960 this.rendered = true;
1965 }))}(document, Math));