jquery.flot.events.js 20 KB

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