jquery.flot.events.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. /**
  2. * Flot plugin for adding 'events' to the plot.
  3. *
  4. * Events are small icons drawn onto the graph that represent something happening at that time.
  5. *
  6. * This plugin adds the following options to flot:
  7. *
  8. * options = {
  9. * events: {
  10. * levels: int // number of hierarchy levels
  11. * data: [], // array of event objects
  12. * types: [] // array of icons
  13. * xaxis: int // the x axis to attach events to
  14. * }
  15. * };
  16. *
  17. *
  18. * An event is a javascript object in the following form:
  19. *
  20. * {
  21. * min: startTime,
  22. * max: endTime,
  23. * eventType: "type",
  24. * title: "event title",
  25. * description: "event description"
  26. * }
  27. *
  28. * Types is an array of javascript objects in the following form:
  29. *
  30. * types: [
  31. * {
  32. * eventType: "eventType",
  33. * level: hierarchicalLevel,
  34. * icon: {
  35. image: "eventImage1.png",
  36. * width: 10,
  37. * height: 10
  38. * }
  39. * }
  40. * ]
  41. *
  42. * @author Joel Oughton
  43. */
  44. (function($){
  45. function init(plot){
  46. var DEFAULT_ICON = {
  47. icon: "icon-caret-up",
  48. size: 20,
  49. width: 19,
  50. height: 10
  51. };
  52. var _events = [], _types, _eventsEnabled = false;
  53. plot.getEvents = function(){
  54. return _events;
  55. };
  56. plot.hideEvents = function(levelRange){
  57. $.each(_events, function(index, event){
  58. if (_withinHierarchy(event.level(), levelRange)) {
  59. event.visual().getObject().hide();
  60. }
  61. });
  62. };
  63. plot.showEvents = function(levelRange){
  64. plot.hideEvents();
  65. $.each(_events, function(index, event){
  66. if (!_withinHierarchy(event.level(), levelRange)) {
  67. event.hide();
  68. }
  69. });
  70. _drawEvents();
  71. };
  72. plot.hooks.processOptions.push(function(plot, options){
  73. // enable the plugin
  74. if (options.events.data != null) {
  75. _eventsEnabled = true;
  76. }
  77. });
  78. plot.hooks.draw.push(function(plot, canvascontext){
  79. var options = plot.getOptions();
  80. var xaxis = plot.getXAxes()[options.events.xaxis - 1];
  81. if (_eventsEnabled) {
  82. // check for first run
  83. if (_events.length < 1) {
  84. // check for clustering
  85. if (options.events.clustering) {
  86. var ed = _clusterEvents(options.events.types, options.events.data, xaxis.max - xaxis.min);
  87. _types = ed.types;
  88. _setupEvents(ed.data);
  89. } else {
  90. _types = options.events.types;
  91. _setupEvents(options.events.data);
  92. }
  93. } else {
  94. /*if (options.events.clustering) {
  95. _clearEvents();
  96. var ed = _clusterEvents(options.events.types, options.events.data, xaxis.max - xaxis.min);
  97. _types = ed.types;
  98. _setupEvents(ed.data);
  99. }*/
  100. _updateEvents();
  101. }
  102. }
  103. _drawEvents();
  104. });
  105. var _drawEvents = function() {
  106. var o = plot.getPlotOffset();
  107. var pleft = o.left, pright = plot.width() - o.right;
  108. $.each(_events, function(index, event){
  109. // check event is inside the graph range and inside the hierarchy level
  110. if (_insidePlot(event.getOptions().min) &&
  111. !event.isHidden()) {
  112. event.visual().draw();
  113. } else {
  114. event.visual().getObject().hide();
  115. }
  116. });
  117. _identicalStarts();
  118. _overlaps();
  119. };
  120. var _withinHierarchy = function(level, levelRange){
  121. var range = {};
  122. if (!levelRange) {
  123. range.start = 0;
  124. range.end = _events.length - 1;
  125. } else {
  126. range.start = (levelRange.min == undefined) ? 0 : levelRange.min;
  127. range.end = (levelRange.max == undefined) ? _events.length - 1 : levelRange.max;
  128. }
  129. if (level >= range.start && level <= range.end) {
  130. return true;
  131. }
  132. return false;
  133. };
  134. var _clearEvents = function(){
  135. $.each(_events, function(index, val) {
  136. val.visual().clear();
  137. });
  138. _events = [];
  139. };
  140. var _updateEvents = function() {
  141. var o = plot.getPlotOffset(), left, top;
  142. var xaxis = plot.getXAxes()[plot.getOptions().events.xaxis - 1];
  143. $.each(_events, function(index, event) {
  144. top = o.top + plot.height() - event.visual().height();
  145. left = xaxis.p2c(event.getOptions().min) + o.left - event.visual().width() / 2;
  146. event.visual().moveTo({ top: top, left: left });
  147. });
  148. };
  149. var _showTooltip = function(x, y, event){
  150. /*
  151. var tooltip = $('<div id="tooltip" class=""></div>').appendTo('body').fadeIn(200);
  152. $('<div id="title">' + event.title + '</div>').appendTo(tooltip);
  153. $('<div id="type">Type: ' + event.eventType + '</div>').appendTo(tooltip);
  154. $('<div id="description">' + event.description + '</div>').appendTo(tooltip);
  155. tooltip.css({
  156. top: y - tooltip.height() - 5,
  157. left: x
  158. });
  159. console.log(tooltip);
  160. */
  161. // grafana addition
  162. var $tooltip = $('<div id="tooltip" annotation-tooltip>');
  163. if (event) {
  164. $tooltip
  165. .html(event.description)
  166. .place_tt(x, y, {offset: 10, compile: true, scopeData: {event: event}});
  167. } else {
  168. $tooltip.remove();
  169. }
  170. };
  171. var _setupEvents = function(events){
  172. $.each(events, function(index, event){
  173. var level = (plot.getOptions().events.levels == null || !_types || !_types[event.eventType]) ? 0 : _types[event.eventType].level;
  174. if (level > plot.getOptions().events.levels) {
  175. throw "A type's level has exceeded the maximum. Level=" +
  176. level +
  177. ", Max levels:" +
  178. (plot.getOptions().events.levels);
  179. }
  180. _events.push(new VisualEvent(event, _buildDiv(event), level));
  181. });
  182. _events.sort(compareEvents);
  183. };
  184. var _identicalStarts = function() {
  185. var ranges = [], range = {}, event, prev, offset = 0;
  186. $.each(_events, function(index, val) {
  187. if (prev) {
  188. if (val.getOptions().min == prev.getOptions().min) {
  189. if (!range.min) {
  190. range.min = index;
  191. }
  192. range.max = index;
  193. } else {
  194. if (range.min) {
  195. ranges.push(range);
  196. range = {};
  197. }
  198. }
  199. }
  200. prev = val;
  201. });
  202. if (range.min) {
  203. ranges.push(range);
  204. }
  205. $.each(ranges, function(index, val) {
  206. var removed = _events.splice(val.min - offset, val.max - val.min + 1);
  207. $.each(removed, function(index, val) {
  208. val.visual().clear();
  209. });
  210. offset += val.max - val.min + 1;
  211. });
  212. };
  213. var _overlaps = function() {
  214. var xaxis = plot.getXAxes()[plot.getOptions().events.xaxis - 1];
  215. var range, diff, cmid, pmid, left = 0, right = -1;
  216. pright = plot.width() - plot.getPlotOffset().right;
  217. // coverts a clump of events into a single vertical line
  218. var processClump = function() {
  219. // find the middle x value
  220. pmid = _events[right].getOptions().min -
  221. (_events[right].getOptions().min - _events[left].getOptions().min) / 2;
  222. cmid = xaxis.p2c(pmid);
  223. // hide the events between the discovered range
  224. while (left <= right) {
  225. _events[left++].visual().getObject().hide();
  226. }
  227. // draw a vertical line in the middle of where they are
  228. if (_insidePlot(pmid)) {
  229. _drawLine('#000', 1, { x: cmid, y: 0 }, { x: cmid, y: plot.height() });
  230. }
  231. };
  232. if (xaxis.min && xaxis.max) {
  233. range = xaxis.max - xaxis.min;
  234. for (var i = 1; i < _events.length; i++) {
  235. diff = _events[i].getOptions().min - _events[i - 1].getOptions().min;
  236. if (diff / range > 0.007) { //enough variance
  237. // has a clump has been found
  238. if (right != -1) {
  239. //processClump();
  240. }
  241. right = -1;
  242. left = i;
  243. } else { // not enough variance
  244. right = i;
  245. // handle to final case
  246. if (i == _events.length - 1) {
  247. //processClump();
  248. }
  249. }
  250. }
  251. }
  252. };
  253. var _buildDiv = function(event){
  254. //var po = plot.pointOffset({ x: 450, y: 1});
  255. var container = plot.getPlaceholder(), o = plot.getPlotOffset(), yaxis,
  256. xaxis = plot.getXAxes()[plot.getOptions().events.xaxis - 1], axes = plot.getAxes();
  257. var top, left, div, icon, level, drawableEvent;
  258. // determine the y axis used
  259. if (axes.yaxis && axes.yaxis.used) yaxis = axes.yaxis;
  260. if (axes.yaxis2 && axes.yaxis2.used) yaxis = axes.yaxis2;
  261. // use the default icon and level
  262. if (_types == null || !_types[event.eventType] || !_types[event.eventType].icon) {
  263. icon = DEFAULT_ICON;
  264. level = 0;
  265. } else {
  266. icon = _types[event.eventType].icon;
  267. level = _types[event.eventType].level;
  268. }
  269. div = $('<i style="position:absolute" class="'+icon.icon+'"></i>').appendTo(container);
  270. top = o.top + plot.height() - icon.size + 1;
  271. left = xaxis.p2c(event.min) + o.left - icon.size / 2;
  272. div.css({
  273. left: left + 'px',
  274. top: top,
  275. color: icon.color,
  276. "text-shadow" : "1px 1px "+icon.outline+", -1px -1px "+icon.outline+", -1px 1px "+icon.outline+", 1px -1px "+icon.outline,
  277. 'font-size': icon['size']+'px',
  278. });
  279. div.hide();
  280. div.data({
  281. "event": event
  282. });
  283. div.hover(
  284. // mouseenter
  285. function(){
  286. var pos = $(this).offset();
  287. _showTooltip(pos.left + $(this).width() / 2, pos.top, $(this).data("event"));
  288. },
  289. // mouseleave
  290. function(){
  291. //$(this).data("bouncing", false);
  292. $('#tooltip').remove();
  293. plot.clearSelection();
  294. });
  295. drawableEvent = new DrawableEvent(
  296. div,
  297. function(obj){
  298. obj.show();
  299. },
  300. function(obj){
  301. obj.remove();
  302. },
  303. function(obj, position){
  304. obj.css({
  305. top: position.top,
  306. left: position.left
  307. });
  308. },
  309. left, top, div.width(), div.height());
  310. return drawableEvent;
  311. };
  312. var _getEventsAtPos = function(x, y){
  313. var found = [], left, top, width, height;
  314. $.each(_events, function(index, val){
  315. left = val.div.offset().left;
  316. top = val.div.offset().top;
  317. width = val.div.width();
  318. height = val.div.height();
  319. if (x >= left && x <= left + width && y >= top && y <= top + height) {
  320. found.push(val);
  321. }
  322. return found;
  323. });
  324. };
  325. var _insidePlot = function(x) {
  326. var xaxis = plot.getXAxes()[plot.getOptions().events.xaxis - 1];
  327. var xc = xaxis.p2c(x);
  328. return xc > 0 && xc < xaxis.p2c(xaxis.max);
  329. };
  330. var _drawLine = function(color, lineWidth, from, to) {
  331. var ctx = plot.getCanvas().getContext("2d");
  332. var plotOffset = plot.getPlotOffset();
  333. ctx.save();
  334. ctx.translate(plotOffset.left, plotOffset.top);
  335. ctx.beginPath();
  336. ctx.strokeStyle = color;
  337. ctx.lineWidth = lineWidth;
  338. ctx.moveTo(from.x, from.y);
  339. ctx.lineTo(to.x, to.y);
  340. ctx.stroke();
  341. ctx.restore();
  342. };
  343. /**
  344. * Runs over the given 2d array of event objects and returns an object
  345. * containing:
  346. *
  347. * {
  348. * types {}, // An array containing all the different event types
  349. * data [], // An array of the clustered events
  350. * }
  351. *
  352. * @param {Object} types
  353. * an object containing event types
  354. * @param {Object} events
  355. * an array of event to cluster
  356. * @param {Object} range
  357. * the current graph range
  358. */
  359. var _clusterEvents = function(types, events, range) {
  360. //TODO: support custom types
  361. var groups, clusters = [], newEvents = [];
  362. // split into same evenType groups
  363. groups = _groupEvents(events);
  364. $.each(groups.eventTypes, function(index, val) {
  365. clusters.push(_varianceAlgorithm(groups.groupedEvents[val], 1, range));
  366. });
  367. // summarise clusters
  368. $.each(clusters, function(index, eventType) {
  369. // each cluser of each event type
  370. $.each(eventType, function(index, cluster) {
  371. var newEvent = {
  372. min: cluster[0].min,
  373. max: cluster[cluster.length - 1].min, //TODO: needs to be max of end event if it exists
  374. eventType: cluster[0].eventType + ",cluster",
  375. title: "Cluster of: " + cluster[0].title,
  376. description: cluster[0].description + ", Number of events in the cluster: " + cluster.length
  377. };
  378. newEvents.push(newEvent);
  379. });
  380. });
  381. return { types: types, data: newEvents };
  382. };
  383. /**
  384. * Runs over the given 2d array of event objects and returns an object
  385. * containing:
  386. *
  387. * {
  388. * eventTypes [], // An array containing all the different event types
  389. * groupedEvents {}, // An object containing all the grouped events
  390. * }
  391. *
  392. * @param {Object} events
  393. * an array of event objects
  394. */
  395. var _groupEvents = function(events) {
  396. var eventTypes = [], groupedEvents = {};
  397. $.each(events, function(index, val) {
  398. if (!groupedEvents[val.eventType]) {
  399. groupedEvents[val.eventType] = [];
  400. eventTypes.push(val.eventType);
  401. }
  402. groupedEvents[val.eventType].push(val);
  403. });
  404. return { eventTypes: eventTypes, groupedEvents: groupedEvents };
  405. };
  406. /**
  407. * Runs over the given 2d array of event objects and returns a 3d array of
  408. * the same events,but clustered into groups with similar x deltas.
  409. *
  410. * This function assumes that the events are related. So it must be run on
  411. * each set of related events.
  412. *
  413. * @param {Object} events
  414. * an array of event objects
  415. * @param {Object} sens
  416. * a measure of the level of grouping tolerance
  417. * @param {Object} space
  418. * the size of the space we have to place clusters within
  419. */
  420. var _varianceAlgorithm = function(events, sens, space) {
  421. var cluster, clusters = [], sum = 0, avg, density;
  422. // find the average x delta
  423. for (var i = 1; i < events.length - 1; i++) {
  424. sum += events[i].min - events[i - 1].min;
  425. }
  426. avg = sum / (events.length - 2);
  427. // first point
  428. cluster = [ events[0] ];
  429. // middle points
  430. for (var i = 1; i < events.length; i++) {
  431. var leftDiff = events[i].min - events[i - 1].min;
  432. density = leftDiff / space;
  433. if (leftDiff > avg * sens && density > 0.05) {
  434. clusters.push(cluster);
  435. cluster = [ events[i] ];
  436. } else {
  437. cluster.push(events[i]);
  438. }
  439. }
  440. clusters.push(cluster);
  441. return clusters;
  442. };
  443. }
  444. var options = {
  445. events: {
  446. levels: null,
  447. data: null,
  448. types: null,
  449. xaxis: 1,
  450. clustering: false
  451. }
  452. };
  453. $.plot.plugins.push({
  454. init: init,
  455. options: options,
  456. name: "events",
  457. version: "0.20"
  458. });
  459. /**
  460. * A class that allows for the drawing an remove of some object
  461. *
  462. * @param {Object} object
  463. * the drawable object
  464. * @param {Object} drawFunc
  465. * the draw function
  466. * @param {Object} clearFunc
  467. * the clear function
  468. */
  469. function DrawableEvent(object, drawFunc, clearFunc, moveFunc, left, top, width, height){
  470. var _object = object, _drawFunc = drawFunc, _clearFunc = clearFunc, _moveFunc = moveFunc,
  471. _position = { left: left, top: top }, _width = width, _height = height;
  472. this.width = function() { return _width; };
  473. this.height = function() { return _height };
  474. this.position = function() { return _position; };
  475. this.draw = function() { _drawFunc(_object); };
  476. this.clear = function() { _clearFunc(_object); };
  477. this.getObject = function() { return _object; };
  478. this.moveTo = function(position) {
  479. _position = position;
  480. _moveFunc(_object, _position);
  481. };
  482. }
  483. /**
  484. * Event class that stores options (eventType, min, max, title, description) and the object to draw.
  485. *
  486. * @param {Object} options
  487. * @param {Object} drawableEvent
  488. */
  489. function VisualEvent(options, drawableEvent, level){
  490. var _parent, _options = options, _drawableEvent = drawableEvent,
  491. _level = level, _hidden = false;
  492. this.visual = function() { return _drawableEvent; }
  493. this.level = function() { return _level; };
  494. this.getOptions = function() { return _options; };
  495. this.getParent = function() { return _parent; };
  496. this.isHidden = function() { return _hidden; };
  497. this.hide = function() { _hidden = true; };
  498. this.unhide = function() { _hidden = false; };
  499. }
  500. function compareEvents(a, b) {
  501. var ao = a.getOptions(), bo = b.getOptions();
  502. if (ao.min > bo.min) return 1;
  503. if (ao.min < bo.min) return -1;
  504. return 0;
  505. };
  506. })(jQuery);