PageRenderTime 56ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/public/themes/js/plugins/flot/jquery.flot.js

https://gitlab.com/heruujoko/dynaform
JavaScript | 1278 lines | 838 code | 208 blank | 232 comment | 280 complexity | 18800e18342a9f488e88050f6415a42a MD5 | raw file
  1. /* Javascript plotting library for jQuery, version 0.8.3.
  2. Copyright (c) 2007-2014 IOLA and Ole Laursen.
  3. Licensed under the MIT license.
  4. */
  5. // first an inline dependency, jquery.colorhelpers.js, we inline it here
  6. // for convenience
  7. /* Plugin for jQuery for working with colors.
  8. *
  9. * Version 1.1.
  10. *
  11. * Inspiration from jQuery color animation plugin by John Resig.
  12. *
  13. * Released under the MIT license by Ole Laursen, October 2009.
  14. *
  15. * Examples:
  16. *
  17. * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
  18. * var c = $.color.extract($("#mydiv"), 'background-color');
  19. * console.log(c.r, c.g, c.b, c.a);
  20. * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
  21. *
  22. * Note that .scale() and .add() return the same modified object
  23. * instead of making a new one.
  24. *
  25. * V. 1.1: Fix error handling so e.g. parsing an empty string does
  26. * produce a color rather than just crashing.
  27. */
  28. (function($){$.color={};$.color.make=function(r,g,b,a){var o={};o.r=r||0;o.g=g||0;o.b=b||0;o.a=a!=null?a:1;o.add=function(c,d){for(var i=0;i<c.length;++i)o[c.charAt(i)]+=d;return o.normalize()};o.scale=function(c,f){for(var i=0;i<c.length;++i)o[c.charAt(i)]*=f;return o.normalize()};o.toString=function(){if(o.a>=1){return"rgb("+[o.r,o.g,o.b].join(",")+")"}else{return"rgba("+[o.r,o.g,o.b,o.a].join(",")+")"}};o.normalize=function(){function clamp(min,value,max){return value<min?min:value>max?max:value}o.r=clamp(0,parseInt(o.r),255);o.g=clamp(0,parseInt(o.g),255);o.b=clamp(0,parseInt(o.b),255);o.a=clamp(0,o.a,1);return o};o.clone=function(){return $.color.make(o.r,o.b,o.g,o.a)};return o.normalize()};$.color.extract=function(elem,css){var c;do{c=elem.css(css).toLowerCase();if(c!=""&&c!="transparent")break;elem=elem.parent()}while(elem.length&&!$.nodeName(elem.get(0),"body"));if(c=="rgba(0, 0, 0, 0)")c="transparent";return $.color.parse(c)};$.color.parse=function(str){var res,m=$.color.make;if(res=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10));if(res=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10),parseFloat(res[4]));if(res=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55);if(res=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55,parseFloat(res[4]));if(res=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))return m(parseInt(res[1],16),parseInt(res[2],16),parseInt(res[3],16));if(res=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))return m(parseInt(res[1]+res[1],16),parseInt(res[2]+res[2],16),parseInt(res[3]+res[3],16));var name=$.trim(str).toLowerCase();if(name=="transparent")return m(255,255,255,0);else{res=lookupColors[name]||[0,0,0];return m(res[0],res[1],res[2])}};var lookupColors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
  29. // the actual Flot code
  30. (function($) {
  31. // Cache the prototype hasOwnProperty for faster access
  32. var hasOwnProperty = Object.prototype.hasOwnProperty;
  33. // A shim to provide 'detach' to jQuery versions prior to 1.4. Using a DOM
  34. // operation produces the same effect as detach, i.e. removing the element
  35. // without touching its jQuery data.
  36. // Do not merge this into Flot 0.9, since it requires jQuery 1.4.4+.
  37. if (!$.fn.detach) {
  38. $.fn.detach = function() {
  39. return this.each(function() {
  40. if (this.parentNode) {
  41. this.parentNode.removeChild( this );
  42. }
  43. });
  44. };
  45. }
  46. ///////////////////////////////////////////////////////////////////////////
  47. // The Canvas object is a wrapper around an HTML5 <canvas> tag.
  48. //
  49. // @constructor
  50. // @param {string} cls List of classes to apply to the canvas.
  51. // @param {element} container Element onto which to append the canvas.
  52. //
  53. // Requiring a container is a little iffy, but unfortunately canvas
  54. // operations don't work unless the canvas is attached to the DOM.
  55. function Canvas(cls, container) {
  56. var element = container.children("." + cls)[0];
  57. if (element == null) {
  58. element = document.createElement("canvas");
  59. element.className = cls;
  60. $(element).css({ direction: "ltr", position: "absolute", left: 0, top: 0 })
  61. .appendTo(container);
  62. // If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas
  63. if (!element.getContext) {
  64. if (window.G_vmlCanvasManager) {
  65. element = window.G_vmlCanvasManager.initElement(element);
  66. } else {
  67. throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode.");
  68. }
  69. }
  70. }
  71. this.element = element;
  72. var context = this.context = element.getContext("2d");
  73. // Determine the screen's ratio of physical to device-independent
  74. // pixels. This is the ratio between the canvas width that the browser
  75. // advertises and the number of pixels actually present in that space.
  76. // The iPhone 4, for example, has a device-independent width of 320px,
  77. // but its screen is actually 640px wide. It therefore has a pixel
  78. // ratio of 2, while most normal devices have a ratio of 1.
  79. var devicePixelRatio = window.devicePixelRatio || 1,
  80. backingStoreRatio =
  81. context.webkitBackingStorePixelRatio ||
  82. context.mozBackingStorePixelRatio ||
  83. context.msBackingStorePixelRatio ||
  84. context.oBackingStorePixelRatio ||
  85. context.backingStorePixelRatio || 1;
  86. this.pixelRatio = devicePixelRatio / backingStoreRatio;
  87. // Size the canvas to match the internal dimensions of its container
  88. this.resize(container.width(), container.height());
  89. // Collection of HTML div layers for text overlaid onto the canvas
  90. this.textContainer = null;
  91. this.text = {};
  92. // Cache of text fragments and metrics, so we can avoid expensively
  93. // re-calculating them when the plot is re-rendered in a loop.
  94. this._textCache = {};
  95. }
  96. // Resizes the canvas to the given dimensions.
  97. //
  98. // @param {number} width New width of the canvas, in pixels.
  99. // @param {number} width New height of the canvas, in pixels.
  100. Canvas.prototype.resize = function(width, height) {
  101. if (width <= 0 || height <= 0) {
  102. throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height);
  103. }
  104. var element = this.element,
  105. context = this.context,
  106. pixelRatio = this.pixelRatio;
  107. // Resize the canvas, increasing its density based on the display's
  108. // pixel ratio; basically giving it more pixels without increasing the
  109. // size of its element, to take advantage of the fact that retina
  110. // displays have that many more pixels in the same advertised space.
  111. // Resizing should reset the state (excanvas seems to be buggy though)
  112. if (this.width != width) {
  113. element.width = width * pixelRatio;
  114. element.style.width = width + "px";
  115. this.width = width;
  116. }
  117. if (this.height != height) {
  118. element.height = height * pixelRatio;
  119. element.style.height = height + "px";
  120. this.height = height;
  121. }
  122. // Save the context, so we can reset in case we get replotted. The
  123. // restore ensure that we're really back at the initial state, and
  124. // should be safe even if we haven't saved the initial state yet.
  125. context.restore();
  126. context.save();
  127. // Scale the coordinate space to match the display density; so even though we
  128. // may have twice as many pixels, we still want lines and other drawing to
  129. // appear at the same size; the extra pixels will just make them crisper.
  130. context.scale(pixelRatio, pixelRatio);
  131. };
  132. // Clears the entire canvas area, not including any overlaid HTML text
  133. Canvas.prototype.clear = function() {
  134. this.context.clearRect(0, 0, this.width, this.height);
  135. };
  136. // Finishes rendering the canvas, including managing the text overlay.
  137. Canvas.prototype.render = function() {
  138. var cache = this._textCache;
  139. // For each text layer, add elements marked as active that haven't
  140. // already been rendered, and remove those that are no longer active.
  141. for (var layerKey in cache) {
  142. if (hasOwnProperty.call(cache, layerKey)) {
  143. var layer = this.getTextLayer(layerKey),
  144. layerCache = cache[layerKey];
  145. layer.hide();
  146. for (var styleKey in layerCache) {
  147. if (hasOwnProperty.call(layerCache, styleKey)) {
  148. var styleCache = layerCache[styleKey];
  149. for (var key in styleCache) {
  150. if (hasOwnProperty.call(styleCache, key)) {
  151. var positions = styleCache[key].positions;
  152. for (var i = 0, position; position = positions[i]; i++) {
  153. if (position.active) {
  154. if (!position.rendered) {
  155. layer.append(position.element);
  156. position.rendered = true;
  157. }
  158. } else {
  159. positions.splice(i--, 1);
  160. if (position.rendered) {
  161. position.element.detach();
  162. }
  163. }
  164. }
  165. if (positions.length == 0) {
  166. delete styleCache[key];
  167. }
  168. }
  169. }
  170. }
  171. }
  172. layer.show();
  173. }
  174. }
  175. };
  176. // Creates (if necessary) and returns the text overlay container.
  177. //
  178. // @param {string} classes String of space-separated CSS classes used to
  179. // uniquely identify the text layer.
  180. // @return {object} The jQuery-wrapped text-layer div.
  181. Canvas.prototype.getTextLayer = function(classes) {
  182. var layer = this.text[classes];
  183. // Create the text layer if it doesn't exist
  184. if (layer == null) {
  185. // Create the text layer container, if it doesn't exist
  186. if (this.textContainer == null) {
  187. this.textContainer = $("<div class='flot-text'></div>")
  188. .css({
  189. position: "absolute",
  190. top: 0,
  191. left: 0,
  192. bottom: 0,
  193. right: 0,
  194. 'font-size': "smaller",
  195. color: "#545454"
  196. })
  197. .insertAfter(this.element);
  198. }
  199. layer = this.text[classes] = $("<div></div>")
  200. .addClass(classes)
  201. .css({
  202. position: "absolute",
  203. top: 0,
  204. left: 0,
  205. bottom: 0,
  206. right: 0
  207. })
  208. .appendTo(this.textContainer);
  209. }
  210. return layer;
  211. };
  212. // Creates (if necessary) and returns a text info object.
  213. //
  214. // The object looks like this:
  215. //
  216. // {
  217. // width: Width of the text's wrapper div.
  218. // height: Height of the text's wrapper div.
  219. // element: The jQuery-wrapped HTML div containing the text.
  220. // positions: Array of positions at which this text is drawn.
  221. // }
  222. //
  223. // The positions array contains objects that look like this:
  224. //
  225. // {
  226. // active: Flag indicating whether the text should be visible.
  227. // rendered: Flag indicating whether the text is currently visible.
  228. // element: The jQuery-wrapped HTML div containing the text.
  229. // x: X coordinate at which to draw the text.
  230. // y: Y coordinate at which to draw the text.
  231. // }
  232. //
  233. // Each position after the first receives a clone of the original element.
  234. //
  235. // The idea is that that the width, height, and general 'identity' of the
  236. // text is constant no matter where it is placed; the placements are a
  237. // secondary property.
  238. //
  239. // Canvas maintains a cache of recently-used text info objects; getTextInfo
  240. // either returns the cached element or creates a new entry.
  241. //
  242. // @param {string} layer A string of space-separated CSS classes uniquely
  243. // identifying the layer containing this text.
  244. // @param {string} text Text string to retrieve info for.
  245. // @param {(string|object)=} font Either a string of space-separated CSS
  246. // classes or a font-spec object, defining the text's font and style.
  247. // @param {number=} angle Angle at which to rotate the text, in degrees.
  248. // Angle is currently unused, it will be implemented in the future.
  249. // @param {number=} width Maximum width of the text before it wraps.
  250. // @return {object} a text info object.
  251. Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) {
  252. var textStyle, layerCache, styleCache, info;
  253. // Cast the value to a string, in case we were given a number or such
  254. text = "" + text;
  255. // If the font is a font-spec object, generate a CSS font definition
  256. if (typeof font === "object") {
  257. textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family;
  258. } else {
  259. textStyle = font;
  260. }
  261. // Retrieve (or create) the cache for the text's layer and styles
  262. layerCache = this._textCache[layer];
  263. if (layerCache == null) {
  264. layerCache = this._textCache[layer] = {};
  265. }
  266. styleCache = layerCache[textStyle];
  267. if (styleCache == null) {
  268. styleCache = layerCache[textStyle] = {};
  269. }
  270. info = styleCache[text];
  271. // If we can't find a matching element in our cache, create a new one
  272. if (info == null) {
  273. var element = $("<div></div>").html(text)
  274. .css({
  275. position: "absolute",
  276. 'max-width': width,
  277. top: -9999
  278. })
  279. .appendTo(this.getTextLayer(layer));
  280. if (typeof font === "object") {
  281. element.css({
  282. font: textStyle,
  283. color: font.color
  284. });
  285. } else if (typeof font === "string") {
  286. element.addClass(font);
  287. }
  288. info = styleCache[text] = {
  289. width: element.outerWidth(true),
  290. height: element.outerHeight(true),
  291. element: element,
  292. positions: []
  293. };
  294. element.detach();
  295. }
  296. return info;
  297. };
  298. // Adds a text string to the canvas text overlay.
  299. //
  300. // The text isn't drawn immediately; it is marked as rendering, which will
  301. // result in its addition to the canvas on the next render pass.
  302. //
  303. // @param {string} layer A string of space-separated CSS classes uniquely
  304. // identifying the layer containing this text.
  305. // @param {number} x X coordinate at which to draw the text.
  306. // @param {number} y Y coordinate at which to draw the text.
  307. // @param {string} text Text string to draw.
  308. // @param {(string|object)=} font Either a string of space-separated CSS
  309. // classes or a font-spec object, defining the text's font and style.
  310. // @param {number=} angle Angle at which to rotate the text, in degrees.
  311. // Angle is currently unused, it will be implemented in the future.
  312. // @param {number=} width Maximum width of the text before it wraps.
  313. // @param {string=} halign Horizontal alignment of the text; either "left",
  314. // "center" or "right".
  315. // @param {string=} valign Vertical alignment of the text; either "top",
  316. // "middle" or "bottom".
  317. Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) {
  318. var info = this.getTextInfo(layer, text, font, angle, width),
  319. positions = info.positions;
  320. // Tweak the div's position to match the text's alignment
  321. if (halign == "center") {
  322. x -= info.width / 2;
  323. } else if (halign == "right") {
  324. x -= info.width;
  325. }
  326. if (valign == "middle") {
  327. y -= info.height / 2;
  328. } else if (valign == "bottom") {
  329. y -= info.height;
  330. }
  331. // Determine whether this text already exists at this position.
  332. // If so, mark it for inclusion in the next render pass.
  333. for (var i = 0, position; position = positions[i]; i++) {
  334. if (position.x == x && position.y == y) {
  335. position.active = true;
  336. return;
  337. }
  338. }
  339. // If the text doesn't exist at this position, create a new entry
  340. // For the very first position we'll re-use the original element,
  341. // while for subsequent ones we'll clone it.
  342. position = {
  343. active: true,
  344. rendered: false,
  345. element: positions.length ? info.element.clone() : info.element,
  346. x: x,
  347. y: y
  348. };
  349. positions.push(position);
  350. // Move the element to its final position within the container
  351. position.element.css({
  352. top: Math.round(y),
  353. left: Math.round(x),
  354. 'text-align': halign // In case the text wraps
  355. });
  356. };
  357. // Removes one or more text strings from the canvas text overlay.
  358. //
  359. // If no parameters are given, all text within the layer is removed.
  360. //
  361. // Note that the text is not immediately removed; it is simply marked as
  362. // inactive, which will result in its removal on the next render pass.
  363. // This avoids the performance penalty for 'clear and redraw' behavior,
  364. // where we potentially get rid of all text on a layer, but will likely
  365. // add back most or all of it later, as when redrawing axes, for example.
  366. //
  367. // @param {string} layer A string of space-separated CSS classes uniquely
  368. // identifying the layer containing this text.
  369. // @param {number=} x X coordinate of the text.
  370. // @param {number=} y Y coordinate of the text.
  371. // @param {string=} text Text string to remove.
  372. // @param {(string|object)=} font Either a string of space-separated CSS
  373. // classes or a font-spec object, defining the text's font and style.
  374. // @param {number=} angle Angle at which the text is rotated, in degrees.
  375. // Angle is currently unused, it will be implemented in the future.
  376. Canvas.prototype.removeText = function(layer, x, y, text, font, angle) {
  377. if (text == null) {
  378. var layerCache = this._textCache[layer];
  379. if (layerCache != null) {
  380. for (var styleKey in layerCache) {
  381. if (hasOwnProperty.call(layerCache, styleKey)) {
  382. var styleCache = layerCache[styleKey];
  383. for (var key in styleCache) {
  384. if (hasOwnProperty.call(styleCache, key)) {
  385. var positions = styleCache[key].positions;
  386. for (var i = 0, position; position = positions[i]; i++) {
  387. position.active = false;
  388. }
  389. }
  390. }
  391. }
  392. }
  393. }
  394. } else {
  395. var positions = this.getTextInfo(layer, text, font, angle).positions;
  396. for (var i = 0, position; position = positions[i]; i++) {
  397. if (position.x == x && position.y == y) {
  398. position.active = false;
  399. }
  400. }
  401. }
  402. };
  403. ///////////////////////////////////////////////////////////////////////////
  404. // The top-level container for the entire plot.
  405. function Plot(placeholder, data_, options_, plugins) {
  406. // data is on the form:
  407. // [ series1, series2 ... ]
  408. // where series is either just the data as [ [x1, y1], [x2, y2], ... ]
  409. // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }
  410. var series = [],
  411. options = {
  412. // the color theme used for graphs
  413. colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
  414. legend: {
  415. show: true,
  416. noColumns: 1, // number of colums in legend table
  417. labelFormatter: null, // fn: string -> string
  418. labelBoxBorderColor: "#ccc", // border color for the little label boxes
  419. container: null, // container (as jQuery object) to put legend in, null means default on top of graph
  420. position: "ne", // position of default legend container within plot
  421. margin: 5, // distance from grid edge to default legend container within plot
  422. backgroundColor: null, // null means auto-detect
  423. backgroundOpacity: 0.85, // set to 0 to avoid background
  424. sorted: null // default to no legend sorting
  425. },
  426. xaxis: {
  427. show: null, // null = auto-detect, true = always, false = never
  428. position: "bottom", // or "top"
  429. mode: null, // null or "time"
  430. font: null, // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" }
  431. color: null, // base color, labels, ticks
  432. tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
  433. transform: null, // null or f: number -> number to transform axis
  434. inverseTransform: null, // if transform is set, this should be the inverse function
  435. min: null, // min. value to show, null means set automatically
  436. max: null, // max. value to show, null means set automatically
  437. autoscaleMargin: null, // margin in % to add if auto-setting min/max
  438. ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
  439. tickFormatter: null, // fn: number -> string
  440. labelWidth: null, // size of tick labels in pixels
  441. labelHeight: null,
  442. reserveSpace: null, // whether to reserve space even if axis isn't shown
  443. tickLength: null, // size in pixels of ticks, or "full" for whole line
  444. alignTicksWithAxis: null, // axis number or null for no sync
  445. tickDecimals: null, // no. of decimals, null means auto
  446. tickSize: null, // number or [number, "unit"]
  447. minTickSize: null // number or [number, "unit"]
  448. },
  449. yaxis: {
  450. autoscaleMargin: 0.02,
  451. position: "left" // or "right"
  452. },
  453. xaxes: [],
  454. yaxes: [],
  455. series: {
  456. points: {
  457. show: false,
  458. radius: 3,
  459. lineWidth: 2, // in pixels
  460. fill: true,
  461. fillColor: "#ffffff",
  462. symbol: "circle" // or callback
  463. },
  464. lines: {
  465. // we don't put in show: false so we can see
  466. // whether lines were actively disabled
  467. lineWidth: 2, // in pixels
  468. fill: false,
  469. fillColor: null,
  470. steps: false
  471. // Omit 'zero', so we can later default its value to
  472. // match that of the 'fill' option.
  473. },
  474. bars: {
  475. show: false,
  476. lineWidth: 2, // in pixels
  477. barWidth: 1, // in units of the x axis
  478. fill: true,
  479. fillColor: null,
  480. align: "left", // "left", "right", or "center"
  481. horizontal: false,
  482. zero: true
  483. },
  484. shadowSize: 3,
  485. highlightColor: null
  486. },
  487. grid: {
  488. show: true,
  489. aboveData: false,
  490. color: "#545454", // primary color used for outline and labels
  491. backgroundColor: null, // null for transparent, else color
  492. borderColor: null, // set if different from the grid color
  493. tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)"
  494. margin: 0, // distance from the canvas edge to the grid
  495. labelMargin: 5, // in pixels
  496. axisMargin: 8, // in pixels
  497. borderWidth: 2, // in pixels
  498. minBorderMargin: null, // in pixels, null means taken from points radius
  499. markings: null, // array of ranges or fn: axes -> array of ranges
  500. markingsColor: "#f4f4f4",
  501. markingsLineWidth: 2,
  502. // interactive stuff
  503. clickable: false,
  504. hoverable: false,
  505. autoHighlight: true, // highlight in case mouse is near
  506. mouseActiveRadius: 10 // how far the mouse can be away to activate an item
  507. },
  508. interaction: {
  509. redrawOverlayInterval: 1000/60 // time between updates, -1 means in same flow
  510. },
  511. hooks: {}
  512. },
  513. surface = null, // the canvas for the plot itself
  514. overlay = null, // canvas for interactive stuff on top of plot
  515. eventHolder = null, // jQuery object that events should be bound to
  516. ctx = null, octx = null,
  517. xaxes = [], yaxes = [],
  518. plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
  519. plotWidth = 0, plotHeight = 0,
  520. hooks = {
  521. processOptions: [],
  522. processRawData: [],
  523. processDatapoints: [],
  524. processOffset: [],
  525. drawBackground: [],
  526. drawSeries: [],
  527. draw: [],
  528. bindEvents: [],
  529. drawOverlay: [],
  530. shutdown: []
  531. },
  532. plot = this;
  533. // public functions
  534. plot.setData = setData;
  535. plot.setupGrid = setupGrid;
  536. plot.draw = draw;
  537. plot.getPlaceholder = function() { return placeholder; };
  538. plot.getCanvas = function() { return surface.element; };
  539. plot.getPlotOffset = function() { return plotOffset; };
  540. plot.width = function () { return plotWidth; };
  541. plot.height = function () { return plotHeight; };
  542. plot.offset = function () {
  543. var o = eventHolder.offset();
  544. o.left += plotOffset.left;
  545. o.top += plotOffset.top;
  546. return o;
  547. };
  548. plot.getData = function () { return series; };
  549. plot.getAxes = function () {
  550. var res = {}, i;
  551. $.each(xaxes.concat(yaxes), function (_, axis) {
  552. if (axis)
  553. res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
  554. });
  555. return res;
  556. };
  557. plot.getXAxes = function () { return xaxes; };
  558. plot.getYAxes = function () { return yaxes; };
  559. plot.c2p = canvasToAxisCoords;
  560. plot.p2c = axisToCanvasCoords;
  561. plot.getOptions = function () { return options; };
  562. plot.highlight = highlight;
  563. plot.unhighlight = unhighlight;
  564. plot.triggerRedrawOverlay = triggerRedrawOverlay;
  565. plot.pointOffset = function(point) {
  566. return {
  567. left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10),
  568. top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10)
  569. };
  570. };
  571. plot.shutdown = shutdown;
  572. plot.destroy = function () {
  573. shutdown();
  574. placeholder.removeData("plot").empty();
  575. series = [];
  576. options = null;
  577. surface = null;
  578. overlay = null;
  579. eventHolder = null;
  580. ctx = null;
  581. octx = null;
  582. xaxes = [];
  583. yaxes = [];
  584. hooks = null;
  585. highlights = [];
  586. plot = null;
  587. };
  588. plot.resize = function () {
  589. var width = placeholder.width(),
  590. height = placeholder.height();
  591. surface.resize(width, height);
  592. overlay.resize(width, height);
  593. };
  594. // public attributes
  595. plot.hooks = hooks;
  596. // initialize
  597. initPlugins(plot);
  598. parseOptions(options_);
  599. setupCanvases();
  600. setData(data_);
  601. setupGrid();
  602. draw();
  603. bindEvents();
  604. function executeHooks(hook, args) {
  605. args = [plot].concat(args);
  606. for (var i = 0; i < hook.length; ++i)
  607. hook[i].apply(this, args);
  608. }
  609. function initPlugins() {
  610. // References to key classes, allowing plugins to modify them
  611. var classes = {
  612. Canvas: Canvas
  613. };
  614. for (var i = 0; i < plugins.length; ++i) {
  615. var p = plugins[i];
  616. p.init(plot, classes);
  617. if (p.options)
  618. $.extend(true, options, p.options);
  619. }
  620. }
  621. function parseOptions(opts) {
  622. $.extend(true, options, opts);
  623. // $.extend merges arrays, rather than replacing them. When less
  624. // colors are provided than the size of the default palette, we
  625. // end up with those colors plus the remaining defaults, which is
  626. // not expected behavior; avoid it by replacing them here.
  627. if (opts && opts.colors) {
  628. options.colors = opts.colors;
  629. }
  630. if (options.xaxis.color == null)
  631. options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
  632. if (options.yaxis.color == null)
  633. options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
  634. if (options.xaxis.tickColor == null) // grid.tickColor for back-compatibility
  635. options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color;
  636. if (options.yaxis.tickColor == null) // grid.tickColor for back-compatibility
  637. options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color;
  638. if (options.grid.borderColor == null)
  639. options.grid.borderColor = options.grid.color;
  640. if (options.grid.tickColor == null)
  641. options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();
  642. // Fill in defaults for axis options, including any unspecified
  643. // font-spec fields, if a font-spec was provided.
  644. // If no x/y axis options were provided, create one of each anyway,
  645. // since the rest of the code assumes that they exist.
  646. var i, axisOptions, axisCount,
  647. fontSize = placeholder.css("font-size"),
  648. fontSizeDefault = fontSize ? +fontSize.replace("px", "") : 13,
  649. fontDefaults = {
  650. style: placeholder.css("font-style"),
  651. size: Math.round(0.8 * fontSizeDefault),
  652. variant: placeholder.css("font-variant"),
  653. weight: placeholder.css("font-weight"),
  654. family: placeholder.css("font-family")
  655. };
  656. axisCount = options.xaxes.length || 1;
  657. for (i = 0; i < axisCount; ++i) {
  658. axisOptions = options.xaxes[i];
  659. if (axisOptions && !axisOptions.tickColor) {
  660. axisOptions.tickColor = axisOptions.color;
  661. }
  662. axisOptions = $.extend(true, {}, options.xaxis, axisOptions);
  663. options.xaxes[i] = axisOptions;
  664. if (axisOptions.font) {
  665. axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
  666. if (!axisOptions.font.color) {
  667. axisOptions.font.color = axisOptions.color;
  668. }
  669. if (!axisOptions.font.lineHeight) {
  670. axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
  671. }
  672. }
  673. }
  674. axisCount = options.yaxes.length || 1;
  675. for (i = 0; i < axisCount; ++i) {
  676. axisOptions = options.yaxes[i];
  677. if (axisOptions && !axisOptions.tickColor) {
  678. axisOptions.tickColor = axisOptions.color;
  679. }
  680. axisOptions = $.extend(true, {}, options.yaxis, axisOptions);
  681. options.yaxes[i] = axisOptions;
  682. if (axisOptions.font) {
  683. axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
  684. if (!axisOptions.font.color) {
  685. axisOptions.font.color = axisOptions.color;
  686. }
  687. if (!axisOptions.font.lineHeight) {
  688. axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
  689. }
  690. }
  691. }
  692. // backwards compatibility, to be removed in future
  693. if (options.xaxis.noTicks && options.xaxis.ticks == null)
  694. options.xaxis.ticks = options.xaxis.noTicks;
  695. if (options.yaxis.noTicks && options.yaxis.ticks == null)
  696. options.yaxis.ticks = options.yaxis.noTicks;
  697. if (options.x2axis) {
  698. options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
  699. options.xaxes[1].position = "top";
  700. // Override the inherit to allow the axis to auto-scale
  701. if (options.x2axis.min == null) {
  702. options.xaxes[1].min = null;
  703. }
  704. if (options.x2axis.max == null) {
  705. options.xaxes[1].max = null;
  706. }
  707. }
  708. if (options.y2axis) {
  709. options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
  710. options.yaxes[1].position = "right";
  711. // Override the inherit to allow the axis to auto-scale
  712. if (options.y2axis.min == null) {
  713. options.yaxes[1].min = null;
  714. }
  715. if (options.y2axis.max == null) {
  716. options.yaxes[1].max = null;
  717. }
  718. }
  719. if (options.grid.coloredAreas)
  720. options.grid.markings = options.grid.coloredAreas;
  721. if (options.grid.coloredAreasColor)
  722. options.grid.markingsColor = options.grid.coloredAreasColor;
  723. if (options.lines)
  724. $.extend(true, options.series.lines, options.lines);
  725. if (options.points)
  726. $.extend(true, options.series.points, options.points);
  727. if (options.bars)
  728. $.extend(true, options.series.bars, options.bars);
  729. if (options.shadowSize != null)
  730. options.series.shadowSize = options.shadowSize;
  731. if (options.highlightColor != null)
  732. options.series.highlightColor = options.highlightColor;
  733. // save options on axes for future reference
  734. for (i = 0; i < options.xaxes.length; ++i)
  735. getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
  736. for (i = 0; i < options.yaxes.length; ++i)
  737. getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];
  738. // add hooks from options
  739. for (var n in hooks)
  740. if (options.hooks[n] && options.hooks[n].length)
  741. hooks[n] = hooks[n].concat(options.hooks[n]);
  742. executeHooks(hooks.processOptions, [options]);
  743. }
  744. function setData(d) {
  745. series = parseData(d);
  746. fillInSeriesOptions();
  747. processData();
  748. }
  749. function parseData(d) {
  750. var res = [];
  751. for (var i = 0; i < d.length; ++i) {
  752. var s = $.extend(true, {}, options.series);
  753. if (d[i].data != null) {
  754. s.data = d[i].data; // move the data instead of deep-copy
  755. delete d[i].data;
  756. $.extend(true, s, d[i]);
  757. d[i].data = s.data;
  758. }
  759. else
  760. s.data = d[i];
  761. res.push(s);
  762. }
  763. return res;
  764. }
  765. function axisNumber(obj, coord) {
  766. var a = obj[coord + "axis"];
  767. if (typeof a == "object") // if we got a real axis, extract number
  768. a = a.n;
  769. if (typeof a != "number")
  770. a = 1; // default to first axis
  771. return a;
  772. }
  773. function allAxes() {
  774. // return flat array without annoying null entries
  775. return $.grep(xaxes.concat(yaxes), function (a) { return a; });
  776. }
  777. function canvasToAxisCoords(pos) {
  778. // return an object with x/y corresponding to all used axes
  779. var res = {}, i, axis;
  780. for (i = 0; i < xaxes.length; ++i) {
  781. axis = xaxes[i];
  782. if (axis && axis.used)
  783. res["x" + axis.n] = axis.c2p(pos.left);
  784. }
  785. for (i = 0; i < yaxes.length; ++i) {
  786. axis = yaxes[i];
  787. if (axis && axis.used)
  788. res["y" + axis.n] = axis.c2p(pos.top);
  789. }
  790. if (res.x1 !== undefined)
  791. res.x = res.x1;
  792. if (res.y1 !== undefined)
  793. res.y = res.y1;
  794. return res;
  795. }
  796. function axisToCanvasCoords(pos) {
  797. // get canvas coords from the first pair of x/y found in pos
  798. var res = {}, i, axis, key;
  799. for (i = 0; i < xaxes.length; ++i) {
  800. axis = xaxes[i];
  801. if (axis && axis.used) {
  802. key = "x" + axis.n;
  803. if (pos[key] == null && axis.n == 1)
  804. key = "x";
  805. if (pos[key] != null) {
  806. res.left = axis.p2c(pos[key]);
  807. break;
  808. }
  809. }
  810. }
  811. for (i = 0; i < yaxes.length; ++i) {
  812. axis = yaxes[i];
  813. if (axis && axis.used) {
  814. key = "y" + axis.n;
  815. if (pos[key] == null && axis.n == 1)
  816. key = "y";
  817. if (pos[key] != null) {
  818. res.top = axis.p2c(pos[key]);
  819. break;
  820. }
  821. }
  822. }
  823. return res;
  824. }
  825. function getOrCreateAxis(axes, number) {
  826. if (!axes[number - 1])
  827. axes[number - 1] = {
  828. n: number, // save the number for future reference
  829. direction: axes == xaxes ? "x" : "y",
  830. options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
  831. };
  832. return axes[number - 1];
  833. }
  834. function fillInSeriesOptions() {
  835. var neededColors = series.length, maxIndex = -1, i;
  836. // Subtract the number of series that already have fixed colors or
  837. // color indexes from the number that we still need to generate.
  838. for (i = 0; i < series.length; ++i) {
  839. var sc = series[i].color;
  840. if (sc != null) {
  841. neededColors--;
  842. if (typeof sc == "number" && sc > maxIndex) {
  843. maxIndex = sc;
  844. }
  845. }
  846. }
  847. // If any of the series have fixed color indexes, then we need to
  848. // generate at least as many colors as the highest index.
  849. if (neededColors <= maxIndex) {
  850. neededColors = maxIndex + 1;
  851. }
  852. // Generate all the colors, using first the option colors and then
  853. // variations on those colors once they're exhausted.
  854. var c, colors = [], colorPool = options.colors,
  855. colorPoolSize = colorPool.length, variation = 0;
  856. for (i = 0; i < neededColors; i++) {
  857. c = $.color.parse(colorPool[i % colorPoolSize] || "#666");
  858. // Each time we exhaust the colors in the pool we adjust
  859. // a scaling factor used to produce more variations on
  860. // those colors. The factor alternates negative/positive
  861. // to produce lighter/darker colors.
  862. // Reset the variation after every few cycles, or else
  863. // it will end up producing only white or black colors.
  864. if (i % colorPoolSize == 0 && i) {
  865. if (variation >= 0) {
  866. if (variation < 0.5) {
  867. variation = -variation - 0.2;
  868. } else variation = 0;
  869. } else variation = -variation;
  870. }
  871. colors[i] = c.scale('rgb', 1 + variation);
  872. }
  873. // Finalize the series options, filling in their colors
  874. var colori = 0, s;
  875. for (i = 0; i < series.length; ++i) {
  876. s = series[i];
  877. // assign colors
  878. if (s.color == null) {
  879. s.color = colors[colori].toString();
  880. ++colori;
  881. }
  882. else if (typeof s.color == "number")
  883. s.color = colors[s.color].toString();
  884. // turn on lines automatically in case nothing is set
  885. if (s.lines.show == null) {
  886. var v, show = true;
  887. for (v in s)
  888. if (s[v] && s[v].show) {
  889. show = false;
  890. break;
  891. }
  892. if (show)
  893. s.lines.show = true;
  894. }
  895. // If nothing was provided for lines.zero, default it to match
  896. // lines.fill, since areas by default should extend to zero.
  897. if (s.lines.zero == null) {
  898. s.lines.zero = !!s.lines.fill;
  899. }
  900. // setup axes
  901. s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
  902. s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
  903. }
  904. }
  905. function processData() {
  906. var topSentry = Number.POSITIVE_INFINITY,
  907. bottomSentry = Number.NEGATIVE_INFINITY,
  908. fakeInfinity = Number.MAX_VALUE,
  909. i, j, k, m, length,
  910. s, points, ps, x, y, axis, val, f, p,
  911. data, format;
  912. function updateAxis(axis, min, max) {
  913. if (min < axis.datamin && min != -fakeInfinity)
  914. axis.datamin = min;
  915. if (max > axis.datamax && max != fakeInfinity)
  916. axis.datamax = max;
  917. }
  918. $.each(allAxes(), function (_, axis) {
  919. // init axis
  920. axis.datamin = topSentry;
  921. axis.datamax = bottomSentry;
  922. axis.used = false;
  923. });
  924. for (i = 0; i < series.length; ++i) {
  925. s = series[i];
  926. s.datapoints = { points: [] };
  927. executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]);
  928. }
  929. // first pass: clean and copy data
  930. for (i = 0; i < series.length; ++i) {
  931. s = series[i];
  932. data = s.data;
  933. format = s.datapoints.format;
  934. if (!format) {
  935. format = [];
  936. // find out how to copy
  937. format.push({ x: true, number: true, required: true });
  938. format.push({ y: true, number: true, required: true });
  939. if (s.bars.show || (s.lines.show && s.lines.fill)) {
  940. var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero));
  941. format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale });
  942. if (s.bars.horizontal) {
  943. delete format[format.length - 1].y;
  944. format[format.length - 1].x = true;
  945. }
  946. }
  947. s.datapoints.format = format;
  948. }
  949. if (s.datapoints.pointsize != null)
  950. continue; // already filled in
  951. s.datapoints.pointsize = format.length;
  952. ps = s.datapoints.pointsize;
  953. points = s.datapoints.points;
  954. var insertSteps = s.lines.show && s.lines.steps;
  955. s.xaxis.used = s.yaxis.used = true;
  956. for (j = k = 0; j < data.length; ++j, k += ps) {
  957. p = data[j];
  958. var nullify = p == null;
  959. if (!nullify) {
  960. for (m = 0; m < ps; ++m) {
  961. val = p[m];
  962. f = format[m];
  963. if (f) {
  964. if (f.number && val != null) {
  965. val = +val; // convert to number
  966. if (isNaN(val))
  967. val = null;
  968. else if (val == Infinity)
  969. val = fakeInfinity;
  970. else if (val == -Infinity)
  971. val = -fakeInfinity;
  972. }
  973. if (val == null) {
  974. if (f.required)
  975. nullify = true;
  976. if (f.defaultValue != null)
  977. val = f.defaultValue;
  978. }
  979. }
  980. points[k + m] = val;
  981. }
  982. }
  983. if (nullify) {
  984. for (m = 0; m < ps; ++m) {
  985. val = points[k + m];
  986. if (val != null) {
  987. f = format[m];
  988. // extract min/max info
  989. if (f.autoscale !== false) {
  990. if (f.x) {
  991. updateAxis(s.xaxis, val, val);
  992. }
  993. if (f.y) {
  994. updateAxis(s.yaxis, val, val);
  995. }
  996. }
  997. }
  998. points[k + m] = null;
  999. }
  1000. }
  1001. else {
  1002. // a little bit of line specific stuff that
  1003. // perhaps shouldn't be here, but lacking
  1004. // better means...
  1005. if (insertSteps && k > 0
  1006. && points[k - ps] != null
  1007. && points[k - ps] != points[k]
  1008. && points[k - ps + 1] != points[k + 1]) {
  1009. // copy the point to make room for a middle point
  1010. for (m = 0; m < ps; ++m)
  1011. points[k + ps + m] = points[k + m];
  1012. // middle point has same y
  1013. points[k + 1] = points[k - ps + 1];
  1014. // we've added a point, better reflect that
  1015. k += ps;
  1016. }
  1017. }
  1018. }
  1019. }
  1020. // give the hooks a chance to run
  1021. for (i = 0; i < series.length; ++i) {
  1022. s = series[i];
  1023. executeHooks(hooks.processDatapoints, [ s, s.datapoints]);
  1024. }
  1025. // second pass: find datamax/datamin for auto-scaling
  1026. for (i = 0; i < series.length; ++i) {
  1027. s = series[i];
  1028. points = s.datapoints.points;
  1029. ps = s.datapoints.pointsize;
  1030. format = s.datapoints.format;
  1031. var xmin = topSentry, ymin = topSentry,
  1032. xmax = bottomSentry, ymax = bottomSentry;
  1033. for (j = 0; j < points.length; j += ps) {
  1034. if (points[j] == null)
  1035. continue;
  1036. for (m = 0; m < ps; ++m) {
  1037. val = points[j + m];
  1038. f = format[m];
  1039. if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity)
  1040. continue;
  1041. if (f.x) {
  1042. if (val < xmin)
  1043. xmin = val;
  1044. if (val > xmax)
  1045. xmax = val;
  1046. }
  1047. if (f.y) {
  1048. if (val < ymin)
  1049. ymin = val;
  1050. if (val > ymax)
  1051. ymax = val;
  1052. }
  1053. }
  1054. }
  1055. if (s.bars.show) {
  1056. // make sure we got room for the bar on the dancing floor
  1057. var delta;
  1058. switch (s.bars.align) {
  1059. case "left":
  1060. delta = 0;
  1061. break;
  1062. case "right":
  1063. delta = -s.bars.barWidth;
  1064. break;
  1065. default:
  1066. delta = -s.bars.barWidth / 2;
  1067. }
  1068. i