From af26aaa53d073a7b2d25caee93e1cb5ceb2e099c Mon Sep 17 00:00:00 2001 From: Igor Sfiligoi Date: Fri, 23 Oct 2009 09:07:01 -0400 Subject: flot-0.6 --- jquery.flot.js | 1516 ++++++++++++++++++++++---------------------------------- 1 file changed, 604 insertions(+), 912 deletions(-) (limited to 'jquery.flot.js') diff --git a/jquery.flot.js b/jquery.flot.js index e2fd767..6534a46 100644 --- a/jquery.flot.js +++ b/jquery.flot.js @@ -1,15 +1,39 @@ -/* Javascript plotting library for jQuery, v. 0.5. +/* Javascript plotting library for jQuery, v. 0.6. * * Released under the MIT license by IOLA, December 2007. * */ +// first an inline dependency, jquery.colorhelpers.js, we inline it here +// for convenience + +/* Plugin for jQuery for working with colors. + * + * Version 1.0. + * + * Inspiration from jQuery color animation plugin by John Resig. + * + * Released under the MIT license by Ole Laursen, October 2009. + * + * Examples: + * + * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString() + * var c = $.color.extract($("#mydiv"), 'background-color'); + * console.log(c.r, c.g, c.b, c.a); + * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)" + * + * Note that .scale() and .add() work in-place instead of returning + * new objects. + */ +(function(){jQuery.color={};jQuery.color.make=function(E,D,B,C){var F={};F.r=E||0;F.g=D||0;F.b=B||0;F.a=C!=null?C:1;F.add=function(I,H){for(var G=0;G=1){return"rgb("+[F.r,F.g,F.b].join(",")+")"}else{return"rgba("+[F.r,F.g,F.b,F.a].join(",")+")"}};F.normalize=function(){function G(I,J,H){return JH?H:J)}F.r=G(0,parseInt(F.r),255);F.g=G(0,parseInt(F.g),255);F.b=G(0,parseInt(F.b),255);F.a=G(0,F.a,1);return F};F.clone=function(){return jQuery.color.make(F.r,F.b,F.g,F.a)};return F.normalize()};jQuery.color.extract=function(C,B){var D;do{D=C.css(B).toLowerCase();if(D!=""&&D!="transparent"){break}C=C.parent()}while(!jQuery.nodeName(C.get(0),"body"));if(D=="rgba(0, 0, 0, 0)"){D="transparent"}return jQuery.color.parse(D)};jQuery.color.parse=function(E){var D,B=jQuery.color.make;if(D=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(E)){return B(parseInt(D[1],10),parseInt(D[2],10),parseInt(D[3],10))}if(D=/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(E)){return B(parseInt(D[1],10),parseInt(D[2],10),parseInt(D[3],10),parseFloat(D[4]))}if(D=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(E)){return B(parseFloat(D[1])*2.55,parseFloat(D[2])*2.55,parseFloat(D[3])*2.55)}if(D=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(E)){return B(parseFloat(D[1])*2.55,parseFloat(D[2])*2.55,parseFloat(D[3])*2.55,parseFloat(D[4]))}if(D=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(E)){return B(parseInt(D[1],16),parseInt(D[2],16),parseInt(D[3],16))}if(D=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(E)){return B(parseInt(D[1]+D[1],16),parseInt(D[2]+D[2],16),parseInt(D[3]+D[3],16))}var C=jQuery.trim(E).toLowerCase();if(C=="transparent"){return B(255,255,255,0)}else{D=A[C];return B(D[0],D[1],D[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(); + +// the actual Flot code (function($) { - function Plot(target_, data_, options_) { + function Plot(placeholder, data_, options_, plugins) { // data is on the form: // [ series1, series2 ... ] // where series is either just the data as [ [x1, y1], [x2, y2], ... ] - // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label" } + // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... } var series = [], options = { @@ -28,6 +52,8 @@ }, xaxis: { mode: null, // null or "time" + transform: null, // null or f: number -> number to transform axis + inverseTransform: null, // if transform is set, this should be the inverse function min: null, // min. value to show, null means set automatically max: null, // max. value to show, null means set automatically autoscaleMargin: null, // margin in % to add if auto-setting min/max @@ -41,7 +67,8 @@ tickSize: null, // number or [number, "unit"] minTickSize: null, // number or [number, "unit"] monthNames: null, // list of names of months - timeformat: null // format string to use + timeformat: null, // format string to use + twelveHourClock: false // 12 or 24 time in time mode }, yaxis: { autoscaleMargin: 0.02 @@ -51,36 +78,40 @@ }, y2axis: { autoscaleMargin: 0.02 - }, - points: { - show: false, - radius: 3, - lineWidth: 2, // in pixels - fill: true, - fillColor: "#ffffff" - }, - lines: { - // we don't put in show: false so we can see - // whether lines were actively disabled - lineWidth: 2, // in pixels - fill: false, - fillColor: null, - steps: false }, - bars: { - show: false, - lineWidth: 2, // in pixels - barWidth: 1, // in units of the x axis - fill: true, - fillColor: null, - align: "left", // or "center" - horizontal: false // when horizontal, left is now top + series: { + points: { + show: false, + radius: 3, + lineWidth: 2, // in pixels + fill: true, + fillColor: "#ffffff" + }, + lines: { + // we don't put in show: false so we can see + // whether lines were actively disabled + lineWidth: 2, // in pixels + fill: false, + fillColor: null, + steps: false + }, + bars: { + show: false, + lineWidth: 2, // in pixels + barWidth: 1, // in units of the x axis + fill: true, + fillColor: null, + align: "left", // or "center" + horizontal: false // when horizontal, left is now top + }, + shadowSize: 3 }, - threshold: null, // or { below: number, color: color spec} grid: { + show: true, + aboveData: false, color: "#545454", // primary color used for outline and labels backgroundColor: null, // null for transparent, else color - tickColor: "#dddddd", // color used for the ticks + tickColor: "rgba(0,0,0,0.15)", // color used for the ticks labelMargin: 5, // in pixels borderWidth: 2, // in pixels borderColor: null, // set if different from the grid color @@ -93,53 +124,112 @@ autoHighlight: true, // highlight in case mouse is near mouseActiveRadius: 10 // how far the mouse can be away to activate an item }, - selection: { - mode: null, // one of null, "x", "y" or "xy" - color: "#e8cfac" - }, - crosshair: { - mode: null, // one of null, "x", "y" or "xy", - color: "#aa0000" - }, - shadowSize: 3 + hooks: {} }, canvas = null, // the canvas for the plot itself overlay = null, // canvas for interactive stuff on top of plot eventHolder = null, // jQuery object that events should be bound to ctx = null, octx = null, - target = $(target_), axes = { xaxis: {}, yaxis: {}, x2axis: {}, y2axis: {} }, plotOffset = { left: 0, right: 0, top: 0, bottom: 0}, canvasWidth = 0, canvasHeight = 0, plotWidth = 0, plotHeight = 0, - // dedicated to storing data for buggy standard compliance cases - workarounds = {}; + hooks = { + processOptions: [], + processRawData: [], + processDatapoints: [], + draw: [], + bindEvents: [], + drawOverlay: [] + }, + plot = this; + + // public functions + plot.setData = setData; + plot.setupGrid = setupGrid; + plot.draw = draw; + plot.getPlaceholder = function() { return placeholder; }; + plot.getCanvas = function() { return canvas; }; + plot.getPlotOffset = function() { return plotOffset; }; + plot.width = function () { return plotWidth; }; + plot.height = function () { return plotHeight; }; + plot.offset = function () { + var o = eventHolder.offset(); + o.left += plotOffset.left; + o.top += plotOffset.top; + return o; + }; + plot.getData = function() { return series; }; + plot.getAxes = function() { return axes; }; + plot.getOptions = function() { return options; }; + plot.highlight = highlight; + plot.unhighlight = unhighlight; + plot.triggerRedrawOverlay = triggerRedrawOverlay; + plot.pointOffset = function(point) { + return { left: parseInt(axisSpecToRealAxis(point, "xaxis").p2c(+point.x) + plotOffset.left), + top: parseInt(axisSpecToRealAxis(point, "yaxis").p2c(+point.y) + plotOffset.top) }; + }; - this.setData = setData; - this.setupGrid = setupGrid; - this.draw = draw; - this.clearSelection = clearSelection; - this.setSelection = setSelection; - this.getCanvas = function() { return canvas; }; - this.getPlotOffset = function() { return plotOffset; }; - this.getData = function() { return series; }; - this.getAxes = function() { return axes; }; - this.setCrosshair = setCrosshair; - this.clearCrosshair = function () { setCrosshair(null); }; - this.highlight = highlight; - this.unhighlight = unhighlight; + + // public attributes + plot.hooks = hooks; // initialize + initPlugins(plot); parseOptions(options_); - setData(data_); constructCanvas(); + setData(data_); setupGrid(); draw(); + bindEvents(); + + function executeHooks(hook, args) { + args = [plot].concat(args); + for (var i = 0; i < hook.length; ++i) + hook[i].apply(this, args); + } + + function initPlugins() { + for (var i = 0; i < plugins.length; ++i) { + var p = plugins[i]; + p.init(plot); + if (p.options) + $.extend(true, options, p.options); + } + } + + function parseOptions(opts) { + $.extend(true, options, opts); + if (options.grid.borderColor == null) + options.grid.borderColor = options.grid.color; + // backwards compatibility, to be removed in future + if (options.xaxis.noTicks && options.xaxis.ticks == null) + options.xaxis.ticks = options.xaxis.noTicks; + if (options.yaxis.noTicks && options.yaxis.ticks == null) + options.yaxis.ticks = options.yaxis.noTicks; + if (options.grid.coloredAreas) + options.grid.markings = options.grid.coloredAreas; + if (options.grid.coloredAreasColor) + options.grid.markingsColor = options.grid.coloredAreasColor; + if (options.lines) + $.extend(true, options.series.lines, options.lines); + if (options.points) + $.extend(true, options.series.points, options.points); + if (options.bars) + $.extend(true, options.series.bars, options.bars); + if (options.shadowSize) + options.series.shadowSize = options.shadowSize; + + for (var n in hooks) + if (options.hooks[n] && options.hooks[n].length) + hooks[n] = hooks[n].concat(options.hooks[n]); + + executeHooks(hooks.processOptions, [options]); + } function setData(d) { series = parseData(d); - fillInSeriesOptions(); processData(); } @@ -147,36 +237,33 @@ function parseData(d) { var res = []; for (var i = 0; i < d.length; ++i) { - var s; + var s = $.extend(true, {}, options.series); + if (d[i].data) { - s = {}; - for (var v in d[i]) - s[v] = d[i][v]; - } - else { - s = { data: d[i] }; + s.data = d[i].data; // move the data instead of deep-copy + delete d[i].data; + + $.extend(true, s, d[i]); + + d[i].data = s.data; } + else + s.data = d[i]; res.push(s); } return res; } - function parseOptions(o) { - $.extend(true, options, o); - if (options.grid.borderColor == null) - options.grid.borderColor = options.grid.color - // backwards compatibility, to be removed in future - if (options.xaxis.noTicks && options.xaxis.ticks == null) - options.xaxis.ticks = options.xaxis.noTicks; - if (options.yaxis.noTicks && options.yaxis.ticks == null) - options.yaxis.ticks = options.yaxis.noTicks; - if (options.grid.coloredAreas) - options.grid.markings = options.grid.coloredAreas; - if (options.grid.coloredAreasColor) - options.grid.markingsColor = options.grid.coloredAreasColor; + function axisSpecToRealAxis(obj, attr) { + var a = obj[attr]; + if (!a || a == 1) + return axes[attr]; + if (typeof a == "number") + return axes[attr.charAt(0) + a + attr.slice(1)]; + return a; // assume it's OK } - + function fillInSeriesOptions() { var i; @@ -191,7 +278,7 @@ if (typeof sc == "number") assignedColors.push(sc); else - usedColors.push(parseColor(series[i].color)); + usedColors.push($.color.parse(series[i].color)); } } @@ -207,14 +294,13 @@ while (colors.length < neededColors) { var c; if (options.colors.length == i) // check degenerate case - c = new Color(100, 100, 100); + c = $.color.make(100, 100, 100); else - c = parseColor(options.colors[i]); + c = $.color.parse(options.colors[i]); // vary color if needed var sign = variation % 2 == 1 ? -1 : 1; - var factor = 1 + sign * Math.ceil(variation / 2) * 0.2; - c.scale(factor, factor, factor); + c.scale('rgb', 1 + sign * Math.ceil(variation / 2) * 0.2) // FIXME: if we're getting to close to something else, // we should probably skip this one @@ -231,7 +317,7 @@ var colori = 0, s; for (i = 0; i < series.length; ++i) { s = series[i]; - + // assign colors if (s.color == null) { s.color = colors[colori].toString(); @@ -240,121 +326,190 @@ else if (typeof s.color == "number") s.color = colors[s.color].toString(); - // copy the rest - s.lines = $.extend(true, {}, options.lines, s.lines); - s.points = $.extend(true, {}, options.points, s.points); - s.bars = $.extend(true, {}, options.bars, s.bars); - // turn on lines automatically in case nothing is set - if (s.lines.show == null && !s.bars.show && !s.points.show) - s.lines.show = true; - if (s.shadowSize == null) - s.shadowSize = options.shadowSize; - - if (!s.xaxis) - s.xaxis = axes.xaxis; - - if (s.xaxis == 1) - s.xaxis = axes.xaxis; - else if (s.xaxis == 2) - s.xaxis = axes.x2axis; - - if (!s.yaxis) - s.yaxis = axes.yaxis; - - if (s.yaxis == 1) - s.yaxis = axes.yaxis; - else if (s.yaxis == 2) - s.yaxis = axes.y2axis; + if (s.lines.show == null) { + var v, show = true; + for (v in s) + if (s[v].show) { + show = false; + break; + } + if (show) + s.lines.show = true; + } - if (!s.threshold) - s.threshold = options.threshold; - s.subseries = null; + // setup axes + s.xaxis = axisSpecToRealAxis(s, "xaxis"); + s.yaxis = axisSpecToRealAxis(s, "yaxis"); } } function processData() { var topSentry = Number.POSITIVE_INFINITY, bottomSentry = Number.NEGATIVE_INFINITY, - axis, i, j, k, m, s; + i, j, k, m, length, + s, points, ps, x, y, axis, val, f, p; for (axis in axes) { axes[axis].datamin = topSentry; axes[axis].datamax = bottomSentry; - axes[axis].min = options[axis].min; - axes[axis].max = options[axis].max; axes[axis].used = false; } - + + function updateAxis(axis, min, max) { + if (min < axis.datamin) + axis.datamin = min; + if (max > axis.datamax) + axis.datamax = max; + } + for (i = 0; i < series.length; ++i) { s = series[i]; - s.datapoints = { points: [], incr: 2 }; + s.datapoints = { points: [] }; - var data = s.data, - points = s.datapoints.points, - axisx = s.xaxis, axisy = s.yaxis, - xmin = topSentry, xmax = bottomSentry, - ymin = topSentry, ymax = bottomSentry, - x, y, p, incr, format = []; + executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]); + } + + // first pass: clean and copy data + for (i = 0; i < series.length; ++i) { + s = series[i]; - // determine the increment - if (s.bars.show) { - s.datapoints.incr = 3; - format.push({ d: 0 }); + var data = s.data, format = s.datapoints.format; + + if (!format) { + format = []; + // find out how to copy + format.push({ x: true, number: true, required: true }); + format.push({ y: true, number: true, required: true }); + + if (s.bars.show) + format.push({ y: true, number: true, required: false, defaultValue: 0 }); + + s.datapoints.format = format; } - /* - // examine data to find out how to copy - for (j = 0; j < data.length; ++j) { - }*/ - + if (s.datapoints.pointsize != null) + continue; // already filled in + + if (s.datapoints.pointsize == null) + s.datapoints.pointsize = format.length; - axisx.used = axisy.used = true; - incr = s.datapoints.incr; + ps = s.datapoints.pointsize; + points = s.datapoints.points; + + insertSteps = s.lines.show && s.lines.steps; + s.xaxis.used = s.yaxis.used = true; - for (j = k = 0; j < data.length; ++j, k += incr) { + for (j = k = 0; j < data.length; ++j, k += ps) { p = data[j]; - x = null; - y = null; - if (data[j] != null) { - x = p[0]; - y = p[1]; + var nullify = p == null; + if (!nullify) { + for (m = 0; m < ps; ++m) { + val = p[m]; + f = format[m]; + + if (f) { + if (f.number && val != null) { + val = +val; // convert to number + if (isNaN(val)) + val = null; + } + + if (val == null) { + if (f.required) + nullify = true; + + if (f.defaultValue != null) + val = f.defaultValue; + } + } + + points[k + m] = val; + } } - // convert to number - if (x != null && !isNaN(x = +x)) { - if (x < xmin) - xmin = x; - if (x > xmax) - xmax = x + if (nullify) { + for (m = 0; m < ps; ++m) { + val = points[k + m]; + if (val != null) { + f = format[m]; + // extract min/max info + if (f.x) + updateAxis(s.xaxis, val, val); + if (f.y) + updateAxis(s.yaxis, val, val); + } + points[k + m] = null; + } } - else - x = null; - - if (y != null && !isNaN(y = +y)) { - if (y < ymin) - ymin = y; - if (y > ymax) - ymax = y; + else { + // a little bit of line specific stuff that + // perhaps shouldn't be here, but lacking + // better means... + if (insertSteps && k > 0 + && points[k - ps] != null + && points[k - ps] != points[k] + && points[k - ps + 1] != points[k + 1]) { + // copy the point to make room for a middle point + for (m = 0; m < ps; ++m) + points[k + ps + m] = points[k + m]; + + // middle point has same y + points[k + 1] = points[k - ps + 1]; + + // we've added a point, better reflect that + k += ps; + } } - else - y = null; + } + } - if (x == null || y == null) - x = y = null; // make sure everything is cleared + // give the hooks a chance to run + for (i = 0; i < series.length; ++i) { + s = series[i]; + + executeHooks(hooks.processDatapoints, [ s, s.datapoints]); + } - for (m = 2; m < incr; ++m) - points[k + m] = p[m] == null ? format[m-2].d : p[m]; + // second pass: find datamax/datamin for auto-scaling + for (i = 0; i < series.length; ++i) { + s = series[i]; + points = s.datapoints.points, + ps = s.datapoints.pointsize; - points[k + 1] = y; - points[k] = x; - } + var xmin = topSentry, ymin = topSentry, + xmax = bottomSentry, ymax = bottomSentry; + + for (j = 0; j < points.length; j += ps) { + if (points[j] == null) + continue; + for (m = 0; m < ps; ++m) { + val = points[j + m]; + f = format[m]; + if (!f) + continue; + + if (f.x) { + if (val < xmin) + xmin = val; + if (val > xmax) + xmax = val; + } + if (f.y) { + if (val < ymin) + ymin = val; + if (val > ymax) + ymax = val; + } + } + } + if (s.bars.show) { // make sure we got room for the bar on the dancing floor var delta = s.bars.align == "left" ? 0 : -s.bars.barWidth/2; - if(s.bars.horizontal) { + if (s.bars.horizontal) { ymin += delta; ymax += delta + s.bars.barWidth; } @@ -364,104 +519,15 @@ } } - axisx.datamin = Math.min(axisx.datamin, xmin); - axisx.datamax = Math.max(axisx.datamax, xmax); - axisy.datamin = Math.min(axisy.datamin, ymin); - axisy.datamax = Math.max(axisy.datamax, ymax); - - - // step charts - if (s.lines.show && s.lines.steps) { - p = []; - // copy, inserting extra points to make steps - for (j = k = 0; j < points.length; j += incr, k += incr) { - x = points[j]; - y = points[j + 1]; - if (j > 0 - && points[j - incr] != null - && x != null - && points[j - incr + 1] != y) { - p[k] = x; - p[k + 1] = points[j - incr + 1]; - k += incr; - } - - p[k] = x; - p[k + 1] = y; - } - s.datapoints.linespoints = p; - } - - // possibly split data points because of threshold - if (s.threshold) { - var orig = $.extend({}, s), thresholded = $.extend({}, s); - orig.datapoints = { points: [], incr: incr }; - thresholded.datapoints = { points: [], incr: incr }; - - thresholded.color = s.threshold.color; - - var below = s.threshold.below, - origpoints = orig.datapoints.points, - threspoints = thresholded.datapoints.points; - - // ordinary points - for (j = 0; j < points.length; j += incr) { - x = points[j]; - y = points[j + 1]; - - if (y < below) - p = threspoints; - else - p = origpoints; - - p.push(x); - p.push(y); - - for (m = 2; m < incr; ++m) - p.push(points[j + m]); - } - - // possibly split lines - if (s.lines.show) { - var lp = s.datapoints.linespoints || points; - - origpoints = []; - threspoints = []; - p = origpoints; - - for (j = 0; j < lp.length; j += incr) { - x = lp[j]; - y = lp[j + 1]; - - var prevp = p; - if (y != null) { - if (y < below) - p = threspoints; - else - p = origpoints; - } - - if (p != prevp && x != null && j > 0 && lp[j - incr] != null) { - // find intersection and add it to both - k = (x - lp[j - incr]) / (y - lp[j - incr + 1]) * (below - y) + x; - prevp.push(k); - prevp.push(below); - p.push(null); // start new segment - p.push(null); - p.push(k); - p.push(below); - } - - p.push(x); - p.push(y); - } - - orig.datapoints.linespoints = origpoints - thresholded.datapoints.linespoints = threspoints; - } + updateAxis(s.xaxis, xmin, xmax); + updateAxis(s.yaxis, ymin, ymax); + } - s.subseries = [orig, thresholded]; - } + for (axis in axes) { + if (axes[axis].datamin == topSentry) + axes[axis].datamin = null; + if (axes[axis].datamax == bottomSentry) + axes[axis].datamax = null; } } @@ -475,11 +541,11 @@ return c; } - canvasWidth = target.width(); - canvasHeight = target.height(); - target.html(""); // clear target - if (target.css("position") == 'static') - target.css("position", "relative"); // for positioning labels and overlay + canvasWidth = placeholder.width(); + canvasHeight = placeholder.height(); + placeholder.html(""); // clear placeholder + if (placeholder.css("position") == 'static') + placeholder.css("position", "relative"); // for positioning labels and overlay if (canvasWidth <= 0 || canvasHeight <= 0) throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight; @@ -488,73 +554,185 @@ window.G_vmlCanvasManager.init_(document); // make sure everything is setup // the canvas - canvas = $(makeCanvas(canvasWidth, canvasHeight)).appendTo(target).get(0); + canvas = $(makeCanvas(canvasWidth, canvasHeight)).appendTo(placeholder).get(0); ctx = canvas.getContext("2d"); // overlay canvas for interactive features - overlay = $(makeCanvas(canvasWidth, canvasHeight)).css({ position: 'absolute', left: 0, top: 0 }).appendTo(target).get(0); + overlay = $(makeCanvas(canvasWidth, canvasHeight)).css({ position: 'absolute', left: 0, top: 0 }).appendTo(placeholder).get(0); octx = overlay.getContext("2d"); + octx.stroke(); + } + function bindEvents() { // we include the canvas in the event holder too, because IE 7 // sometimes has trouble with the stacking order eventHolder = $([overlay, canvas]); // bind events - if (options.selection.mode != null || options.crosshair.mode != null - || options.grid.hoverable) { - // FIXME: temp. work-around until jQuery bug 4398 is fixed - eventHolder.each(function () { - this.onmousemove = onMouseMove; - }); - - if (options.selection.mode != null) - eventHolder.mousedown(onMouseDown); - } + if (options.grid.hoverable) + eventHolder.mousemove(onMouseMove); - if (options.crosshair.mode != null) - eventHolder.mouseout(onMouseOut); - if (options.grid.clickable) eventHolder.click(onClick); + + executeHooks(hooks.bindEvents, [eventHolder]); } function setupGrid() { - function setupAxis(axis, options) { - setRange(axis, options); - prepareTickGeneration(axis, options); - setTicks(axis, options); + function setTransformationHelpers(axis, o) { + function identity(x) { return x; } + + var s, m, t = o.transform || identity, + it = o.inverseTransform; + // add transformation helpers if (axis == axes.xaxis || axis == axes.x2axis) { + // precompute how much the axis is scaling a point + // in canvas space + s = axis.scale = plotWidth / (t(axis.max) - t(axis.min)); + m = t(axis.min); + // data point to canvas coordinate - axis.p2c = function (p) { return (p - axis.min) * axis.scale; }; - // canvas coordinate to data point - axis.c2p = function (c) { return axis.min + c / axis.scale; }; + if (t == identity) // slight optimization + axis.p2c = function (p) { return (p - m) * s; }; + else + axis.p2c = function (p) { return (t(p) - m) * s; }; + // canvas coordinate to data point + if (!it) + axis.c2p = function (c) { return m + c / s; }; + else + axis.c2p = function (c) { return it(m + c / s); }; } else { - axis.p2c = function (p) { return (axis.max - p) * axis.scale; }; - axis.c2p = function (p) { return axis.max - p / axis.scale; }; + s = axis.scale = plotHeight / (t(axis.max) - t(axis.min)); + m = t(axis.max); + + if (t == identity) + axis.p2c = function (p) { return (m - p) * s; }; + else + axis.p2c = function (p) { return (m - t(p)) * s; }; + if (!it) + axis.c2p = function (c) { return m - c / s; }; + else + axis.c2p = function (c) { return it(m - c / s); }; + } + } + + function measureLabels(axis, axisOptions) { + var i, labels = [], l; + + axis.labelWidth = axisOptions.labelWidth; + axis.labelHeight = axisOptions.labelHeight; + + if (axis == axes.xaxis || axis == axes.x2axis) { + // to avoid measuring the widths of the labels, we + // construct fixed-size boxes and put the labels inside + // them, we don't need the exact figures and the + // fixed-size box content is easy to center + if (axis.labelWidth == null) + axis.labelWidth = canvasWidth / (axis.ticks.length > 0 ? axis.ticks.length : 1); + + // measure x label heights + if (axis.labelHeight == null) { + labels = []; + for (i = 0; i < axis.ticks.length; ++i) { + l = axis.ticks[i].label; + if (l) + labels.push('
' + l + '
'); + } + + if (labels.length > 0) { + var dummyDiv = $('
' + + labels.join("") + '
').appendTo(placeholder); + axis.labelHeight = dummyDiv.height(); + dummyDiv.remove(); + } + } + } + else if (axis.labelWidth == null || axis.labelHeight == null) { + // calculate y label dimensions + for (i = 0; i < axis.ticks.length; ++i) { + l = axis.ticks[i].label; + if (l) + labels.push('
' + l + '
'); + } + + if (labels.length > 0) { + var dummyDiv = $('
' + + labels.join("") + '
').appendTo(placeholder); + if (axis.labelWidth == null) + axis.labelWidth = dummyDiv.width(); + if (axis.labelHeight == null) + axis.labelHeight = dummyDiv.find("div").height(); + dummyDiv.remove(); + } + } + + if (axis.labelWidth == null) + axis.labelWidth = 0; + if (axis.labelHeight == null) + axis.labelHeight = 0; } + + function setGridSpacing() { + // get the most space needed around the grid for things + // that may stick out + var maxOutset = options.grid.borderWidth; + for (i = 0; i < series.length; ++i) + maxOutset = Math.max(maxOutset, 2 * (series[i].points.radius + series[i].points.lineWidth/2)); + + plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = maxOutset; + + var margin = options.grid.labelMargin + options.grid.borderWidth; + + if (axes.xaxis.labelHeight > 0) + plotOffset.bottom = Math.max(maxOutset, axes.xaxis.labelHeight + margin); + if (axes.yaxis.labelWidth > 0) + plotOffset.left = Math.max(maxOutset, axes.yaxis.labelWidth + margin); + if (axes.x2axis.labelHeight > 0) + plotOffset.top = Math.max(maxOutset, axes.x2axis.labelHeight + margin); + if (axes.y2axis.labelWidth > 0) + plotOffset.right = Math.max(maxOutset, axes.y2axis.labelWidth + margin); + + plotWidth = canvasWidth - plotOffset.left - plotOffset.right; + plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top; + } + + var axis; + for (axis in axes) + setRange(axes[axis], options[axis]); + + if (options.grid.show) { + for (axis in axes) { + prepareTickGeneration(axes[axis], options[axis]); + setTicks(axes[axis], options[axis]); + measureLabels(axes[axis], options[axis]); + } - for (var axis in axes) - setupAxis(axes[axis], options[axis]); + setGridSpacing(); + } + else { + plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = 0; + plotWidth = canvasWidth; + plotHeight = canvasHeight; + } + + for (axis in axes) + setTransformationHelpers(axes[axis], options[axis]); - setSpacing(); - insertLabels(); + if (options.grid.show) + insertLabels(); + insertLegend(); } function setRange(axis, axisOptions) { - var min = axisOptions.min != null ? +axisOptions.min : axis.datamin, - max = axisOptions.max != null ? +axisOptions.max : axis.datamax; - - // degenerate case - if (min == Number.POSITIVE_INFINITY) - min = 0; - if (max == Number.NEGATIVE_INFINITY) - max = 1; - - if (max - min == 0.0) { + var min = +(axisOptions.min != null ? axisOptions.min : axis.datamin), + max = +(axisOptions.max != null ? axisOptions.max : axis.datamax), + delta = max - min; + + if (delta == 0.0) { // degenerate case var widen = max == 0 ? 1 : 0.01; @@ -570,15 +748,15 @@ var margin = axisOptions.autoscaleMargin; if (margin != null) { if (axisOptions.min == null) { - min -= (max - min) * margin; + min -= delta * margin; // make sure we don't go below zero if all values // are positive - if (min < 0 && axis.datamin >= 0) + if (min < 0 && axis.datamin != null && axis.datamin >= 0) min = 0; } if (axisOptions.max == null) { - max += (max - min) * margin; - if (max > 0 && axis.datamax <= 0) + max += delta * margin; + if (max > 0 && axis.datamax != null && axis.datamax <= 0) max = 0; } } @@ -593,12 +771,14 @@ if (typeof axisOptions.ticks == "number" && axisOptions.ticks > 0) noTicks = axisOptions.ticks; else if (axis == axes.xaxis || axis == axes.x2axis) - noTicks = canvasWidth / 100; + // heuristic based on the model a*sqrt(x) fitted to + // some reasonable data points + noTicks = 0.3 * Math.sqrt(canvasWidth); else - noTicks = canvasHeight / 60; + noTicks = 0.3 * Math.sqrt(canvasHeight); - var delta = (axis.max - axis.min) / noTicks; - var size, generator, unit, formatter, i, magn, norm; + var delta = (axis.max - axis.min) / noTicks, + size, generator, unit, formatter, i, magn, norm; if (axisOptions.mode == "time") { // pretty handling of time @@ -738,14 +918,15 @@ var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]]; var span = axis.max - axis.min; + var suffix = (axisOptions.twelveHourClock) ? " %p" : ""; if (t < timeUnitSize.minute) - fmt = "%h:%M:%S"; + fmt = "%h:%M:%S" + suffix; else if (t < timeUnitSize.day) { if (span < 2 * timeUnitSize.day) - fmt = "%h:%M"; + fmt = "%h:%M" + suffix; else - fmt = "%b %d %h:%M"; + fmt = "%b %d %h:%M" + suffix; } else if (t < timeUnitSize.month) fmt = "%b %d"; @@ -767,7 +948,7 @@ var dec = -Math.floor(Math.log(delta) / Math.LN10); if (maxDec != null && dec > maxDec) dec = maxDec; - + magn = Math.pow(10, -dec); norm = delta / magn; // norm is between 1.0 and 10.0 @@ -793,9 +974,9 @@ if (axisOptions.tickSize != null) size = axisOptions.tickSize; - + axis.tickDecimals = Math.max(0, (maxDec != null) ? maxDec : dec); - + generator = function (axis) { var ticks = []; @@ -822,10 +1003,6 @@ axis.tickFormatter = function (v, axis) { return "" + axisOptions.tickFormatter(v, axis); }; else axis.tickFormatter = formatter; - if (axisOptions.labelWidth != null) - axis.labelWidth = axisOptions.labelWidth; - if (axisOptions.labelHeight != null) - axis.labelHeight = axisOptions.labelHeight; } function setTicks(axis, axisOptions) { @@ -870,111 +1047,25 @@ if (axisOptions.min == null) axis.min = Math.min(axis.min, axis.ticks[0].v); if (axisOptions.max == null && axis.ticks.length > 1) - axis.max = Math.min(axis.max, axis.ticks[axis.ticks.length - 1].v); + axis.max = Math.max(axis.max, axis.ticks[axis.ticks.length - 1].v); } } - - function setSpacing() { - function measureXLabels(axis) { - // to avoid measuring the widths of the labels, we - // construct fixed-size boxes and put the labels inside - // them, we don't need the exact figures and the - // fixed-size box content is easy to center - if (axis.labelWidth == null) - axis.labelWidth = canvasWidth / 6; + + function draw() { + ctx.clearRect(0, 0, canvasWidth, canvasHeight); - // measure x label heights - if (axis.labelHeight == null) { - labels = []; - for (i = 0; i < axis.ticks.length; ++i) { - l = axis.ticks[i].label; - if (l) - labels.push('
' + l + '
'); - } - - axis.labelHeight = 0; - if (labels.length > 0) { - var dummyDiv = $('
' - + labels.join("") + '
').appendTo(target); - axis.labelHeight = dummyDiv.height(); - dummyDiv.remove(); - } - } - } - - function measureYLabels(axis) { - if (axis.labelWidth == null || axis.labelHeight == null) { - var i, labels = [], l; - // calculate y label dimensions - for (i = 0; i < axis.ticks.length; ++i) { - l = axis.ticks[i].label; - if (l) - labels.push('
' + l + '
'); - } - - if (labels.length > 0) { - var dummyDiv = $('
' - + labels.join("") + '
').appendTo(target); - if (axis.labelWidth == null) - axis.labelWidth = dummyDiv.width(); - if (axis.labelHeight == null) - axis.labelHeight = dummyDiv.find("div").height(); - dummyDiv.remove(); - } - - if (axis.labelWidth == null) - axis.labelWidth = 0; - if (axis.labelHeight == null) - axis.labelHeight = 0; - } - } + var grid = options.grid; - measureXLabels(axes.xaxis); - measureYLabels(axes.yaxis); - measureXLabels(axes.x2axis); - measureYLabels(axes.y2axis); - - // get the most space needed around the grid for things - // that may stick out - var maxOutset = options.grid.borderWidth; - for (i = 0; i < series.length; ++i) - maxOutset = Math.max(maxOutset, 2 * (series[i].points.radius + series[i].points.lineWidth/2)); - - plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = maxOutset; + if (grid.show && !grid.aboveData) + drawGrid(); - var margin = options.grid.labelMargin + options.grid.borderWidth; - - if (axes.xaxis.labelHeight > 0) - plotOffset.bottom = Math.max(maxOutset, axes.xaxis.labelHeight + margin); - if (axes.yaxis.labelWidth > 0) - plotOffset.left = Math.max(maxOutset, axes.yaxis.labelWidth + margin); + for (var i = 0; i < series.length; ++i) + drawSeries(series[i]); - if (axes.x2axis.labelHeight > 0) - plotOffset.top = Math.max(maxOutset, axes.x2axis.labelHeight + margin); + executeHooks(hooks.draw, [ctx]); - if (axes.y2axis.labelWidth > 0) - plotOffset.right = Math.max(maxOutset, axes.y2axis.labelWidth + margin); - - plotWidth = canvasWidth - plotOffset.left - plotOffset.right; - plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top; - - // precompute how much the axis is scaling a point in canvas space - axes.xaxis.scale = plotWidth / (axes.xaxis.max - axes.xaxis.min); - axes.yaxis.scale = plotHeight / (axes.yaxis.max - axes.yaxis.min); - axes.x2axis.scale = plotWidth / (axes.x2axis.max - axes.x2axis.min); - axes.y2axis.scale = plotHeight / (axes.y2axis.max - axes.y2axis.min); - } - - function draw() { - drawGrid(); - for (var i = 0; i < series.length; ++i) { - var s = series[i]; - if (s.subseries) - for (var j = 0; j < s.subseries.length; ++j) - drawSeries(s.subseries[j]); - else - drawSeries(s); - } + if (grid.show && grid.aboveData) + drawGrid(); } function extractRange(ranges, coord) { @@ -1010,7 +1101,6 @@ var i; ctx.save(); - ctx.clearRect(0, 0, canvasWidth, canvasHeight); ctx.translate(plotOffset.left, plotOffset.top); // draw background, if any @@ -1062,8 +1152,8 @@ if (xrange.from == xrange.to || yrange.from == yrange.to) { // draw line - ctx.strokeStyle = m.color || options.grid.markingsColor; ctx.beginPath(); + ctx.strokeStyle = m.color || options.grid.markingsColor; ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth; //ctx.moveTo(Math.floor(xrange.from), yrange.from); //ctx.lineTo(Math.floor(xrange.to), yrange.to); @@ -1137,9 +1227,9 @@ ctx.restore(); } - + function insertLabels() { - target.find(".tickLabels").remove(); + placeholder.find(".tickLabels").remove(); var html = ['
']; @@ -1173,7 +1263,7 @@ html.push('
'); - target.append(html.join("")); + placeholder.append(html.join("")); } function drawSeries(series) { @@ -1187,13 +1277,13 @@ function drawSeriesLines(series) { function plotLine(datapoints, xoffset, yoffset, axisx, axisy) { - var points = datapoints.linespoints || datapoints.points, - incr = datapoints.incr, + var points = datapoints.points, + ps = datapoints.pointsize, prevx = null, prevy = null; ctx.beginPath(); - for (var i = incr; i < points.length; i += incr) { - var x1 = points[i - incr], y1 = points[i - incr + 1], + for (var i = ps; i < points.length; i += ps) { + var x1 = points[i - ps], y1 = points[i - ps + 1], x2 = points[i], y2 = points[i + 1]; if (x1 == null || x2 == null) @@ -1267,13 +1357,13 @@ } function plotLineArea(datapoints, axisx, axisy) { - var points = datapoints.linespoints || datapoints.points, - incr = datapoints.incr, + var points = datapoints.points, + ps = datapoints.pointsize, bottom = Math.min(Math.max(0, axisy.min), axisy.max), top, lastX = 0, areaOpen = false; - for (var i = incr; i < points.length; i += incr) { - var x1 = points[i - incr], y1 = points[i - incr + 1], + for (var i = ps; i < points.length; i += ps) { + var x1 = points[i - ps], y1 = points[i - ps + 1], x2 = points[i], y2 = points[i + 1]; if (areaOpen && x1 != null && x2 == null) { @@ -1413,10 +1503,11 @@ // draw shadow as a thick and thin line with transparency ctx.lineWidth = sw; ctx.strokeStyle = "rgba(0,0,0,0.1)"; - var xoffset = 1; - plotLine(series.datapoints, xoffset, Math.sqrt((lw/2 + sw/2)*(lw/2 + sw/2) - xoffset*xoffset), series.xaxis, series.yaxis); + // position shadow at angle from the mid of line + var angle = Math.PI/18; + plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis); ctx.lineWidth = sw/2; - plotLine(series.datapoints, xoffset, Math.sqrt((lw/2 + sw/4)*(lw/2 + sw/4) - xoffset*xoffset), series.xaxis, series.yaxis); + plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis); } ctx.lineWidth = lw; @@ -1434,15 +1525,15 @@ function drawSeriesPoints(series) { function plotPoints(datapoints, radius, fillStyle, offset, circumference, axisx, axisy) { - var points = datapoints.points, incr = datapoints.incr; + var points = datapoints.points, ps = datapoints.pointsize; - for (var i = 0; i < points.length; i += incr) { + for (var i = 0; i < points.length; i += ps) { var x = points[i], y = points[i + 1]; if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) continue; ctx.beginPath(); - ctx.arc(axisx.p2c(x), axisy.p2c(y) + offset, radius, 0, circumference, true); + ctx.arc(axisx.p2c(x), axisy.p2c(y) + offset, radius, 0, circumference, false); if (fillStyle) { ctx.fillStyle = fillStyle; ctx.fill(); @@ -1462,11 +1553,11 @@ var w = sw / 2; ctx.lineWidth = w; ctx.strokeStyle = "rgba(0,0,0,0.1)"; - plotPoints(series.datapoints, radius, null, w + w/2, 2 * Math.PI, + plotPoints(series.datapoints, radius, null, w + w/2, Math.PI, series.xaxis, series.yaxis); ctx.strokeStyle = "rgba(0,0,0,0.2)"; - plotPoints(series.datapoints, radius, null, w/2, 2 * Math.PI, + plotPoints(series.datapoints, radius, null, w/2, Math.PI, series.xaxis, series.yaxis); } @@ -1587,9 +1678,9 @@ function drawSeriesBars(series) { function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) { - var points = datapoints.points, incr = datapoints.incr; + var points = datapoints.points, ps = datapoints.pointsize; - for (var i = 0; i < points.length; i += incr) { + for (var i = 0; i < points.length; i += ps) { if (points[i] == null) continue; drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal); @@ -1616,14 +1707,14 @@ if (filloptions.fillColor) return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor); - var c = parseColor(seriesColor); + var c = $.color.parse(seriesColor); c.a = typeof fill == "number" ? fill : 0.4; c.normalize(); return c.toString(); } function insertLegend() { - target.find(".legend").remove(); + placeholder.find(".legend").remove(); if (!options.legend.show) return; @@ -1673,19 +1764,20 @@ pos += 'right:' + (m[0] + plotOffset.right) + 'px;'; else if (p.charAt(1) == "w") pos += 'left:' + (m[0] + plotOffset.left) + 'px;'; - var legend = $('
' + table.replace('style="', 'style="position:absolute;' + pos +';') + '
').appendTo(target); + var legend = $('
' + table.replace('style="', 'style="position:absolute;' + pos +';') + '
').appendTo(placeholder); if (options.legend.backgroundOpacity != 0.0) { // put in the transparent background // separately to avoid blended labels and // label boxes var c = options.legend.backgroundColor; if (c == null) { - var tmp; - if (options.grid.backgroundColor && typeof options.grid.backgroundColor == "string") - tmp = options.grid.backgroundColor; + c = options.grid.backgroundColor; + if (c && typeof c == "string") + c = $.color.parse(c); else - tmp = extractColor(legend); - c = parseColor(tmp).adjust(null, null, null, 1).toString(); + c = $.color.extract(legend, 'background-color'); + c.a = 1; + c = c.toString(); } var div = legend.children(); $('
').prependTo(legend).css('opacity', options.legend.backgroundOpacity); @@ -1696,23 +1788,16 @@ // interactive features - var lastMousePos = { pageX: null, pageY: null }, - selection = { - first: { x: -1, y: -1}, second: { x: -1, y: -1}, - show: false, active: false }, - crosshair = { pos: { x: -1, y: -1 } }, - highlights = [], - clickIsMouseUp = false, - redrawTimeout = null, - hoverTimeout = null; + var highlights = [], + redrawTimeout = null; - // Returns the data item the mouse is over, or null if none is found + // returns the data item the mouse is over, or null if none is found function findNearbyItem(mouseX, mouseY, seriesFilter) { var maxDistance = options.grid.mouseActiveRadius, - lowestDistance = maxDistance * maxDistance + 1, + smallestDistance = maxDistance * maxDistance + 1, item = null, foundPoint = false, i, j; - for (var i = 0; i < series.length; ++i) { + for (i = 0; i < series.length; ++i) { if (!seriesFilter(series[i])) continue; @@ -1720,14 +1805,14 @@ axisx = s.xaxis, axisy = s.yaxis, points = s.datapoints.points, - incr = s.datapoints.incr, + ps = s.datapoints.pointsize, mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster my = axisy.c2p(mouseY), maxx = maxDistance / axisx.scale, maxy = maxDistance / axisy.scale; if (s.lines.show || s.points.show) { - for (j = 0; j < points.length; j += incr) { + for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1]; if (x == null) continue; @@ -1742,10 +1827,13 @@ // data units, because the scales of the axes may be different var dx = Math.abs(axisx.p2c(x) - mouseX), dy = Math.abs(axisy.p2c(y) - mouseY), - dist = dx * dx + dy * dy; // no idea in taking sqrt - if (dist < lowestDistance) { - lowestDistance = dist; - item = [i, j / incr]; + dist = dx * dx + dy * dy; // we save the sqrt + + // use <= to ensure last point takes precedence + // (last generally means on top of) + if (dist <= smallestDistance) { + smallestDistance = dist; + item = [i, j / ps]; } } } @@ -1754,7 +1842,7 @@ var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2, barRight = barLeft + s.bars.barWidth; - for (j = 0; j < points.length; j += incr) { + for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1], b = points[j + 2]; if (x == null) continue; @@ -1765,7 +1853,7 @@ my >= y + barLeft && my <= y + barRight) : (mx >= x + barLeft && mx <= x + barRight && my >= Math.min(b, y) && my <= Math.max(b, y))) - item = [i, j / incr]; + item = [i, j / ps]; } } } @@ -1773,102 +1861,28 @@ if (item) { i = item[0]; j = item[1]; + ps = series[i].datapoints.pointsize; - return { datapoint: series[i].data[j], + return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps), dataIndex: j, series: series[i], - seriesIndex: i } + seriesIndex: i }; } return null; } - function onMouseMove(ev) { - // FIXME: temp. work-around until jQuery bug 4398 is fixed - var e = ev || window.event; - if (e.pageX == null && e.clientX != null) { - var de = document.documentElement, b = document.body; - lastMousePos.pageX = e.clientX + (de && de.scrollLeft || b.scrollLeft || 0) - (de.clientLeft || 0); - lastMousePos.pageY = e.clientY + (de && de.scrollTop || b.scrollTop || 0) - (de.clientTop || 0); - } - else { - lastMousePos.pageX = e.pageX; - lastMousePos.pageY = e.pageY; - } - + function onMouseMove(e) { if (options.grid.hoverable) - triggerClickHoverEvent("plothover", lastMousePos, + triggerClickHoverEvent("plothover", e, function (s) { return s["hoverable"] != false; }); - - if (options.crosshair.mode != null) { - if (!selection.active) { - setPositionFromEvent(crosshair.pos, lastMousePos); - triggerRedrawOverlay(); - } - else - crosshair.pos.x = -1; // hide the crosshair while selecting - } - - if (selection.active) { - target.trigger("plotselecting", [ selectionIsSane() ? getSelectionForEvent() : null ]); - - updateSelection(lastMousePos); - } - } - - function onMouseDown(e) { - if (e.which != 1) // only accept left-click - return; - - // cancel out any text selections - document.body.focus(); - - // prevent text selection and drag in old-school browsers - if (document.onselectstart !== undefined && workarounds.onselectstart == null) { - workarounds.onselectstart = document.onselectstart; - document.onselectstart = function () { return false; }; - } - if (document.ondrag !== undefined && workarounds.ondrag == null) { - workarounds.ondrag = document.ondrag; - document.ondrag = function () { return false; }; - } - - setSelectionPos(selection.first, e); - - lastMousePos.pageX = null; - selection.active = true; - $(document).one("mouseup", onSelectionMouseUp); - } - - function onMouseOut(ev) { - if (options.crosshair.mode != null && crosshair.pos.x != -1) { - crosshair.pos.x = -1; - triggerRedrawOverlay(); - } } function onClick(e) { - if (clickIsMouseUp) { - clickIsMouseUp = false; - return; - } - triggerClickHoverEvent("plotclick", e, function (s) { return s["clickable"] != false; }); } - /* - function userPositionInCanvasSpace(pos) { - return { x: parseInt(pos.x != null ? axes.xaxis.p2c(pos.x) : axes.x2axis.p2c(pos.x2)), - y: parseInt(pos.y != null ? axes.yaxis.p2c(pos.y) : axes.y2axis.p2c(pos.y2)) }; - } - - function positionInDivSpace(pos) { - var cpos = userPositionInCanvasSpace(pos); - return { x: cpos.x + plotOffset.left, - y: cpos.y + plotOffset.top }; - }*/ - // trigger click or hover event (they send the same parameters // so we share their code) function triggerClickHoverEvent(eventname, event, seriesFilter) { @@ -1907,18 +1921,18 @@ highlight(item.series, item.datapoint, eventname); } - target.trigger(eventname, [ pos, item ]); + placeholder.trigger(eventname, [ pos, item ]); } function triggerRedrawOverlay() { if (!redrawTimeout) - redrawTimeout = setTimeout(redrawOverlay, 30); + redrawTimeout = setTimeout(drawOverlay, 30); } - function redrawOverlay() { + function drawOverlay() { redrawTimeout = null; - // redraw highlights + // draw highlights octx.save(); octx.clearRect(0, 0, canvasWidth, canvasHeight); octx.translate(plotOffset.left, plotOffset.top); @@ -1932,43 +1946,9 @@ else drawPointHighlight(hi.series, hi.point); } - - // redraw selection - if (selection.show && selectionIsSane()) { - octx.strokeStyle = parseColor(options.selection.color).scale(null, null, null, 0.8).toString(); - octx.lineWidth = 1; - ctx.lineJoin = "round"; - octx.fillStyle = parseColor(options.selection.color).scale(null, null, null, 0.4).toString(); - - var x = Math.min(selection.first.x, selection.second.x), - y = Math.min(selection.first.y, selection.second.y), - w = Math.abs(selection.second.x - selection.first.x), - h = Math.abs(selection.second.y - selection.first.y); - - octx.fillRect(x, y, w, h); - octx.strokeRect(x, y, w, h); - } - - // redraw crosshair - var pos = crosshair.pos, mode = options.crosshair.mode; - if (mode != null && pos.x != -1) { - octx.strokeStyle = parseColor(options.crosshair.color).scale(null, null, null, 0.8).toString(); - octx.lineWidth = 1; - ctx.lineJoin = "round"; - - octx.beginPath(); - if (mode.indexOf("x") != -1) { - octx.moveTo(pos.x, 0); - octx.lineTo(pos.x, plotHeight); - } - if (mode.indexOf("y") != -1) { - octx.moveTo(0, pos.y); - octx.lineTo(plotWidth, pos.y); - } - octx.stroke(); - - } octx.restore(); + + executeHooks(hooks.drawOverlay, [octx]); } function highlight(s, point, auto) { @@ -1989,6 +1969,11 @@ } function unhighlight(s, point) { + if (s == null && point == null) { + highlights = []; + triggerRedrawOverlay(); + } + if (typeof s == "number") s = series[s]; @@ -2022,167 +2007,22 @@ var pointRadius = series.points.radius + series.points.lineWidth / 2; octx.lineWidth = pointRadius; - octx.strokeStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString(); + octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString(); var radius = 1.5 * pointRadius; octx.beginPath(); - octx.arc(axisx.p2c(x), axisy.p2c(y), radius, 0, 2 * Math.PI, true); + octx.arc(axisx.p2c(x), axisy.p2c(y), radius, 0, 2 * Math.PI, false); octx.stroke(); } function drawBarHighlight(series, point) { octx.lineWidth = series.bars.lineWidth; - octx.strokeStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString(); - var fillStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString(); + octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString(); + var fillStyle = $.color.parse(series.color).scale('a', 0.5).toString(); var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth, 0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal); } - function setPositionFromEvent(pos, e) { - var offset = eventHolder.offset(); - pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plotWidth); - pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plotHeight); - } - - function setCrosshair(pos) { - if (pos == null) - crosshair.pos.x = -1; - else { - crosshair.pos.x = clamp(0, pos.x != null ? axes.xaxis.p2c(pos.x) : axes.x2axis.p2c(pos.x2), plotWidth); - crosshair.pos.y = clamp(0, pos.y != null ? axes.yaxis.p2c(pos.y) : axes.y2axis.p2c(pos.y2), plotHeight); - } - triggerRedrawOverlay(); - } - - function getSelectionForEvent() { - var x1 = Math.min(selection.first.x, selection.second.x), - x2 = Math.max(selection.first.x, selection.second.x), - y1 = Math.max(selection.first.y, selection.second.y), - y2 = Math.min(selection.first.y, selection.second.y); - - var r = {}; - if (axes.xaxis.used) - r.xaxis = { from: axes.xaxis.c2p(x1), to: axes.xaxis.c2p(x2) }; - if (axes.x2axis.used) - r.x2axis = { from: axes.x2axis.c2p(x1), to: axes.x2axis.c2p(x2) }; - if (axes.yaxis.used) - r.yaxis = { from: axes.yaxis.c2p(y1), to: axes.yaxis.c2p(y2) }; - if (axes.y2axis.used) - r.y2axis = { from: axes.y2axis.c2p(y1), to: axes.y2axis.c2p(y2) }; - return r; - } - - function triggerSelectedEvent() { - var r = getSelectionForEvent(); - - target.trigger("plotselected", [ r ]); - - // backwards-compat stuff, to be removed in future - if (axes.xaxis.used && axes.yaxis.used) - target.trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]); - } - - function onSelectionMouseUp(e) { - // revert drag stuff for old-school browsers - if (document.onselectstart !== undefined) - document.onselectstart = workarounds.onselectstart; - if (document.ondrag !== undefined) - document.ondrag = workarounds.ondrag; - - // no more draggy-dee-drag - selection.active = false; - updateSelection(e); - - if (selectionIsSane()) { - triggerSelectedEvent(); - clickIsMouseUp = true; - } - else { - // this counts as a clear - target.trigger("plotunselected", [ ]); - target.trigger("plotselecting", [ null ]); - } - - return false; - } - - function setSelectionPos(pos, e) { - setPositionFromEvent(pos, e); - - if (options.selection.mode == "y") { - if (pos == selection.first) - pos.x = 0; - else - pos.x = plotWidth; - } - - if (options.selection.mode == "x") { - if (pos == selection.first) - pos.y = 0; - else - pos.y = plotHeight; - } - } - - function updateSelection(pos) { - if (pos.pageX == null) - return; - - setSelectionPos(selection.second, pos); - if (selectionIsSane()) { - selection.show = true; - triggerRedrawOverlay(); - } - else - clearSelection(true); - } - - function clearSelection(preventEvent) { - if (selection.show) { - selection.show = false; - triggerRedrawOverlay(); - if (!preventEvent) - target.trigger("plotunselected", [ ]); - } - } - - function setSelection(ranges, preventEvent) { - var range; - - if (options.selection.mode == "y") { - selection.first.x = 0; - selection.second.x = plotWidth; - } - else { - range = extractRange(ranges, "x"); - - selection.first.x = range.axis.p2c(range.from); - selection.second.x = range.axis.p2c(range.to); - } - - if (options.selection.mode == "x") { - selection.first.y = 0; - selection.second.y = plotHeight; - } - else { - range = extractRange(ranges, "y"); - - selection.first.y = range.axis.p2c(range.from); - selection.second.y = range.axis.p2c(range.to); - } - - selection.show = true; - triggerRedrawOverlay(); - if (!preventEvent) - triggerSelectedEvent(); - } - - function selectionIsSane() { - var minSize = 5; - return Math.abs(selection.second.x - selection.first.x) >= minSize && - Math.abs(selection.second.y - selection.first.y) >= minSize; - } - function getColorOrGradient(spec, bottom, top, defaultColor) { if (typeof spec == "string") return spec; @@ -2194,17 +2034,22 @@ for (var i = 0, l = spec.colors.length; i < l; ++i) { var c = spec.colors[i]; - gradient.addColorStop(i / (l - 1), typeof c == "string" ? c : parseColor(defaultColor).scale(c.brightness, c.brightness, c.brightness, c.opacity)); + if (typeof c != "string") { + c = $.color.parse(defaultColor).scale('rgb', c.brightness); + c.a *= c.opacity; + c = c.toString(); + } + gradient.addColorStop(i / (l - 1), c); } return gradient; } } } - - $.plot = function(target, data, options) { - var plot = new Plot(target, data, options); - /*var t0 = new Date(); + + $.plot = function(placeholder, data, options) { + var plot = new Plot($(placeholder), data, options, $.plot.plugins); + /*var t0 = new Date(); var t1 = new Date(); var tstr = "time used (msecs): " + (t1.getTime() - t0.getTime()) if (window.console) @@ -2214,6 +2059,8 @@ return plot; }; + $.plot.plugins = []; + // returns a string with the date d formatted according to fmt $.plot.formatDate = function(d, fmt, monthNames) { var leftPad = function(n) { @@ -2223,21 +2070,33 @@ var r = []; var escape = false; + var hours = d.getUTCHours(); + var isAM = hours < 12; if (monthNames == null) monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + + if (fmt.search(/%p|%P/) != -1) { + if (hours > 12) { + hours = hours - 12; + } else if (hours == 0) { + hours = 12; + } + } for (var i = 0; i < fmt.length; ++i) { var c = fmt.charAt(i); if (escape) { switch (c) { - case 'h': c = "" + d.getUTCHours(); break; - case 'H': c = leftPad(d.getUTCHours()); break; + case 'h': c = "" + hours; break; + case 'H': c = leftPad(hours); break; case 'M': c = leftPad(d.getUTCMinutes()); break; case 'S': c = leftPad(d.getUTCSeconds()); break; case 'd': c = "" + d.getUTCDate(); break; case 'm': c = "" + (d.getUTCMonth() + 1); break; case 'y': c = "" + d.getUTCFullYear(); break; case 'b': c = "" + monthNames[d.getUTCMonth()]; break; + case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break; + case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break; } r.push(c); escape = false; @@ -2257,171 +2116,4 @@ return base * Math.floor(n / base); } - function clamp(min, value, max) { - if (value < min) - return min; - else if (value > max) - return max; - else - return value; - } - - // color helpers, inspiration from the jquery color animation - // plugin by John Resig - function Color (r, g, b, a) { - - var rgba = ['r','g','b','a']; - var x = 4; //rgba.length - - while (-1<--x) { - this[rgba[x]] = arguments[x] || ((x==3) ? 1.0 : 0); - } - - this.toString = function() { - if (this.a >= 1.0) { - return "rgb("+[this.r,this.g,this.b].join(",")+")"; - } else { - return "rgba("+[this.r,this.g,this.b,this.a].join(",")+")"; - } - }; - - this.scale = function(rf, gf, bf, af) { - x = 4; //rgba.length - while (-1<--x) { - if (arguments[x] != null) - this[rgba[x]] *= arguments[x]; - } - return this.normalize(); - }; - - this.adjust = function(rd, gd, bd, ad) { - x = 4; //rgba.length - while (-1<--x) { - if (arguments[x] != null) - this[rgba[x]] += arguments[x]; - } - return this.normalize(); - }; - - this.clone = function() { - return new Color(this.r, this.b, this.g, this.a); - }; - - var limit = function(val,minVal,maxVal) { - return Math.max(Math.min(val, maxVal), minVal); - }; - - this.normalize = function() { - this.r = clamp(0, parseInt(this.r), 255); - this.g = clamp(0, parseInt(this.g), 255); - this.b = clamp(0, parseInt(this.b), 255); - this.a = clamp(0, this.a, 1); - return this; - }; - - this.normalize(); - } - - var lookupColors = { - aqua:[0,255,255], - azure:[240,255,255], - beige:[245,245,220], - black:[0,0,0], - blue:[0,0,255], - brown:[165,42,42], - cyan:[0,255,255], - darkblue:[0,0,139], - darkcyan:[0,139,139], - darkgrey:[169,169,169], - darkgreen:[0,100,0], - darkkhaki:[189,183,107], - darkmagenta:[139,0,139], - darkolivegreen:[85,107,47], - darkorange:[255,140,0], - darkorchid:[153,50,204], - darkred:[139,0,0], - darksalmon:[233,150,122], - darkviolet:[148,0,211], - fuchsia:[255,0,255], - gold:[255,215,0], - green:[0,128,0], - indigo:[75,0,130], - khaki:[240,230,140], - lightblue:[173,216,230], - lightcyan:[224,255,255], - lightgreen:[144,238,144], - lightgrey:[211,211,211], - lightpink:[255,182,193], - lightyellow:[255,255,224], - lime:[0,255,0], - magenta:[255,0,255], - maroon:[128,0,0], - navy:[0,0,128], - olive:[128,128,0], - orange:[255,165,0], - pink:[255,192,203], - purple:[128,0,128], - violet:[128,0,128], - red:[255,0,0], - silver:[192,192,192], - white:[255,255,255], - yellow:[255,255,0] - }; - - function extractColor(element) { - var color, elem = element; - do { - color = elem.css("background-color").toLowerCase(); - // keep going until we find an element that has color, or - // we hit the body - if (color != '' && color != 'transparent') - break; - elem = elem.parent(); - } while (!$.nodeName(elem.get(0), "body")); - - // catch Safari's way of signalling transparent - if (color == "rgba(0, 0, 0, 0)") - return "transparent"; - - return color; - } - - // parse string, returns Color - function parseColor(str) { - var result; - - // Look for rgb(num,num,num) - if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str)) - return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10)); - - // Look for rgba(num,num,num,num) - if (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(str)) - return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10), parseFloat(result[4])); - - // Look for rgb(num%,num%,num%) - if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str)) - return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55); - - // Look for rgba(num%,num%,num%,num) - if (result = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) - return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, parseFloat(result[4])); - - // Look for #a0b1c2 - if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str)) - return new Color(parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)); - - // Look for #fff - if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str)) - return new Color(parseInt(result[1]+result[1], 16), parseInt(result[2]+result[2], 16), parseInt(result[3]+result[3], 16)); - - // Otherwise, we're most likely dealing with a named color - var name = $.trim(str).toLowerCase(); - if (name == "transparent") - return new Color(255, 255, 255, 0); - else { - result = lookupColors[name]; - return new Color(result[0], result[1], result[2]); - } - } - })(jQuery); -- cgit v1.2.3