rickshaw.js 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659
  1. var Rickshaw = {
  2. namespace: function(namespace, obj) {
  3. var parts = namespace.split('.');
  4. var parent = Rickshaw;
  5. for(var i = 1, length = parts.length; i < length; i++) {
  6. currentPart = parts[i];
  7. parent[currentPart] = parent[currentPart] || {};
  8. parent = parent[currentPart];
  9. }
  10. return parent;
  11. },
  12. keys: function(obj) {
  13. var keys = [];
  14. for (var key in obj) keys.push(key);
  15. return keys;
  16. },
  17. extend: function(destination, source) {
  18. for (var property in source) {
  19. destination[property] = source[property];
  20. }
  21. return destination;
  22. }
  23. };
  24. if (typeof module !== 'undefined' && module.exports) {
  25. var d3 = require('d3');
  26. module.exports = Rickshaw;
  27. }
  28. /* Adapted from https://github.com/Jakobo/PTClass */
  29. /*
  30. Copyright (c) 2005-2010 Sam Stephenson
  31. Permission is hereby granted, free of charge, to any person obtaining a copy
  32. of this software and associated documentation files (the "Software"), to deal
  33. in the Software without restriction, including without limitation the rights
  34. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  35. copies of the Software, and to permit persons to whom the Software is
  36. furnished to do so, subject to the following conditions:
  37. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  38. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  39. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  42. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  43. SOFTWARE.
  44. */
  45. /* Based on Alex Arnell's inheritance implementation. */
  46. /** section: Language
  47. * class Class
  48. *
  49. * Manages Prototype's class-based OOP system.
  50. *
  51. * Refer to Prototype's web site for a [tutorial on classes and
  52. * inheritance](http://prototypejs.org/learn/class-inheritance).
  53. **/
  54. (function(globalContext) {
  55. /* ------------------------------------ */
  56. /* Import from object.js */
  57. /* ------------------------------------ */
  58. var _toString = Object.prototype.toString,
  59. NULL_TYPE = 'Null',
  60. UNDEFINED_TYPE = 'Undefined',
  61. BOOLEAN_TYPE = 'Boolean',
  62. NUMBER_TYPE = 'Number',
  63. STRING_TYPE = 'String',
  64. OBJECT_TYPE = 'Object',
  65. FUNCTION_CLASS = '[object Function]';
  66. function isFunction(object) {
  67. return _toString.call(object) === FUNCTION_CLASS;
  68. }
  69. function extend(destination, source) {
  70. for (var property in source) if (source.hasOwnProperty(property)) // modify protect primitive slaughter
  71. destination[property] = source[property];
  72. return destination;
  73. }
  74. function keys(object) {
  75. if (Type(object) !== OBJECT_TYPE) { throw new TypeError(); }
  76. var results = [];
  77. for (var property in object) {
  78. if (object.hasOwnProperty(property)) {
  79. results.push(property);
  80. }
  81. }
  82. return results;
  83. }
  84. function Type(o) {
  85. switch(o) {
  86. case null: return NULL_TYPE;
  87. case (void 0): return UNDEFINED_TYPE;
  88. }
  89. var type = typeof o;
  90. switch(type) {
  91. case 'boolean': return BOOLEAN_TYPE;
  92. case 'number': return NUMBER_TYPE;
  93. case 'string': return STRING_TYPE;
  94. }
  95. return OBJECT_TYPE;
  96. }
  97. function isUndefined(object) {
  98. return typeof object === "undefined";
  99. }
  100. /* ------------------------------------ */
  101. /* Import from Function.js */
  102. /* ------------------------------------ */
  103. var slice = Array.prototype.slice;
  104. function argumentNames(fn) {
  105. var names = fn.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1]
  106. .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
  107. .replace(/\s+/g, '').split(',');
  108. return names.length == 1 && !names[0] ? [] : names;
  109. }
  110. function wrap(fn, wrapper) {
  111. var __method = fn;
  112. return function() {
  113. var a = update([bind(__method, this)], arguments);
  114. return wrapper.apply(this, a);
  115. }
  116. }
  117. function update(array, args) {
  118. var arrayLength = array.length, length = args.length;
  119. while (length--) array[arrayLength + length] = args[length];
  120. return array;
  121. }
  122. function merge(array, args) {
  123. array = slice.call(array, 0);
  124. return update(array, args);
  125. }
  126. function bind(fn, context) {
  127. if (arguments.length < 2 && isUndefined(arguments[0])) return this;
  128. var __method = fn, args = slice.call(arguments, 2);
  129. return function() {
  130. var a = merge(args, arguments);
  131. return __method.apply(context, a);
  132. }
  133. }
  134. /* ------------------------------------ */
  135. /* Import from Prototype.js */
  136. /* ------------------------------------ */
  137. var emptyFunction = function(){};
  138. var Class = (function() {
  139. // Some versions of JScript fail to enumerate over properties, names of which
  140. // correspond to non-enumerable properties in the prototype chain
  141. var IS_DONTENUM_BUGGY = (function(){
  142. for (var p in { toString: 1 }) {
  143. // check actual property name, so that it works with augmented Object.prototype
  144. if (p === 'toString') return false;
  145. }
  146. return true;
  147. })();
  148. function subclass() {};
  149. function create() {
  150. var parent = null, properties = [].slice.apply(arguments);
  151. if (isFunction(properties[0]))
  152. parent = properties.shift();
  153. function klass() {
  154. this.initialize.apply(this, arguments);
  155. }
  156. extend(klass, Class.Methods);
  157. klass.superclass = parent;
  158. klass.subclasses = [];
  159. if (parent) {
  160. subclass.prototype = parent.prototype;
  161. klass.prototype = new subclass;
  162. try { parent.subclasses.push(klass) } catch(e) {}
  163. }
  164. for (var i = 0, length = properties.length; i < length; i++)
  165. klass.addMethods(properties[i]);
  166. if (!klass.prototype.initialize)
  167. klass.prototype.initialize = emptyFunction;
  168. klass.prototype.constructor = klass;
  169. return klass;
  170. }
  171. function addMethods(source) {
  172. var ancestor = this.superclass && this.superclass.prototype,
  173. properties = keys(source);
  174. // IE6 doesn't enumerate `toString` and `valueOf` (among other built-in `Object.prototype`) properties,
  175. // Force copy if they're not Object.prototype ones.
  176. // Do not copy other Object.prototype.* for performance reasons
  177. if (IS_DONTENUM_BUGGY) {
  178. if (source.toString != Object.prototype.toString)
  179. properties.push("toString");
  180. if (source.valueOf != Object.prototype.valueOf)
  181. properties.push("valueOf");
  182. }
  183. for (var i = 0, length = properties.length; i < length; i++) {
  184. var property = properties[i], value = source[property];
  185. if (ancestor && isFunction(value) &&
  186. argumentNames(value)[0] == "$super") {
  187. var method = value;
  188. value = wrap((function(m) {
  189. return function() { return ancestor[m].apply(this, arguments); };
  190. })(property), method);
  191. value.valueOf = bind(method.valueOf, method);
  192. value.toString = bind(method.toString, method);
  193. }
  194. this.prototype[property] = value;
  195. }
  196. return this;
  197. }
  198. return {
  199. create: create,
  200. Methods: {
  201. addMethods: addMethods
  202. }
  203. };
  204. })();
  205. if (globalContext.exports) {
  206. globalContext.exports.Class = Class;
  207. }
  208. else {
  209. globalContext.Class = Class;
  210. }
  211. })(Rickshaw);
  212. Rickshaw.namespace('Rickshaw.Compat.ClassList');
  213. Rickshaw.Compat.ClassList = function() {
  214. /* adapted from http://purl.eligrey.com/github/classList.js/blob/master/classList.js */
  215. if (typeof document !== "undefined" && !("classList" in document.createElement("a"))) {
  216. (function (view) {
  217. "use strict";
  218. var
  219. classListProp = "classList"
  220. , protoProp = "prototype"
  221. , elemCtrProto = (view.HTMLElement || view.Element)[protoProp]
  222. , objCtr = Object
  223. , strTrim = String[protoProp].trim || function () {
  224. return this.replace(/^\s+|\s+$/g, "");
  225. }
  226. , arrIndexOf = Array[protoProp].indexOf || function (item) {
  227. var
  228. i = 0
  229. , len = this.length
  230. ;
  231. for (; i < len; i++) {
  232. if (i in this && this[i] === item) {
  233. return i;
  234. }
  235. }
  236. return -1;
  237. }
  238. // Vendors: please allow content code to instantiate DOMExceptions
  239. , DOMEx = function (type, message) {
  240. this.name = type;
  241. this.code = DOMException[type];
  242. this.message = message;
  243. }
  244. , checkTokenAndGetIndex = function (classList, token) {
  245. if (token === "") {
  246. throw new DOMEx(
  247. "SYNTAX_ERR"
  248. , "An invalid or illegal string was specified"
  249. );
  250. }
  251. if (/\s/.test(token)) {
  252. throw new DOMEx(
  253. "INVALID_CHARACTER_ERR"
  254. , "String contains an invalid character"
  255. );
  256. }
  257. return arrIndexOf.call(classList, token);
  258. }
  259. , ClassList = function (elem) {
  260. var
  261. trimmedClasses = strTrim.call(elem.className)
  262. , classes = trimmedClasses ? trimmedClasses.split(/\s+/) : []
  263. , i = 0
  264. , len = classes.length
  265. ;
  266. for (; i < len; i++) {
  267. this.push(classes[i]);
  268. }
  269. this._updateClassName = function () {
  270. elem.className = this.toString();
  271. };
  272. }
  273. , classListProto = ClassList[protoProp] = []
  274. , classListGetter = function () {
  275. return new ClassList(this);
  276. }
  277. ;
  278. // Most DOMException implementations don't allow calling DOMException's toString()
  279. // on non-DOMExceptions. Error's toString() is sufficient here.
  280. DOMEx[protoProp] = Error[protoProp];
  281. classListProto.item = function (i) {
  282. return this[i] || null;
  283. };
  284. classListProto.contains = function (token) {
  285. token += "";
  286. return checkTokenAndGetIndex(this, token) !== -1;
  287. };
  288. classListProto.add = function (token) {
  289. token += "";
  290. if (checkTokenAndGetIndex(this, token) === -1) {
  291. this.push(token);
  292. this._updateClassName();
  293. }
  294. };
  295. classListProto.remove = function (token) {
  296. token += "";
  297. var index = checkTokenAndGetIndex(this, token);
  298. if (index !== -1) {
  299. this.splice(index, 1);
  300. this._updateClassName();
  301. }
  302. };
  303. classListProto.toggle = function (token) {
  304. token += "";
  305. if (checkTokenAndGetIndex(this, token) === -1) {
  306. this.add(token);
  307. } else {
  308. this.remove(token);
  309. }
  310. };
  311. classListProto.toString = function () {
  312. return this.join(" ");
  313. };
  314. if (objCtr.defineProperty) {
  315. var classListPropDesc = {
  316. get: classListGetter
  317. , enumerable: true
  318. , configurable: true
  319. };
  320. try {
  321. objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
  322. } catch (ex) { // IE 8 doesn't support enumerable:true
  323. if (ex.number === -0x7FF5EC54) {
  324. classListPropDesc.enumerable = false;
  325. objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
  326. }
  327. }
  328. } else if (objCtr[protoProp].__defineGetter__) {
  329. elemCtrProto.__defineGetter__(classListProp, classListGetter);
  330. }
  331. }(window));
  332. }
  333. };
  334. if ( (typeof RICKSHAW_NO_COMPAT !== "undefined" && !RICKSHAW_NO_COMPAT) || typeof RICKSHAW_NO_COMPAT === "undefined") {
  335. new Rickshaw.Compat.ClassList();
  336. }
  337. Rickshaw.namespace('Rickshaw.Graph');
  338. Rickshaw.Graph = function(args) {
  339. this.element = args.element;
  340. this.series = args.series;
  341. this.defaults = {
  342. interpolation: 'cardinal',
  343. offset: 'zero',
  344. min: undefined,
  345. max: undefined
  346. };
  347. Rickshaw.keys(this.defaults).forEach( function(k) {
  348. this[k] = args[k] || this.defaults[k];
  349. }, this );
  350. this.window = {};
  351. this.updateCallbacks = [];
  352. var self = this;
  353. this.initialize = function(args) {
  354. this.validateSeries(args.series);
  355. this.series.active = function() { return self.series.filter( function(s) { return !s.disabled } ) };
  356. this.setSize({ width: args.width, height: args.height });
  357. this.element.classList.add('rickshaw_graph');
  358. this.vis = d3.select(this.element)
  359. .append("svg:svg")
  360. .attr('width', this.width)
  361. .attr('height', this.height);
  362. var renderers = [
  363. Rickshaw.Graph.Renderer.Stack,
  364. Rickshaw.Graph.Renderer.Line,
  365. Rickshaw.Graph.Renderer.Bar,
  366. Rickshaw.Graph.Renderer.Area,
  367. Rickshaw.Graph.Renderer.ScatterPlot
  368. ];
  369. renderers.forEach( function(r) {
  370. if (!r) return;
  371. self.registerRenderer(new r( { graph: self } ));
  372. } );
  373. this.setRenderer(args.renderer || 'stack', args);
  374. this.discoverRange();
  375. };
  376. this.validateSeries = function(series) {
  377. if (!(series instanceof Array) && !(series instanceof Rickshaw.Series)) {
  378. var seriesSignature = Object.prototype.toString.apply(series);
  379. throw "series is not an array: " + seriesSignature;
  380. }
  381. var pointsCount;
  382. series.forEach( function(s) {
  383. if (!(s instanceof Object)) {
  384. throw "series element is not an object: " + s;
  385. }
  386. if (!(s.data)) {
  387. throw "series has no data: " + JSON.stringify(s);
  388. }
  389. if (!(s.data instanceof Array)) {
  390. throw "series data is not an array: " + JSON.stringify(s.data);
  391. }
  392. pointsCount = pointsCount || s.data.length;
  393. if (pointsCount && s.data.length != pointsCount) {
  394. throw "series cannot have differing numbers of points: " +
  395. pointsCount + " vs " + s.data.length + "; see Rickshaw.Series.zeroFill()";
  396. }
  397. var dataTypeX = typeof s.data[0].x;
  398. var dataTypeY = typeof s.data[0].y;
  399. if (dataTypeX != 'number' || dataTypeY != 'number') {
  400. throw "x and y properties of points should be numbers instead of " +
  401. dataTypeX + " and " + dataTypeY;
  402. }
  403. } );
  404. };
  405. this.dataDomain = function() {
  406. // take from the first series
  407. var data = this.series[0].data;
  408. return [ data[0].x, data.slice(-1).shift().x ];
  409. };
  410. this.discoverRange = function() {
  411. var domain = this.renderer.domain();
  412. this.x = d3.scale.linear().domain(domain.x).range([0, this.width]);
  413. this.y = d3.scale.linear().domain(domain.y).range([this.height, 0]);
  414. this.y.magnitude = d3.scale.linear()
  415. .domain([domain.y[0] - domain.y[0], domain.y[1] - domain.y[0]])
  416. .range([0, this.height]);
  417. };
  418. this.render = function() {
  419. var stackedData = this.stackData();
  420. this.discoverRange();
  421. this.renderer.render();
  422. this.updateCallbacks.forEach( function(callback) {
  423. callback();
  424. } );
  425. };
  426. this.update = this.render;
  427. this.stackData = function() {
  428. var data = this.series.active()
  429. .map( function(d) { return d.data } )
  430. .map( function(d) { return d.filter( function(d) { return this._slice(d) }, this ) }, this);
  431. this.stackData.hooks.data.forEach( function(entry) {
  432. data = entry.f.apply(self, [data]);
  433. } );
  434. var layout = d3.layout.stack();
  435. layout.offset( self.offset );
  436. var stackedData = layout(data);
  437. this.stackData.hooks.after.forEach( function(entry) {
  438. stackedData = entry.f.apply(self, [data]);
  439. } );
  440. var i = 0;
  441. this.series.forEach( function(series) {
  442. if (series.disabled) return;
  443. series.stack = stackedData[i++];
  444. } );
  445. this.stackedData = stackedData;
  446. return stackedData;
  447. };
  448. this.stackData.hooks = { data: [], after: [] };
  449. this._slice = function(d) {
  450. if (this.window.xMin || this.window.xMax) {
  451. var isInRange = true;
  452. if (this.window.xMin && d.x < this.window.xMin) isInRange = false;
  453. if (this.window.xMax && d.x > this.window.xMax) isInRange = false;
  454. return isInRange;
  455. }
  456. return true;
  457. };
  458. this.onUpdate = function(callback) {
  459. this.updateCallbacks.push(callback);
  460. };
  461. this.registerRenderer = function(renderer) {
  462. this._renderers = this._renderers || {};
  463. this._renderers[renderer.name] = renderer;
  464. };
  465. this.configure = function(args) {
  466. if (args.width || args.height) {
  467. this.setSize(args);
  468. }
  469. Rickshaw.keys(this.defaults).forEach( function(k) {
  470. this[k] = k in args ? args[k]
  471. : k in this ? this[k]
  472. : this.defaults[k];
  473. }, this );
  474. this.setRenderer(args.renderer || this.renderer.name, args);
  475. };
  476. this.setRenderer = function(name, args) {
  477. if (!this._renderers[name]) {
  478. throw "couldn't find renderer " + name;
  479. }
  480. this.renderer = this._renderers[name];
  481. if (typeof args == 'object') {
  482. this.renderer.configure(args);
  483. }
  484. };
  485. this.setSize = function(args) {
  486. args = args || {};
  487. if (typeof window !== undefined) {
  488. var style = window.getComputedStyle(this.element, null);
  489. var elementWidth = parseInt(style.getPropertyValue('width'));
  490. var elementHeight = parseInt(style.getPropertyValue('height'));
  491. }
  492. this.width = args.width || elementWidth || 400;
  493. this.height = args.height || elementHeight || 250;
  494. this.vis && this.vis
  495. .attr('width', this.width)
  496. .attr('height', this.height);
  497. }
  498. this.initialize(args);
  499. };
  500. Rickshaw.namespace('Rickshaw.Fixtures.Color');
  501. Rickshaw.Fixtures.Color = function() {
  502. this.schemes = {};
  503. this.schemes.spectrum14 = [
  504. '#ecb796',
  505. '#dc8f70',
  506. '#b2a470',
  507. '#92875a',
  508. '#716c49',
  509. '#d2ed82',
  510. '#bbe468',
  511. '#a1d05d',
  512. '#e7cbe6',
  513. '#d8aad6',
  514. '#a888c2',
  515. '#9dc2d3',
  516. '#649eb9',
  517. '#387aa3'
  518. ].reverse();
  519. this.schemes.spectrum2000 = [
  520. '#57306f',
  521. '#514c76',
  522. '#646583',
  523. '#738394',
  524. '#6b9c7d',
  525. '#84b665',
  526. '#a7ca50',
  527. '#bfe746',
  528. '#e2f528',
  529. '#fff726',
  530. '#ecdd00',
  531. '#d4b11d',
  532. '#de8800',
  533. '#de4800',
  534. '#c91515',
  535. '#9a0000',
  536. '#7b0429',
  537. '#580839',
  538. '#31082b'
  539. ];
  540. this.schemes.spectrum2001 = [
  541. '#2f243f',
  542. '#3c2c55',
  543. '#4a3768',
  544. '#565270',
  545. '#6b6b7c',
  546. '#72957f',
  547. '#86ad6e',
  548. '#a1bc5e',
  549. '#b8d954',
  550. '#d3e04e',
  551. '#ccad2a',
  552. '#cc8412',
  553. '#c1521d',
  554. '#ad3821',
  555. '#8a1010',
  556. '#681717',
  557. '#531e1e',
  558. '#3d1818',
  559. '#320a1b'
  560. ];
  561. this.schemes.classic9 = [
  562. '#423d4f',
  563. '#4a6860',
  564. '#848f39',
  565. '#a2b73c',
  566. '#ddcb53',
  567. '#c5a32f',
  568. '#7d5836',
  569. '#963b20',
  570. '#7c2626',
  571. '#491d37',
  572. '#2f254a'
  573. ].reverse();
  574. this.schemes.httpStatus = {
  575. 503: '#ea5029',
  576. 502: '#d23f14',
  577. 500: '#bf3613',
  578. 410: '#efacea',
  579. 409: '#e291dc',
  580. 403: '#f457e8',
  581. 408: '#e121d2',
  582. 401: '#b92dae',
  583. 405: '#f47ceb',
  584. 404: '#a82a9f',
  585. 400: '#b263c6',
  586. 301: '#6fa024',
  587. 302: '#87c32b',
  588. 307: '#a0d84c',
  589. 304: '#28b55c',
  590. 200: '#1a4f74',
  591. 206: '#27839f',
  592. 201: '#52adc9',
  593. 202: '#7c979f',
  594. 203: '#a5b8bd',
  595. 204: '#c1cdd1'
  596. };
  597. this.schemes.colorwheel = [
  598. '#b5b6a9',
  599. '#858772',
  600. '#785f43',
  601. '#96557e',
  602. '#4682b4',
  603. '#65b9ac',
  604. '#73c03a',
  605. '#cb513a'
  606. ].reverse();
  607. this.schemes.cool = [
  608. '#5e9d2f',
  609. '#73c03a',
  610. '#4682b4',
  611. '#7bc3b8',
  612. '#a9884e',
  613. '#c1b266',
  614. '#a47493',
  615. '#c09fb5'
  616. ];
  617. this.schemes.munin = [
  618. '#00cc00',
  619. '#0066b3',
  620. '#ff8000',
  621. '#ffcc00',
  622. '#330099',
  623. '#990099',
  624. '#ccff00',
  625. '#ff0000',
  626. '#808080',
  627. '#008f00',
  628. '#00487d',
  629. '#b35a00',
  630. '#b38f00',
  631. '#6b006b',
  632. '#8fb300',
  633. '#b30000',
  634. '#bebebe',
  635. '#80ff80',
  636. '#80c9ff',
  637. '#ffc080',
  638. '#ffe680',
  639. '#aa80ff',
  640. '#ee00cc',
  641. '#ff8080',
  642. '#666600',
  643. '#ffbfff',
  644. '#00ffcc',
  645. '#cc6699',
  646. '#999900'
  647. ];
  648. };
  649. Rickshaw.namespace('Rickshaw.Fixtures.RandomData');
  650. Rickshaw.Fixtures.RandomData = function(timeInterval) {
  651. var addData;
  652. timeInterval = timeInterval || 1;
  653. var lastRandomValue = 200;
  654. var timeBase = Math.floor(new Date().getTime() / 1000);
  655. this.addData = function(data) {
  656. var randomValue = Math.random() * 100 + 15 + lastRandomValue;
  657. var index = data[0].length;
  658. var counter = 1;
  659. data.forEach( function(series) {
  660. var randomVariance = Math.random() * 20;
  661. var v = randomValue / 25 + counter++
  662. + (Math.cos((index * counter * 11) / 960) + 2) * 15
  663. + (Math.cos(index / 7) + 2) * 7
  664. + (Math.cos(index / 17) + 2) * 1;
  665. series.push( { x: (index * timeInterval) + timeBase, y: v + randomVariance } );
  666. } );
  667. lastRandomValue = randomValue * .85;
  668. }
  669. };
  670. Rickshaw.namespace('Rickshaw.Fixtures.Time');
  671. Rickshaw.Fixtures.Time = function() {
  672. var tzOffset = new Date().getTimezoneOffset() * 60;
  673. var self = this;
  674. this.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  675. this.units = [
  676. {
  677. name: 'decade',
  678. seconds: 86400 * 365.25 * 10,
  679. formatter: function(d) { return (parseInt(d.getUTCFullYear() / 10) * 10) }
  680. }, {
  681. name: '5 year',
  682. seconds: 86400 * 365.25 * 5,
  683. formatter: function(d) { return (parseInt(d.getUTCFullYear() / 5) * 5) }
  684. }, {
  685. name: 'year',
  686. seconds: 86400 * 365.25,
  687. formatter: function(d) { return d.getUTCFullYear() }
  688. }, {
  689. name: '6 month',
  690. seconds: 86400 * 30.5 * 6,
  691. formatter: function(d) { return self.months[d.getUTCMonth()] }
  692. }, {
  693. name: 'month',
  694. seconds: 86400 * 30.5,
  695. formatter: function(d) { return self.months[d.getUTCMonth()] }
  696. }, {
  697. name: 'week',
  698. seconds: 86400 * 7,
  699. formatter: function(d) { return self.formatDate(d) }
  700. }, {
  701. name: '3 day',
  702. seconds: 86400 * 3,
  703. formatter: function(d) { return self.formatDate(d) }
  704. }, {
  705. name: 'day',
  706. seconds: 86400,
  707. formatter: function(d) { return d.getUTCDate() }
  708. }, {
  709. name: '6 hour',
  710. seconds: 3600 * 6,
  711. formatter: function(d) { return self.formatTime(d) }
  712. }, {
  713. name: 'hour',
  714. seconds: 3600,
  715. formatter: function(d) { return self.formatTime(d) }
  716. }, {
  717. name: '15 minute',
  718. seconds: 60 * 15,
  719. formatter: function(d) { return self.formatTime(d) }
  720. }, {
  721. name: '5 minute',
  722. seconds: 60 * 5,
  723. formatter: function(d) { return self.formatTime(d) }
  724. }, {
  725. name: 'minute',
  726. seconds: 60,
  727. formatter: function(d) { return d.getUTCMinutes() }
  728. }, {
  729. name: '15 second',
  730. seconds: 15,
  731. formatter: function(d) { return d.getUTCSeconds() + 's' }
  732. }, {
  733. name: '5 second',
  734. seconds: 5,
  735. formatter: function(d) { return d.getUTCSeconds() + 's' }
  736. }, {
  737. name: 'second',
  738. seconds: 1,
  739. formatter: function(d) { return d.getUTCSeconds() + 's' }
  740. }
  741. ];
  742. this.unit = function(unitName) {
  743. return this.units.filter( function(unit) { return unitName == unit.name } ).shift();
  744. };
  745. this.formatDate = function(d) {
  746. return d.toUTCString().match(/, (\w+ \w+ \w+)/)[1];
  747. };
  748. this.formatTime = function(d) {
  749. return d.toUTCString().match(/(\d+:\d+):/)[1];
  750. };
  751. this.ceil = function(time, unit) {
  752. if (unit.name == 'month') {
  753. var nearFuture = new Date((time + unit.seconds - 1) * 1000);
  754. var rounded = new Date(0);
  755. rounded.setUTCFullYear(nearFuture.getUTCFullYear());
  756. rounded.setUTCMonth(nearFuture.getUTCMonth());
  757. rounded.setUTCDate(1);
  758. rounded.setUTCHours(0);
  759. rounded.setUTCMinutes(0);
  760. rounded.setUTCSeconds(0);
  761. rounded.setUTCMilliseconds(0);
  762. return rounded.getTime() / 1000;
  763. }
  764. if (unit.name == 'year') {
  765. var nearFuture = new Date((time + unit.seconds - 1) * 1000);
  766. var rounded = new Date(0);
  767. rounded.setUTCFullYear(nearFuture.getUTCFullYear());
  768. rounded.setUTCMonth(0);
  769. rounded.setUTCDate(1);
  770. rounded.setUTCHours(0);
  771. rounded.setUTCMinutes(0);
  772. rounded.setUTCSeconds(0);
  773. rounded.setUTCMilliseconds(0);
  774. return rounded.getTime() / 1000;
  775. }
  776. return Math.ceil(time / unit.seconds) * unit.seconds;
  777. };
  778. };
  779. Rickshaw.namespace('Rickshaw.Fixtures.Number');
  780. Rickshaw.Fixtures.Number.formatKMBT = function(y) {
  781. if (y >= 1000000000000) { return y / 1000000000000 + "T" }
  782. else if (y >= 1000000000) { return y / 1000000000 + "B" }
  783. else if (y >= 1000000) { return y / 1000000 + "M" }
  784. else if (y >= 1000) { return y / 1000 + "K" }
  785. else if (y < 1 && y > 0) { return y.toFixed(2) }
  786. else if (y == 0) { return '' }
  787. else { return y }
  788. };
  789. Rickshaw.Fixtures.Number.formatBase1024KMGTP = function(y) {
  790. if (y >= 1125899906842624) { return y / 1125899906842624 + "P" }
  791. else if (y >= 1099511627776){ return y / 1099511627776 + "T" }
  792. else if (y >= 1073741824) { return y / 1073741824 + "G" }
  793. else if (y >= 1048576) { return y / 1048576 + "M" }
  794. else if (y >= 1024) { return y / 1024 + "K" }
  795. else if (y < 1 && y > 0) { return y.toFixed(2) }
  796. else if (y == 0) { return '' }
  797. else { return y }
  798. };
  799. Rickshaw.namespace("Rickshaw.Color.Palette");
  800. Rickshaw.Color.Palette = function(args) {
  801. var color = new Rickshaw.Fixtures.Color();
  802. args = args || {};
  803. this.schemes = {};
  804. this.scheme = color.schemes[args.scheme] || args.scheme || color.schemes.colorwheel;
  805. this.runningIndex = 0;
  806. this.generatorIndex = 0;
  807. if (args.interpolatedStopCount) {
  808. var schemeCount = this.scheme.length - 1;
  809. var i, j, scheme = [];
  810. for (i = 0; i < schemeCount; i++) {
  811. scheme.push(this.scheme[i]);
  812. var generator = d3.interpolateHsl(this.scheme[i], this.scheme[i + 1]);
  813. for (j = 1; j < args.interpolatedStopCount; j++) {
  814. scheme.push(generator((1 / args.interpolatedStopCount) * j));
  815. }
  816. }
  817. scheme.push(this.scheme[this.scheme.length - 1]);
  818. this.scheme = scheme;
  819. }
  820. this.rotateCount = this.scheme.length;
  821. this.color = function(key) {
  822. return this.scheme[key] || this.scheme[this.runningIndex++] || this.interpolateColor() || '#808080';
  823. };
  824. this.interpolateColor = function() {
  825. if (!Array.isArray(this.scheme)) return;
  826. var color;
  827. if (this.generatorIndex == this.rotateCount * 2 - 1) {
  828. color = d3.interpolateHsl(this.scheme[this.generatorIndex], this.scheme[0])(0.5);
  829. this.generatorIndex = 0;
  830. this.rotateCount *= 2;
  831. } else {
  832. color = d3.interpolateHsl(this.scheme[this.generatorIndex], this.scheme[this.generatorIndex + 1])(0.5);
  833. this.generatorIndex++;
  834. }
  835. this.scheme.push(color);
  836. return color;
  837. };
  838. };
  839. Rickshaw.namespace('Rickshaw.Graph.Ajax');
  840. Rickshaw.Graph.Ajax = Rickshaw.Class.create( {
  841. initialize: function(args) {
  842. this.dataURL = args.dataURL;
  843. this.onData = args.onData || function(d) { return d };
  844. this.onComplete = args.onComplete || function() {};
  845. this.onError = args.onError || function() {};
  846. this.args = args; // pass through to Rickshaw.Graph
  847. this.request();
  848. },
  849. request: function() {
  850. $.ajax( {
  851. url: this.dataURL,
  852. dataType: 'json',
  853. success: this.success.bind(this),
  854. error: this.error.bind(this)
  855. } );
  856. },
  857. error: function() {
  858. console.log("error loading dataURL: " + this.dataURL);
  859. this.onError(this);
  860. },
  861. success: function(data, status) {
  862. data = this.onData(data);
  863. this.args.series = this._splice({ data: data, series: this.args.series });
  864. this.graph = new Rickshaw.Graph(this.args);
  865. this.graph.render();
  866. this.onComplete(this);
  867. },
  868. _splice: function(args) {
  869. var data = args.data;
  870. var series = args.series;
  871. if (!args.series) return data;
  872. series.forEach( function(s) {
  873. var seriesKey = s.key || s.name;
  874. if (!seriesKey) throw "series needs a key or a name";
  875. data.forEach( function(d) {
  876. var dataKey = d.key || d.name;
  877. if (!dataKey) throw "data needs a key or a name";
  878. if (seriesKey == dataKey) {
  879. var properties = ['color', 'name', 'data'];
  880. properties.forEach( function(p) {
  881. s[p] = s[p] || d[p];
  882. } );
  883. }
  884. } );
  885. } );
  886. return series;
  887. }
  888. } );
  889. Rickshaw.namespace('Rickshaw.Graph.Annotate');
  890. Rickshaw.Graph.Annotate = function(args) {
  891. var graph = this.graph = args.graph;
  892. this.elements = { timeline: args.element };
  893. var self = this;
  894. this.data = {};
  895. this.elements.timeline.classList.add('rickshaw_annotation_timeline');
  896. this.add = function(time, content, end_time) {
  897. self.data[time] = self.data[time] || {'boxes': []};
  898. self.data[time].boxes.push({content: content, end: end_time});
  899. };
  900. this.update = function() {
  901. Rickshaw.keys(self.data).forEach( function(time) {
  902. var annotation = self.data[time];
  903. var left = self.graph.x(time);
  904. if (left < 0 || left > self.graph.x.range()[1]) {
  905. if (annotation.element) {
  906. annotation.line.classList.add('offscreen');
  907. annotation.element.style.display = 'none';
  908. }
  909. annotation.boxes.forEach( function(box) {
  910. if ( box.rangeElement ) box.rangeElement.classList.add('offscreen');
  911. });
  912. return;
  913. }
  914. if (!annotation.element) {
  915. var element = annotation.element = document.createElement('div');
  916. element.classList.add('annotation');
  917. this.elements.timeline.appendChild(element);
  918. element.addEventListener('click', function(e) {
  919. element.classList.toggle('active');
  920. annotation.line.classList.toggle('active');
  921. annotation.boxes.forEach( function(box) {
  922. if ( box.rangeElement ) box.rangeElement.classList.toggle('active');
  923. });
  924. }, false);
  925. }
  926. annotation.element.style.left = left + 'px';
  927. annotation.element.style.display = 'block';
  928. annotation.boxes.forEach( function(box) {
  929. var element = box.element;
  930. if (!element) {
  931. element = box.element = document.createElement('div');
  932. element.classList.add('content');
  933. element.innerHTML = box.content;
  934. annotation.element.appendChild(element);
  935. annotation.line = document.createElement('div');
  936. annotation.line.classList.add('annotation_line');
  937. self.graph.element.appendChild(annotation.line);
  938. if ( box.end ) {
  939. box.rangeElement = document.createElement('div');
  940. box.rangeElement.classList.add('annotation_range');
  941. self.graph.element.appendChild(box.rangeElement);
  942. }
  943. }
  944. if ( box.end ) {
  945. var annotationRangeStart = left;
  946. var annotationRangeEnd = Math.min( self.graph.x(box.end), self.graph.x.range()[1] );
  947. // annotation makes more sense at end
  948. if ( annotationRangeStart > annotationRangeEnd ) {
  949. annotationRangeEnd = left;
  950. annotationRangeStart = Math.max( self.graph.x(box.end), self.graph.x.range()[0] );
  951. }
  952. var annotationRangeWidth = annotationRangeEnd - annotationRangeStart;
  953. box.rangeElement.style.left = annotationRangeStart + 'px';
  954. box.rangeElement.style.width = annotationRangeWidth + 'px'
  955. box.rangeElement.classList.remove('offscreen');
  956. }
  957. annotation.line.classList.remove('offscreen');
  958. annotation.line.style.left = left + 'px';
  959. } );
  960. }, this );
  961. };
  962. this.graph.onUpdate( function() { self.update() } );
  963. };
  964. Rickshaw.namespace('Rickshaw.Graph.Axis.Time');
  965. Rickshaw.Graph.Axis.Time = function(args) {
  966. var self = this;
  967. this.graph = args.graph;
  968. this.elements = [];
  969. this.ticksTreatment = args.ticksTreatment || 'plain';
  970. this.fixedTimeUnit = args.timeUnit;
  971. var time = new Rickshaw.Fixtures.Time();
  972. this.appropriateTimeUnit = function() {
  973. var unit;
  974. var units = time.units;
  975. var domain = this.graph.x.domain();
  976. var rangeSeconds = domain[1] - domain[0];
  977. units.forEach( function(u) {
  978. if (Math.floor(rangeSeconds / u.seconds) >= 2) {
  979. unit = unit || u;
  980. }
  981. } );
  982. return (unit || time.units[time.units.length - 1]);
  983. };
  984. this.tickOffsets = function() {
  985. var domain = this.graph.x.domain();
  986. var unit = this.fixedTimeUnit || this.appropriateTimeUnit();
  987. var count = Math.ceil((domain[1] - domain[0]) / unit.seconds);
  988. var runningTick = domain[0];
  989. var offsets = [];
  990. for (var i = 0; i < count; i++) {
  991. tickValue = time.ceil(runningTick, unit);
  992. runningTick = tickValue + unit.seconds / 2;
  993. offsets.push( { value: tickValue, unit: unit } );
  994. }
  995. return offsets;
  996. };
  997. this.render = function() {
  998. this.elements.forEach( function(e) {
  999. e.parentNode.removeChild(e);
  1000. } );
  1001. this.elements = [];
  1002. var offsets = this.tickOffsets();
  1003. offsets.forEach( function(o) {
  1004. if (self.graph.x(o.value) > self.graph.x.range()[1]) return;
  1005. var element = document.createElement('div');
  1006. element.style.left = self.graph.x(o.value) + 'px';
  1007. element.classList.add('x_tick');
  1008. element.classList.add(self.ticksTreatment);
  1009. var title = document.createElement('div');
  1010. title.classList.add('title');
  1011. title.innerHTML = o.unit.formatter(new Date(o.value * 1000));
  1012. element.appendChild(title);
  1013. self.graph.element.appendChild(element);
  1014. self.elements.push(element);
  1015. } );
  1016. };
  1017. this.graph.onUpdate( function() { self.render() } );
  1018. };
  1019. Rickshaw.namespace('Rickshaw.Graph.Axis.Y');
  1020. Rickshaw.Graph.Axis.Y = function(args) {
  1021. var self = this;
  1022. var berthRate = 0.10;
  1023. this.initialize = function(args) {
  1024. this.graph = args.graph;
  1025. this.orientation = args.orientation || 'right';
  1026. var pixelsPerTick = args.pixelsPerTick || 75;
  1027. this.ticks = args.ticks || Math.floor(this.graph.height / pixelsPerTick);
  1028. this.tickSize = args.tickSize || 4;
  1029. this.ticksTreatment = args.ticksTreatment || 'plain';
  1030. if (args.element) {
  1031. this.element = args.element;
  1032. this.vis = d3.select(args.element)
  1033. .append("svg:svg")
  1034. .attr('class', 'rickshaw_graph y_axis');
  1035. this.element = this.vis[0][0];
  1036. this.element.style.position = 'relative';
  1037. this.setSize({ width: args.width, height: args.height });
  1038. } else {
  1039. this.vis = this.graph.vis;
  1040. }
  1041. this.graph.onUpdate( function() { self.render() } );
  1042. };
  1043. this.setSize = function(args) {
  1044. args = args || {};
  1045. if (!this.element) return;
  1046. if (typeof window !== 'undefined') {
  1047. var style = window.getComputedStyle(this.element.parentNode, null);
  1048. var elementWidth = parseInt(style.getPropertyValue('width'));
  1049. if (!args.auto) {
  1050. var elementHeight = parseInt(style.getPropertyValue('height'));
  1051. }
  1052. }
  1053. this.width = args.width || elementWidth || this.graph.width * berthRate;
  1054. this.height = args.height || elementHeight || this.graph.height;
  1055. this.vis
  1056. .attr('width', this.width)
  1057. .attr('height', this.height * (1 + berthRate));
  1058. var berth = this.height * berthRate;
  1059. this.element.style.top = -1 * berth + 'px';
  1060. };
  1061. this.render = function() {
  1062. if (this.graph.height !== this._renderHeight) this.setSize({ auto: true });
  1063. var axis = d3.svg.axis().scale(this.graph.y).orient(this.orientation);
  1064. axis.tickFormat( args.tickFormat || function(y) { return y } );
  1065. if (this.orientation == 'left') {
  1066. var berth = this.height * berthRate;
  1067. var transform = 'translate(' + this.width + ', ' + berth + ')';
  1068. }
  1069. if (this.element) {
  1070. this.vis.selectAll('*').remove();
  1071. }
  1072. this.vis
  1073. .append("svg:g")
  1074. .attr("class", ["y_ticks", this.ticksTreatment].join(" "))
  1075. .attr("transform", transform)
  1076. .call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(this.tickSize))
  1077. var gridSize = (this.orientation == 'right' ? 1 : -1) * this.graph.width;
  1078. this.graph.vis
  1079. .append("svg:g")
  1080. .attr("class", "y_grid")
  1081. .call(axis.ticks(this.ticks).tickSubdivide(0).tickSize(gridSize));
  1082. this._renderHeight = this.graph.height;
  1083. };
  1084. this.initialize(args);
  1085. };
  1086. Rickshaw.namespace('Rickshaw.Graph.Behavior.Series.Highlight');
  1087. Rickshaw.Graph.Behavior.Series.Highlight = function(args) {
  1088. this.graph = args.graph;
  1089. this.legend = args.legend;
  1090. var self = this;
  1091. var colorSafe = {};
  1092. this.addHighlightEvents = function (l) {
  1093. l.element.addEventListener( 'mouseover', function(e) {
  1094. self.legend.lines.forEach( function(line) {
  1095. if (l === line) return;
  1096. colorSafe[line.series.name] = colorSafe[line.series.name] || line.series.color;
  1097. line.series.color = d3.interpolateRgb(line.series.color, d3.rgb('#d8d8d8'))(0.8).toString();
  1098. } );
  1099. self.graph.update();
  1100. }, false );
  1101. l.element.addEventListener( 'mouseout', function(e) {
  1102. self.legend.lines.forEach( function(line) {
  1103. if (colorSafe[line.series.name]) {
  1104. line.series.color = colorSafe[line.series.name];
  1105. }
  1106. } );
  1107. self.graph.update();
  1108. }, false );
  1109. };
  1110. if (this.legend) {
  1111. this.legend.lines.forEach( function(l) {
  1112. self.addHighlightEvents(l);
  1113. } );
  1114. }
  1115. };
  1116. Rickshaw.namespace('Rickshaw.Graph.Behavior.Series.Order');
  1117. Rickshaw.Graph.Behavior.Series.Order = function(args) {
  1118. this.graph = args.graph;
  1119. this.legend = args.legend;
  1120. var self = this;
  1121. $(function() {
  1122. $(self.legend.list).sortable( {
  1123. containment: 'parent',
  1124. tolerance: 'pointer',
  1125. update: function( event, ui ) {
  1126. var series = [];
  1127. $(self.legend.list).find('li').each( function(index, item) {
  1128. if (!item.series) return;
  1129. series.push(item.series);
  1130. } );
  1131. for (var i = self.graph.series.length - 1; i >= 0; i--) {
  1132. self.graph.series[i] = series.shift();
  1133. }
  1134. self.graph.update();
  1135. }
  1136. } );
  1137. $(self.legend.list).disableSelection();
  1138. });
  1139. //hack to make jquery-ui sortable behave
  1140. this.graph.onUpdate( function() {
  1141. // commenting out since this breaks rendering in IE9
  1142. //var h = window.getComputedStyle(self.legend.element).height;
  1143. //self.legend.element.style.height = h;
  1144. } );
  1145. };
  1146. Rickshaw.namespace('Rickshaw.Graph.Behavior.Series.Toggle');
  1147. Rickshaw.Graph.Behavior.Series.Toggle = function(args) {
  1148. this.graph = args.graph;
  1149. this.legend = args.legend;
  1150. var self = this;
  1151. this.addAnchor = function(line) {
  1152. var anchor = document.createElement('a');
  1153. anchor.innerHTML = '&#10004;';
  1154. anchor.classList.add('action');
  1155. line.element.insertBefore(anchor, line.element.firstChild);
  1156. anchor.onclick = function(e) {
  1157. if (line.series.disabled) {
  1158. line.series.enable();
  1159. line.element.classList.remove('disabled');
  1160. } else {
  1161. line.series.disable();
  1162. line.element.classList.add('disabled');
  1163. }
  1164. }
  1165. var label = line.element.getElementsByTagName('span')[0];
  1166. label.onclick = function(e){
  1167. var disableAllOtherLines = line.series.disabled;
  1168. if ( ! disableAllOtherLines ) {
  1169. for ( var i = 0; i < self.legend.lines.length; i++ ) {
  1170. var l = self.legend.lines[i];
  1171. if ( line.series === l.series ) {
  1172. // noop
  1173. } else if ( l.series.disabled ) {
  1174. // noop
  1175. } else {
  1176. disableAllOtherLines = true;
  1177. break;
  1178. }
  1179. }
  1180. }
  1181. // show all or none
  1182. if ( disableAllOtherLines ) {
  1183. // these must happen first or else we try ( and probably fail ) to make a no line graph
  1184. line.series.enable();
  1185. line.element.classList.remove('disabled');
  1186. self.legend.lines.forEach(function(l){
  1187. if ( line.series === l.series ) {
  1188. // noop
  1189. } else {
  1190. l.series.disable();
  1191. l.element.classList.add('disabled');
  1192. }
  1193. });
  1194. } else {
  1195. self.legend.lines.forEach(function(l){
  1196. l.series.enable();
  1197. l.element.classList.remove('disabled');
  1198. });
  1199. }
  1200. };
  1201. };
  1202. if (this.legend) {
  1203. $(this.legend.list).sortable( {
  1204. start: function(event, ui) {
  1205. ui.item.bind('no.onclick',
  1206. function(event) {
  1207. event.preventDefault();
  1208. }
  1209. );
  1210. },
  1211. stop: function(event, ui) {
  1212. setTimeout(function(){
  1213. ui.item.unbind('no.onclick');
  1214. }, 250);
  1215. }
  1216. })
  1217. this.legend.lines.forEach( function(l) {
  1218. self.addAnchor(l);
  1219. } );
  1220. }
  1221. this._addBehavior = function() {
  1222. this.graph.series.forEach( function(s) {
  1223. s.disable = function() {
  1224. if (self.graph.series.length <= 1) {
  1225. throw('only one series left');
  1226. }
  1227. s.disabled = true;
  1228. self.graph.update();
  1229. };
  1230. s.enable = function() {
  1231. s.disabled = false;
  1232. self.graph.update();
  1233. };
  1234. } );
  1235. };
  1236. this._addBehavior();
  1237. this.updateBehaviour = function () { this._addBehavior() };
  1238. };
  1239. Rickshaw.namespace('Rickshaw.Graph.HoverDetail');
  1240. Rickshaw.Graph.HoverDetail = Rickshaw.Class.create({
  1241. initialize: function(args) {
  1242. var graph = this.graph = args.graph;
  1243. this.xFormatter = args.xFormatter || function(x) {
  1244. return new Date( x * 1000 ).toUTCString();
  1245. };
  1246. this.yFormatter = args.yFormatter || function(y) {
  1247. return y.toFixed(2);
  1248. };
  1249. var element = this.element = document.createElement('div');
  1250. element.className = 'detail';
  1251. this.visible = true;
  1252. graph.element.appendChild(element);
  1253. this.lastEvent = null;
  1254. this._addListeners();
  1255. this.onShow = args.onShow;
  1256. this.onHide = args.onHide;
  1257. this.onRender = args.onRender;
  1258. this.formatter = args.formatter || this.formatter;
  1259. },
  1260. formatter: function(series, x, y, formattedX, formattedY, d) {
  1261. return series.name + ':&nbsp;' + formattedY;
  1262. },
  1263. update: function(e) {
  1264. e = e || this.lastEvent;
  1265. if (!e) return;
  1266. this.lastEvent = e;
  1267. if (!e.target.nodeName.match(/^(path|svg|rect)$/)) return;
  1268. var graph = this.graph;
  1269. var eventX = e.offsetX || e.layerX;
  1270. var eventY = e.offsetY || e.layerY;
  1271. var domainX = graph.x.invert(eventX);
  1272. var stackedData = graph.stackedData;
  1273. var topSeriesData = stackedData.slice(-1).shift();
  1274. var domainIndexScale = d3.scale.linear()
  1275. .domain([topSeriesData[0].x, topSeriesData.slice(-1).shift().x])
  1276. .range([0, topSeriesData.length]);
  1277. var approximateIndex = Math.floor(domainIndexScale(domainX));
  1278. var dataIndex = Math.min(approximateIndex || 0, stackedData[0].length - 1);
  1279. for (var i = approximateIndex; i < stackedData[0].length - 1;) {
  1280. if (!stackedData[0][i] || !stackedData[0][i + 1]) {
  1281. break;
  1282. }
  1283. if (stackedData[0][i].x <= domainX && stackedData[0][i + 1].x > domainX) {
  1284. dataIndex = i;
  1285. break;
  1286. }
  1287. if (stackedData[0][i + 1] <= domainX) { i++ } else { i-- }
  1288. }
  1289. var domainX = stackedData[0][dataIndex].x;
  1290. var formattedXValue = this.xFormatter(domainX);
  1291. var graphX = graph.x(domainX);
  1292. var order = 0;
  1293. var detail = graph.series.active()
  1294. .map( function(s) { return { order: order++, series: s, name: s.name, value: s.stack[dataIndex] } } );
  1295. var activeItem;
  1296. var sortFn = function(a, b) {
  1297. return (a.value.y0 + a.value.y) - (b.value.y0 + b.value.y);
  1298. };
  1299. var domainMouseY = graph.y.magnitude.invert(graph.element.offsetHeight - eventY);
  1300. detail.sort(sortFn).forEach( function(d) {
  1301. d.formattedYValue = (this.yFormatter.constructor == Array) ?
  1302. this.yFormatter[detail.indexOf(d)](d.value.y) :
  1303. this.yFormatter(d.value.y);
  1304. d.graphX = graphX;
  1305. d.graphY = graph.y(d.value.y0 + d.value.y);
  1306. if (domainMouseY > d.value.y0 && domainMouseY < d.value.y0 + d.value.y && !activeItem) {
  1307. activeItem = d;
  1308. d.active = true;
  1309. }
  1310. }, this );
  1311. this.element.innerHTML = '';
  1312. this.element.style.left = graph.x(domainX) + 'px';
  1313. if (this.visible) {
  1314. this.render( {
  1315. detail: detail,
  1316. domainX: domainX,
  1317. formattedXValue: formattedXValue,
  1318. mouseX: eventX,
  1319. mouseY: eventY
  1320. } );
  1321. }
  1322. },
  1323. hide: function() {
  1324. this.visible = false;
  1325. this.element.classList.add('inactive');
  1326. if (typeof this.onHide == 'function') {
  1327. this.onHide();
  1328. }
  1329. },
  1330. show: function() {
  1331. this.visible = true;
  1332. this.element.classList.remove('inactive');
  1333. if (typeof this.onShow == 'function') {
  1334. this.onShow();
  1335. }
  1336. },
  1337. render: function(args) {
  1338. var detail = args.detail;
  1339. var domainX = args.domainX;
  1340. var mouseX = args.mouseX;
  1341. var mouseY = args.mouseY;
  1342. var formattedXValue = args.formattedXValue;
  1343. var xLabel = document.createElement('div');
  1344. xLabel.className = 'x_label';
  1345. xLabel.innerHTML = formattedXValue;
  1346. this.element.appendChild(xLabel);
  1347. detail.forEach( function(d) {
  1348. var item = document.createElement('div');
  1349. item.className = 'item';
  1350. item.innerHTML = this.formatter(d.series, domainX, d.value.y, formattedXValue, d.formattedYValue, d);
  1351. item.style.top = this.graph.y(d.value.y0 + d.value.y) + 'px';
  1352. this.element.appendChild(item);
  1353. var dot = document.createElement('div');
  1354. dot.className = 'dot';
  1355. dot.style.top = item.style.top;
  1356. dot.style.borderColor = d.series.color;
  1357. this.element.appendChild(dot);
  1358. if (d.active) {
  1359. item.className = 'item active';
  1360. dot.className = 'dot active';
  1361. }
  1362. }, this );
  1363. this.show();
  1364. if (typeof this.onRender == 'function') {
  1365. this.onRender(args);
  1366. }
  1367. },
  1368. _addListeners: function() {
  1369. this.graph.element.addEventListener(
  1370. 'mousemove',
  1371. function(e) {
  1372. this.visible = true;
  1373. this.update(e)
  1374. }.bind(this),
  1375. false
  1376. );
  1377. this.graph.onUpdate( function() { this.update() }.bind(this) );
  1378. this.graph.element.addEventListener(
  1379. 'mouseout',
  1380. function(e) {
  1381. if (e.relatedTarget && !(e.relatedTarget.compareDocumentPosition(this.graph.element) & Node.DOCUMENT_POSITION_CONTAINS)) {
  1382. this.hide();
  1383. }
  1384. }.bind(this),
  1385. false
  1386. );
  1387. }
  1388. });
  1389. Rickshaw.namespace('Rickshaw.Graph.JSONP');
  1390. Rickshaw.Graph.JSONP = Rickshaw.Class.create( Rickshaw.Graph.Ajax, {
  1391. request: function() {
  1392. $.ajax( {
  1393. url: this.dataURL,
  1394. dataType: 'jsonp',
  1395. success: this.success.bind(this),
  1396. error: this.error.bind(this)
  1397. } );
  1398. }
  1399. } );
  1400. Rickshaw.namespace('Rickshaw.Graph.Legend');
  1401. Rickshaw.Graph.Legend = function(args) {
  1402. var element = this.element = args.element;
  1403. var graph = this.graph = args.graph;
  1404. var self = this;
  1405. element.classList.add('rickshaw_legend');
  1406. var list = this.list = document.createElement('ul');
  1407. element.appendChild(list);
  1408. var series = graph.series
  1409. .map( function(s) { return s } )
  1410. .reverse();
  1411. this.lines = [];
  1412. this.addLine = function (series) {
  1413. var line = document.createElement('li');
  1414. line.className = 'line';
  1415. var swatch = document.createElement('div');
  1416. swatch.className = 'swatch';
  1417. swatch.style.backgroundColor = series.color;
  1418. line.appendChild(swatch);
  1419. var label = document.createElement('span');
  1420. label.className = 'label';
  1421. label.innerHTML = series.name;
  1422. line.appendChild(label);
  1423. list.appendChild(line);
  1424. line.series = series;
  1425. if (series.noLegend) {
  1426. line.style.display = 'none';
  1427. }
  1428. var _line = { element: line, series: series };
  1429. if (self.shelving) {
  1430. self.shelving.addAnchor(_line);
  1431. self.shelving.updateBehaviour();
  1432. }
  1433. if (self.highlighter) {
  1434. self.highlighter.addHighlightEvents(_line);
  1435. }
  1436. self.lines.push(_line);
  1437. };
  1438. series.forEach( function(s) {
  1439. self.addLine(s);
  1440. } );
  1441. graph.onUpdate( function() {} );
  1442. };
  1443. Rickshaw.namespace('Rickshaw.Graph.RangeSlider');
  1444. Rickshaw.Graph.RangeSlider = function(args) {
  1445. var element = this.element = args.element;
  1446. var graph = this.graph = args.graph;
  1447. $( function() {
  1448. $(element).slider( {
  1449. range: true,
  1450. min: graph.dataDomain()[0],
  1451. max: graph.dataDomain()[1],
  1452. values: [
  1453. graph.dataDomain()[0],
  1454. graph.dataDomain()[1]
  1455. ],
  1456. slide: function( event, ui ) {
  1457. graph.window.xMin = ui.values[0];
  1458. graph.window.xMax = ui.values[1];
  1459. graph.update();
  1460. // if we're at an extreme, stick there
  1461. if (graph.dataDomain()[0] == ui.values[0]) {
  1462. graph.window.xMin = undefined;
  1463. }
  1464. if (graph.dataDomain()[1] == ui.values[1]) {
  1465. graph.window.xMax = undefined;
  1466. }
  1467. }
  1468. } );
  1469. } );
  1470. element[0].style.width = graph.width + 'px';
  1471. graph.onUpdate( function() {
  1472. var values = $(element).slider('option', 'values');
  1473. $(element).slider('option', 'min', graph.dataDomain()[0]);
  1474. $(element).slider('option', 'max', graph.dataDomain()[1]);
  1475. if (graph.window.xMin == undefined) {
  1476. values[0] = graph.dataDomain()[0];
  1477. }
  1478. if (graph.window.xMax == undefined) {
  1479. values[1] = graph.dataDomain()[1];
  1480. }
  1481. $(element).slider('option', 'values', values);
  1482. } );
  1483. };
  1484. Rickshaw.namespace("Rickshaw.Graph.Renderer");
  1485. Rickshaw.Graph.Renderer = Rickshaw.Class.create( {
  1486. initialize: function(args) {
  1487. this.graph = args.graph;
  1488. this.tension = args.tension || this.tension;
  1489. this.graph.unstacker = this.graph.unstacker || new Rickshaw.Graph.Unstacker( { graph: this.graph } );
  1490. this.configure(args);
  1491. },
  1492. seriesPathFactory: function() {
  1493. //implement in subclass
  1494. },
  1495. seriesStrokeFactory: function() {
  1496. // implement in subclass
  1497. },
  1498. defaults: function() {
  1499. return {
  1500. tension: 0.8,
  1501. strokeWidth: 2,
  1502. unstack: true,
  1503. padding: { top: 0.01, right: 0, bottom: 0.01, left: 0 },
  1504. stroke: false,
  1505. fill: false
  1506. };
  1507. },
  1508. domain: function() {
  1509. var values = [];
  1510. var stackedData = this.graph.stackedData || this.graph.stackData();
  1511. var topSeriesData = this.unstack ? stackedData : [ stackedData.slice(-1).shift() ];
  1512. topSeriesData.forEach( function(series) {
  1513. series.forEach( function(d) {
  1514. values.push( d.y + d.y0 );
  1515. } );
  1516. } );
  1517. var xMin = stackedData[0][0].x;
  1518. var xMax = stackedData[0][ stackedData[0].length - 1 ].x;
  1519. xMin -= (xMax - xMin) * this.padding.left;
  1520. xMax += (xMax - xMin) * this.padding.right;
  1521. var yMin = this.graph.min === 'auto' ? d3.min( values ) : this.graph.min || 0;
  1522. var yMax = this.graph.max || d3.max( values );
  1523. if (this.graph.min === 'auto' || yMin < 0) {
  1524. yMin -= (yMax - yMin) * this.padding.bottom;
  1525. }
  1526. if (this.graph.max === undefined) {
  1527. yMax += (yMax - yMin) * this.padding.top;
  1528. }
  1529. return { x: [xMin, xMax], y: [yMin, yMax] };
  1530. },
  1531. render: function() {
  1532. var graph = this.graph;
  1533. graph.vis.selectAll('*').remove();
  1534. var nodes = graph.vis.selectAll("path")
  1535. .data(this.graph.stackedData)
  1536. .enter().append("svg:path")
  1537. .attr("d", this.seriesPathFactory());
  1538. var i = 0;
  1539. graph.series.forEach( function(series) {
  1540. if (series.disabled) return;
  1541. series.path = nodes[0][i++];
  1542. this._styleSeries(series);
  1543. }, this );
  1544. },
  1545. _styleSeries: function(series) {
  1546. var fill = this.fill ? series.color : 'none';
  1547. var stroke = this.stroke ? series.color : 'none';
  1548. series.path.setAttribute('fill', fill);
  1549. series.path.setAttribute('stroke', stroke);
  1550. series.path.setAttribute('stroke-width', this.strokeWidth);
  1551. series.path.setAttribute('class', series.className);
  1552. },
  1553. configure: function(args) {
  1554. args = args || {};
  1555. Rickshaw.keys(this.defaults()).forEach( function(key) {
  1556. if (!args.hasOwnProperty(key)) {
  1557. this[key] = this[key] || this.graph[key] || this.defaults()[key];
  1558. return;
  1559. }
  1560. if (typeof this.defaults()[key] == 'object') {
  1561. Rickshaw.keys(this.defaults()[key]).forEach( function(k) {
  1562. this[key][k] =
  1563. args[key][k] !== undefined ? args[key][k] :
  1564. this[key][k] !== undefined ? this[key][k] :
  1565. this.defaults()[key][k];
  1566. }, this );
  1567. } else {
  1568. this[key] =
  1569. args[key] !== undefined ? args[key] :
  1570. this[key] !== undefined ? this[key] :
  1571. this.graph[key] !== undefined ? this.graph[key] :
  1572. this.defaults()[key];
  1573. }
  1574. }, this );
  1575. },
  1576. setStrokeWidth: function(strokeWidth) {
  1577. if (strokeWidth !== undefined) {
  1578. this.strokeWidth = strokeWidth;
  1579. }
  1580. },
  1581. setTension: function(tension) {
  1582. if (tension !== undefined) {
  1583. this.tension = tension;
  1584. }
  1585. }
  1586. } );
  1587. Rickshaw.namespace('Rickshaw.Graph.Renderer.Line');
  1588. Rickshaw.Graph.Renderer.Line = Rickshaw.Class.create( Rickshaw.Graph.Renderer, {
  1589. name: 'line',
  1590. defaults: function($super) {
  1591. return Rickshaw.extend( $super(), {
  1592. unstack: true,
  1593. fill: false,
  1594. stroke: true
  1595. } );
  1596. },
  1597. seriesPathFactory: function() {
  1598. var graph = this.graph;
  1599. return d3.svg.line()
  1600. .x( function(d) { return graph.x(d.x) } )
  1601. .y( function(d) { return graph.y(d.y) } )
  1602. .interpolate(this.graph.interpolation).tension(this.tension);
  1603. }
  1604. } );
  1605. Rickshaw.namespace('Rickshaw.Graph.Renderer.Stack');
  1606. Rickshaw.Graph.Renderer.Stack = Rickshaw.Class.create( Rickshaw.Graph.Renderer, {
  1607. name: 'stack',
  1608. defaults: function($super) {
  1609. return Rickshaw.extend( $super(), {
  1610. fill: true,
  1611. stroke: false,
  1612. unstack: false
  1613. } );
  1614. },
  1615. seriesPathFactory: function() {
  1616. var graph = this.graph;
  1617. return d3.svg.area()
  1618. .x( function(d) { return graph.x(d.x) } )
  1619. .y0( function(d) { return graph.y(d.y0) } )
  1620. .y1( function(d) { return graph.y(d.y + d.y0) } )
  1621. .interpolate(this.graph.interpolation).tension(this.tension);
  1622. }
  1623. } );
  1624. Rickshaw.namespace('Rickshaw.Graph.Renderer.Bar');
  1625. Rickshaw.Graph.Renderer.Bar = Rickshaw.Class.create( Rickshaw.Graph.Renderer, {
  1626. name: 'bar',
  1627. defaults: function($super) {
  1628. var defaults = Rickshaw.extend( $super(), {
  1629. gapSize: 0.05,
  1630. unstack: false
  1631. } );
  1632. delete defaults.tension;
  1633. return defaults;
  1634. },
  1635. initialize: function($super, args) {
  1636. args = args || {};
  1637. this.gapSize = args.gapSize || this.gapSize;
  1638. $super(args);
  1639. },
  1640. domain: function($super) {
  1641. var domain = $super();
  1642. var frequentInterval = this._frequentInterval();
  1643. domain.x[1] += parseInt(frequentInterval.magnitude);
  1644. return domain;
  1645. },
  1646. barWidth: function() {
  1647. var stackedData = this.graph.stackedData || this.graph.stackData();
  1648. var data = stackedData.slice(-1).shift();
  1649. var frequentInterval = this._frequentInterval();
  1650. var barWidth = this.graph.x(data[0].x + frequentInterval.magnitude * (1 - this.gapSize));
  1651. return barWidth;
  1652. },
  1653. render: function() {
  1654. var graph = this.graph;
  1655. graph.vis.selectAll('*').remove();
  1656. var barWidth = this.barWidth();
  1657. var barXOffset = 0;
  1658. var activeSeriesCount = graph.series.filter( function(s) { return !s.disabled; } ).length;
  1659. var seriesBarWidth = this.unstack ? barWidth / activeSeriesCount : barWidth;
  1660. var transform = function(d) {
  1661. // add a matrix transform for negative values
  1662. var matrix = [ 1, 0, 0, (d.y < 0 ? -1 : 1), 0, (d.y < 0 ? graph.y.magnitude(Math.abs(d.y)) * 2 : 0) ];
  1663. return "matrix(" + matrix.join(',') + ")";
  1664. };
  1665. graph.series.forEach( function(series) {
  1666. if (series.disabled) return;
  1667. var nodes = graph.vis.selectAll("path")
  1668. .data(series.stack)
  1669. .enter().append("svg:rect")
  1670. .attr("x", function(d) { return graph.x(d.x) + barXOffset })
  1671. .attr("y", function(d) { return (graph.y(d.y0 + Math.abs(d.y))) * (d.y < 0 ? -1 : 1 ) })
  1672. .attr("width", seriesBarWidth)
  1673. .attr("height", function(d) { return graph.y.magnitude(Math.abs(d.y)) })
  1674. .attr("transform", transform);
  1675. Array.prototype.forEach.call(nodes[0], function(n) {
  1676. n.setAttribute('fill', series.color);
  1677. } );
  1678. if (this.unstack) barXOffset += seriesBarWidth;
  1679. }, this );
  1680. },
  1681. _frequentInterval: function() {
  1682. var stackedData = this.graph.stackedData || this.graph.stackData();
  1683. var data = stackedData.slice(-1).shift();
  1684. var intervalCounts = {};
  1685. for (var i = 0; i < data.length - 1; i++) {
  1686. var interval = data[i + 1].x - data[i].x;
  1687. intervalCounts[interval] = intervalCounts[interval] || 0;
  1688. intervalCounts[interval]++;
  1689. }
  1690. var frequentInterval = { count: 0 };
  1691. Rickshaw.keys(intervalCounts).forEach( function(i) {
  1692. if (frequentInterval.count < intervalCounts[i]) {
  1693. frequentInterval = {
  1694. count: intervalCounts[i],
  1695. magnitude: i
  1696. };
  1697. }
  1698. } );
  1699. this._frequentInterval = function() { return frequentInterval };
  1700. return frequentInterval;
  1701. }
  1702. } );
  1703. Rickshaw.namespace('Rickshaw.Graph.Renderer.Area');
  1704. Rickshaw.Graph.Renderer.Area = Rickshaw.Class.create( Rickshaw.Graph.Renderer, {
  1705. name: 'area',
  1706. defaults: function($super) {
  1707. return Rickshaw.extend( $super(), {
  1708. unstack: false,
  1709. fill: false,
  1710. stroke: false
  1711. } );
  1712. },
  1713. seriesPathFactory: function() {
  1714. var graph = this.graph;
  1715. return d3.svg.area()
  1716. .x( function(d) { return graph.x(d.x) } )
  1717. .y0( function(d) { return graph.y(d.y0) } )
  1718. .y1( function(d) { return graph.y(d.y + d.y0) } )
  1719. .interpolate(graph.interpolation).tension(this.tension);
  1720. },
  1721. seriesStrokeFactory: function() {
  1722. var graph = this.graph;
  1723. return d3.svg.line()
  1724. .x( function(d) { return graph.x(d.x) } )
  1725. .y( function(d) { return graph.y(d.y + d.y0) } )
  1726. .interpolate(graph.interpolation).tension(this.tension);
  1727. },
  1728. render: function() {
  1729. var graph = this.graph;
  1730. graph.vis.selectAll('*').remove();
  1731. var nodes = graph.vis.selectAll("path")
  1732. .data(this.graph.stackedData)
  1733. .enter().insert("svg:g", 'g');
  1734. nodes.append("svg:path")
  1735. .attr("d", this.seriesPathFactory())
  1736. .attr("class", 'area');
  1737. if (this.stroke) {
  1738. nodes.append("svg:path")
  1739. .attr("d", this.seriesStrokeFactory())
  1740. .attr("class", 'line');
  1741. }
  1742. var i = 0;
  1743. graph.series.forEach( function(series) {
  1744. if (series.disabled) return;
  1745. series.path = nodes[0][i++];
  1746. this._styleSeries(series);
  1747. }, this );
  1748. },
  1749. _styleSeries: function(series) {
  1750. if (!series.path) return;
  1751. d3.select(series.path).select('.area')
  1752. .attr('fill', series.color);
  1753. if (this.stroke) {
  1754. d3.select(series.path).select('.line')
  1755. .attr('fill', 'none')
  1756. .attr('stroke', series.stroke || d3.interpolateRgb(series.color, 'black')(0.125))
  1757. .attr('stroke-width', this.strokeWidth);
  1758. }
  1759. if (series.className) {
  1760. series.path.setAttribute('class', series.className);
  1761. }
  1762. }
  1763. } );
  1764. Rickshaw.namespace('Rickshaw.Graph.Renderer.ScatterPlot');
  1765. Rickshaw.Graph.Renderer.ScatterPlot = Rickshaw.Class.create( Rickshaw.Graph.Renderer, {
  1766. name: 'scatterplot',
  1767. defaults: function($super) {
  1768. return Rickshaw.extend( $super(), {
  1769. unstack: true,
  1770. fill: true,
  1771. stroke: false,
  1772. padding:{ top: 0.01, right: 0.01, bottom: 0.01, left: 0.01 },
  1773. dotSize: 4
  1774. } );
  1775. },
  1776. initialize: function($super, args) {
  1777. $super(args);
  1778. },
  1779. render: function() {
  1780. var graph = this.graph;
  1781. graph.vis.selectAll('*').remove();
  1782. graph.series.forEach( function(series) {
  1783. if (series.disabled) return;
  1784. var nodes = graph.vis.selectAll("path")
  1785. .data(series.stack)
  1786. .enter().append("svg:circle")
  1787. .attr("cx", function(d) { return graph.x(d.x) })
  1788. .attr("cy", function(d) { return graph.y(d.y) })
  1789. .attr("r", function(d) { return ("r" in d) ? d.r : graph.renderer.dotSize});
  1790. Array.prototype.forEach.call(nodes[0], function(n) {
  1791. n.setAttribute('fill', series.color);
  1792. } );
  1793. }, this );
  1794. }
  1795. } );
  1796. Rickshaw.namespace('Rickshaw.Graph.Smoother');
  1797. Rickshaw.Graph.Smoother = function(args) {
  1798. this.graph = args.graph;
  1799. this.element = args.element;
  1800. var self = this;
  1801. this.aggregationScale = 1;
  1802. if (this.element) {
  1803. $( function() {
  1804. $(self.element).slider( {
  1805. min: 1,
  1806. max: 100,
  1807. slide: function( event, ui ) {
  1808. self.setScale(ui.value);
  1809. self.graph.update();
  1810. }
  1811. } );
  1812. } );
  1813. }
  1814. self.graph.stackData.hooks.data.push( {
  1815. name: 'smoother',
  1816. orderPosition: 50,
  1817. f: function(data) {
  1818. var aggregatedData = [];
  1819. data.forEach( function(seriesData) {
  1820. var aggregatedSeriesData = [];
  1821. while (seriesData.length) {
  1822. var avgX = 0, avgY = 0;
  1823. var slice = seriesData.splice(0, self.aggregationScale);
  1824. slice.forEach( function(d) {
  1825. avgX += d.x / slice.length;
  1826. avgY += d.y / slice.length;
  1827. } );
  1828. aggregatedSeriesData.push( { x: avgX, y: avgY } );
  1829. }
  1830. aggregatedData.push(aggregatedSeriesData);
  1831. } );
  1832. return aggregatedData;
  1833. }
  1834. } );
  1835. this.setScale = function(scale) {
  1836. if (scale < 1) {
  1837. throw "scale out of range: " + scale;
  1838. }
  1839. this.aggregationScale = scale;
  1840. this.graph.update();
  1841. }
  1842. };
  1843. Rickshaw.namespace('Rickshaw.Graph.Unstacker');
  1844. Rickshaw.Graph.Unstacker = function(args) {
  1845. this.graph = args.graph;
  1846. var self = this;
  1847. this.graph.stackData.hooks.after.push( {
  1848. name: 'unstacker',
  1849. f: function(data) {
  1850. if (!self.graph.renderer.unstack) return data;
  1851. data.forEach( function(seriesData) {
  1852. seriesData.forEach( function(d) {
  1853. d.y0 = 0;
  1854. } );
  1855. } );
  1856. return data;
  1857. }
  1858. } );
  1859. };
  1860. Rickshaw.namespace('Rickshaw.Series');
  1861. Rickshaw.Series = Rickshaw.Class.create( Array, {
  1862. initialize: function (data, palette, options) {
  1863. options = options || {}
  1864. this.palette = new Rickshaw.Color.Palette(palette);
  1865. this.timeBase = typeof(options.timeBase) === 'undefined' ?
  1866. Math.floor(new Date().getTime() / 1000) :
  1867. options.timeBase;
  1868. var timeInterval = typeof(options.timeInterval) == 'undefined' ?
  1869. 1000 :
  1870. options.timeInterval;
  1871. this.setTimeInterval(timeInterval);
  1872. if (data && (typeof(data) == "object") && (data instanceof Array)) {
  1873. data.forEach( function(item) { this.addItem(item) }, this );
  1874. }
  1875. },
  1876. addItem: function(item) {
  1877. if (typeof(item.name) === 'undefined') {
  1878. throw('addItem() needs a name');
  1879. }
  1880. item.color = (item.color || this.palette.color(item.name));
  1881. item.data = (item.data || []);
  1882. // backfill, if necessary
  1883. if ((item.data.length == 0) && this.length && (this.getIndex() > 0)) {
  1884. this[0].data.forEach( function(plot) {
  1885. item.data.push({ x: plot.x, y: 0 });
  1886. } );
  1887. } else if (item.data.length == 0) {
  1888. item.data.push({ x: this.timeBase - (this.timeInterval || 0), y: 0 });
  1889. }
  1890. this.push(item);
  1891. if (this.legend) {
  1892. this.legend.addLine(this.itemByName(item.name));
  1893. }
  1894. },
  1895. addData: function(data) {
  1896. var index = this.getIndex();
  1897. Rickshaw.keys(data).forEach( function(name) {
  1898. if (! this.itemByName(name)) {
  1899. this.addItem({ name: name });
  1900. }
  1901. }, this );
  1902. this.forEach( function(item) {
  1903. item.data.push({
  1904. x: (index * this.timeInterval || 1) + this.timeBase,
  1905. y: (data[item.name] || 0)
  1906. });
  1907. }, this );
  1908. },
  1909. getIndex: function () {
  1910. return (this[0] && this[0].data && this[0].data.length) ? this[0].data.length : 0;
  1911. },
  1912. itemByName: function(name) {
  1913. for (var i = 0; i < this.length; i++) {
  1914. if (this[i].name == name)
  1915. return this[i];
  1916. }
  1917. },
  1918. setTimeInterval: function(iv) {
  1919. this.timeInterval = iv / 1000;
  1920. },
  1921. setTimeBase: function (t) {
  1922. this.timeBase = t;
  1923. },
  1924. dump: function() {
  1925. var data = {
  1926. timeBase: this.timeBase,
  1927. timeInterval: this.timeInterval,
  1928. items: []
  1929. };
  1930. this.forEach( function(item) {
  1931. var newItem = {
  1932. color: item.color,
  1933. name: item.name,
  1934. data: []
  1935. };
  1936. item.data.forEach( function(plot) {
  1937. newItem.data.push({ x: plot.x, y: plot.y });
  1938. } );
  1939. data.items.push(newItem);
  1940. } );
  1941. return data;
  1942. },
  1943. load: function(data) {
  1944. if (data.timeInterval) {
  1945. this.timeInterval = data.timeInterval;
  1946. }
  1947. if (data.timeBase) {
  1948. this.timeBase = data.timeBase;
  1949. }
  1950. if (data.items) {
  1951. data.items.forEach( function(item) {
  1952. this.push(item);
  1953. if (this.legend) {
  1954. this.legend.addLine(this.itemByName(item.name));
  1955. }
  1956. }, this );
  1957. }
  1958. }
  1959. } );
  1960. Rickshaw.Series.zeroFill = function(series) {
  1961. var x;
  1962. var i = 0;
  1963. var data = series.map( function(s) { return s.data } );
  1964. while ( i < Math.max.apply(null, data.map( function(d) { return d.length } )) ) {
  1965. x = Math.min.apply( null,
  1966. data
  1967. .filter(function(d) { return d[i] })
  1968. .map(function(d) { return d[i].x })
  1969. );
  1970. data.forEach( function(d) {
  1971. if (!d[i] || d[i].x != x) {
  1972. d.splice(i, 0, { x: x, y: 0 });
  1973. }
  1974. } );
  1975. i++;
  1976. }
  1977. };
  1978. Rickshaw.namespace('Rickshaw.Series.FixedDuration');
  1979. Rickshaw.Series.FixedDuration = Rickshaw.Class.create(Rickshaw.Series, {
  1980. initialize: function (data, palette, options) {
  1981. var options = options || {}
  1982. if (typeof(options.timeInterval) === 'undefined') {
  1983. throw new Error('FixedDuration series requires timeInterval');
  1984. }
  1985. if (typeof(options.maxDataPoints) === 'undefined') {
  1986. throw new Error('FixedDuration series requires maxDataPoints');
  1987. }
  1988. this.palette = new Rickshaw.Color.Palette(palette);
  1989. this.timeBase = typeof(options.timeBase) === 'undefined' ? Math.floor(new Date().getTime() / 1000) : options.timeBase;
  1990. this.setTimeInterval(options.timeInterval);
  1991. if (this[0] && this[0].data && this[0].data.length) {
  1992. this.currentSize = this[0].data.length;
  1993. this.currentIndex = this[0].data.length;
  1994. } else {
  1995. this.currentSize = 0;
  1996. this.currentIndex = 0;
  1997. }
  1998. this.maxDataPoints = options.maxDataPoints;
  1999. if (data && (typeof(data) == "object") && (data instanceof Array)) {
  2000. data.forEach( function (item) { this.addItem(item) }, this );
  2001. this.currentSize += 1;
  2002. this.currentIndex += 1;
  2003. }
  2004. // reset timeBase for zero-filled values if needed
  2005. this.timeBase -= (this.maxDataPoints - this.currentSize) * this.timeInterval;
  2006. // zero-fill up to maxDataPoints size if we don't have that much data yet
  2007. if ((typeof(this.maxDataPoints) !== 'undefined') && (this.currentSize < this.maxDataPoints)) {
  2008. for (var i = this.maxDataPoints - this.currentSize - 1; i > 0; i--) {
  2009. this.currentSize += 1;
  2010. this.currentIndex += 1;
  2011. this.forEach( function (item) {
  2012. item.data.unshift({ x: ((i-1) * this.timeInterval || 1) + this.timeBase, y: 0, i: i });
  2013. }, this );
  2014. }
  2015. }
  2016. },
  2017. addData: function($super, data) {
  2018. $super(data)
  2019. this.currentSize += 1;
  2020. this.currentIndex += 1;
  2021. if (this.maxDataPoints !== undefined) {
  2022. while (this.currentSize > this.maxDataPoints) {
  2023. this.dropData();
  2024. }
  2025. }
  2026. },
  2027. dropData: function() {
  2028. this.forEach(function(item) {
  2029. item.data.splice(0, 1);
  2030. } );
  2031. this.currentSize -= 1;
  2032. },
  2033. getIndex: function () {
  2034. return this.currentIndex;
  2035. }
  2036. } );