barChart.jquery.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. (function ($) {
  2. var settings = {};
  3. $.fn.barChart = function (options) {
  4. var defaults = {
  5. vertical: false,
  6. bars: [],
  7. hiddenBars: [],
  8. milestones: [],
  9. colors: [
  10. "#f44336", "#e91e63", "#9c27b0", "#673ab7", "#3f51b5",
  11. "#2196f3", "#03a9f4", "#00bcd4", "#009688", "#4caf50",
  12. "#8bc34a", "#cddc39", "#ffeb3b", "#ffc107", "#ff9800",
  13. "#ff5722", "#795548", "#9e9e9e", "#607d8b", "#263238"
  14. ],
  15. barColors: {},
  16. dateFormat: 'DD.MM.YYYY HH:mm',
  17. barGap: 5,
  18. totalSumHeight: 25,
  19. defaultWidth: 40,
  20. defaultColumnWidth: 65
  21. };
  22. settings = $.extend(settings, defaults, options);
  23. $(this)
  24. .css('height', settings.height && !settings.vertical ? settings.height : 'auto')
  25. .addClass('bar-chart')
  26. .addClass(settings.vertical ? 'bar-chart-vertical' : '')
  27. .wrap('<div class="bar-chart-wrapper"></div>');
  28. $.proxy(init, this)();
  29. this.handler = this;
  30. return this;
  31. };
  32. // init
  33. function init() {
  34. settings.maxHeight = settings.vertical ? $(this).width() : ($(this).height() - settings.totalSumHeight);
  35. settings.maxWidth = settings.vertical ? settings.defaultWidth : $(this).width();
  36. settings.barGapPercent = settings.barGap / (settings.maxWidth / 100);
  37. var bars = colorizeBars(settings.bars, settings.colors);
  38. var columns = groupByKey(bars, settings.hiddenBars);
  39. $.proxy(drawY, this)(columns);
  40. console.time('draw X');
  41. $.proxy(drawX, this)(columns);
  42. console.timeEnd('draw X');
  43. $.proxy(drawTooltip, this)();
  44. $.proxy(drawLegend, this)(bars, settings.hiddenBars);
  45. $.proxy(subscribe_tooltip, this)();
  46. $.proxy(subscribe_legend, this)();
  47. return this;
  48. };
  49. // up to date
  50. function update() {
  51. var bars = colorizeBars(settings.bars, settings.colors);
  52. var columns = groupByKey(bars, settings.hiddenBars);
  53. $(this).html('');
  54. $.proxy(drawY, this)(columns);
  55. $.proxy(drawX, this)(columns);
  56. return this;
  57. };
  58. // group bar values by keys
  59. function groupByKey(bars, hiddenBars) {
  60. var hiddenBarsArray = hiddenBars || [];
  61. var columns = {};
  62. bars.forEach(function (bar) {
  63. if (hiddenBarsArray.indexOf(bar.name) !== -1) {
  64. return true;
  65. }
  66. bar.values.forEach(function (value) {
  67. columns[value[0]] = columns[value[0]] || [];
  68. columns[value[0]].push({value: parseFloat(value[1]), name: bar.name, color: bar.color});
  69. });
  70. });
  71. return columns;
  72. };
  73. // set bars colors
  74. function colorizeBars(bars, colors) {
  75. colorIndex = 0;
  76. bars.forEach(function (bar) {
  77. if (typeof bar.color === 'undefined') {
  78. bar.color = colors[colorIndex];
  79. }
  80. colorIndex++;
  81. if (colorIndex >= colors.length) {
  82. colorIndex = 0;
  83. }
  84. });
  85. return bars;
  86. };
  87. // find max value through all bars
  88. function findMax(columns) {
  89. var result = 0;
  90. for (var i in columns) {
  91. if (columns.hasOwnProperty(i)) {
  92. var max = 0;
  93. columns[i].forEach(function (value) {
  94. max += value.value;
  95. });
  96. if (max > result) {
  97. result = max;
  98. }
  99. }
  100. }
  101. return result;
  102. };
  103. // find total sum of all values through all bars
  104. function totalSum(columns) {
  105. var result = 0;
  106. for (var i in columns) {
  107. if (columns.hasOwnProperty(i)) {
  108. columns[i].forEach(function (value) {
  109. result += value.value;
  110. });
  111. }
  112. }
  113. return result;
  114. };
  115. // draw y-milestones
  116. function drawY(columns) {
  117. var $container = $('<div />').addClass(settings.vertical ? 'bar-x' : 'bar-y');
  118. var max = findMax(columns);
  119. var milestonesCount = Math.round(max).toString().length;
  120. var multiplier = Math.pow(10, milestonesCount - 1);
  121. max = settings.vertical ? Math.ceil(max) : Math.ceil(max / multiplier) * multiplier;
  122. var step = (max / 5);
  123. if (step < 1) {
  124. step = 1;
  125. }
  126. var top = 0;
  127. var value = 0;
  128. while (top < settings.maxHeight) {
  129. top = (value * settings.maxHeight) / max;
  130. var gridValue = value;
  131. if (gridValue < 1000) {
  132. gridValue = gridValue.toFixed(2);
  133. }
  134. if (gridValue >= 1000 && gridValue <= 1000000) {
  135. gridValue = (gridValue / 1000).toFixed(2) + ' K';
  136. }
  137. if (gridValue >= 1000000 && gridValue <= 1000000000) {
  138. gridValue = (gridValue / 1000000).toFixed(2) + ' M';
  139. }
  140. var $gridValue = $('<div />')
  141. .addClass(settings.vertical ? 'bar-x-value' : 'bar-y-value')
  142. .css(settings.vertical ? {left: top} : {bottom: top})
  143. .html('<div>' + gridValue + '</div>');
  144. $container.append($gridValue);
  145. value += step;
  146. }
  147. $(this).append($container);
  148. return this;
  149. };
  150. // draw x-values
  151. function drawX(columns) {
  152. var keys = Object.keys(columns);
  153. var columnsCount = keys.length;
  154. var columnWidth = Math.round((settings.maxWidth - settings.barGap * (columnsCount + 1)) / columnsCount);
  155. if (settings.vertical) {
  156. columnWidth = settings.defaultWidth;
  157. }
  158. var max = findMax(columns);
  159. var total = totalSum(columns);
  160. if (!settings.vertical) {
  161. if (columnWidth < settings.defaultColumnWidth) { //settings.defaultColumnWidth = 65
  162. $(this).addClass('bar-titles-vertical');
  163. }
  164. columnWidth = (columnWidth / (settings.maxWidth / 100));
  165. }
  166. keys.sort(function (a, b) {
  167. return parseInt(a) - parseInt(b);
  168. });
  169. for (var k in keys) {
  170. if (keys.hasOwnProperty(k)) {
  171. var key = keys[k];
  172. var column = columns[key];
  173. var localMax = 0;
  174. var localSum = 0;
  175. var localMaxHeight = 0;
  176. //sort values desc
  177. column.sort(function (a, b) {
  178. return b.value - a.value;
  179. });
  180. column.forEach(function (bar) {
  181. localMax = bar.value > localMax ? bar.value : localMax;
  182. localSum += bar.value;
  183. });
  184. localMaxHeight = (localMax * settings.maxHeight / max);
  185. var text = key.toString()
  186. //it's timestamp, so let's format it
  187. if (text.length === 10 && text == parseInt(text)) {
  188. text = formatDate(new Date(text * 1000));
  189. }
  190. var $barTitle = $('<div />').addClass('bar-title').html(text);
  191. var $barValue = $('<div />')
  192. .addClass('bar-value')
  193. .css(
  194. settings.vertical ?
  195. {width: localMaxHeight} :
  196. {height: localMaxHeight}
  197. );
  198. var $bar = $('<div />')
  199. .addClass('bar')
  200. .css(
  201. settings.vertical ?
  202. {height: columnWidth} :
  203. {width: columnWidth + '%', marginLeft: settings.barGapPercent + '%'}
  204. )
  205. .attr({'data-id': key})
  206. .append($barValue)
  207. .append($barTitle);
  208. $(this).append($bar);
  209. var bottom = 0;
  210. var previousBottom = 0;
  211. var previousHeight = 0;
  212. console.time('bar lines');
  213. var appendixArray = [];
  214. column.forEach(function (bar) {
  215. var height = localMaxHeight / localMax * bar.value;
  216. var percentage = (bar.value / (total / 100)).toFixed(2);
  217. bottom = previousHeight + previousBottom;
  218. $appendix = $('<div />')
  219. .addClass('bar-line')
  220. .attr({
  221. 'data-percentage': (percentage + '%'),
  222. 'data-name': bar.name,
  223. 'data-value': bar.value
  224. })
  225. .css(
  226. settings.vertical ?
  227. {background: bar.color, width: height, left: bottom} :
  228. {background: bar.color, height: height, bottom: bottom}
  229. );
  230. $barValue.append($appendix);
  231. previousBottom = bottom;
  232. previousHeight = height;
  233. });
  234. console.timeEnd('bar lines');
  235. var tmpSum = localSum.toString().split('.');
  236. if (tmpSum[0].length >= 5) {
  237. tmpSum[0] = tmpSum[0].replace(/(\d)(?=(\d{3})+$)/g, '$1 ');
  238. }
  239. localSum = tmpSum.join('.');
  240. $barValueSum = $('<div />')
  241. .addClass('bar-value-sum')
  242. .css(
  243. settings.vertical ?
  244. {left: previousBottom + previousHeight} :
  245. {bottom: previousBottom + previousHeight}
  246. )
  247. .html(localSum); // + <i> currency </i>
  248. $bar.append($barValueSum);
  249. }
  250. }
  251. return this;
  252. };
  253. // adds tooltip markup to dom
  254. function drawTooltip() {
  255. if ($(this).find('.tooltip').length === 0) {
  256. $(this).append(
  257. '<div class="tooltip tooltip-mobile hidden" style="top: 0; left: 0;">' +
  258. '<div class="tooltip-title">{title}</div> ' +
  259. '<div class="tooltip-change">{value}</div> ' +
  260. '</div>'
  261. );
  262. }
  263. return this;
  264. };
  265. // legend
  266. function drawLegend(bars, hiddenBars) {
  267. var $legend = $('<div />').addClass('bar-legend legend');
  268. $(this).parent().append($legend);
  269. bars.forEach(function (bar) {
  270. var $checkbox = $('<div />')
  271. .addClass('checkbox')
  272. .addClass(hiddenBars.indexOf(bar.name) === -1 ? 'checked' : '')
  273. .css({'background-color': bar.color});
  274. var $legendItem = $('<div />')
  275. .addClass('legend-item')
  276. .css({color: bar.color})
  277. .html(bar.name)
  278. var $legendItemWrapper = $('<div />')
  279. .addClass('legend-item-wrapper')
  280. .append($checkbox)
  281. .append($legendItem);
  282. $legend.append($legendItemWrapper);
  283. });
  284. return this;
  285. };
  286. // mousemove and mouseleave pon bar
  287. function subscribe_tooltip() {
  288. var $barLines = $(this).find('.bar-line');
  289. var $tooltip = $(this).find('.tooltip');
  290. $barLines.on('mousemove', function (e) {
  291. $(this).parents('.bar').addClass('bar-active');
  292. $tooltip.css({
  293. top: e.pageY - 65, // + $(this).offset().top
  294. left: e.pageX - 65 // + $(this).offset().left
  295. });
  296. $tooltip.find('.tooltip-title').html($(this).data('name'));
  297. $tooltip.find('.tooltip-change').html($(this).data('value') + '<small>' + $(this).data('percentage') + '</small>');
  298. $tooltip.removeClass('hidden');
  299. });
  300. $barLines.on('mouseleave', function (e) {
  301. $tooltip.addClass('hidden');
  302. $(this).parents('.bar').removeClass('bar-active');
  303. });
  304. return this;
  305. };
  306. // checkbox click and double click
  307. function subscribe_legend() {
  308. /**
  309. * emulate single and double clicks pon same element
  310. */
  311. var clicks = 0;
  312. var timer = null;
  313. var delay = 200;
  314. var $self = $(this);
  315. var $legendItemWrapper = $(this).parent().find('.legend-item-wrapper');
  316. $legendItemWrapper.on('mouseleave', function () {
  317. var barName = $(this).find('.legend-item').html();
  318. var $bar = $('.bar-line[data-name="' + barName + '"]');
  319. $bar.removeClass('active');
  320. });
  321. $legendItemWrapper.on('mouseenter', function () {
  322. var barName = $(this).find('.legend-item').html();
  323. var $bar = $('.bar-line[data-name="' + barName + '"]');
  324. $bar.addClass('active');
  325. });
  326. $legendItemWrapper.on('click', function (e) {
  327. e.preventDefault();
  328. var $this = $(this);
  329. clicks++;
  330. if (clicks === 1) {
  331. timer = setTimeout(function () {
  332. clearTimeout(timer);
  333. var name = $this.find('.legend-item').html();
  334. var isChecked = $this.find('.checkbox').hasClass('checked');
  335. $('.bar-line[data-name="' + name + '"]').toggleClass('hidden');
  336. $this.find('.checkbox').toggleClass('checked');
  337. if (isChecked) {
  338. settings.hiddenBars.push(name);
  339. } else {
  340. var index = settings.hiddenBars.indexOf(name);
  341. if (index >= 0) {
  342. settings.hiddenBars.splice(index, 1);
  343. }
  344. }
  345. $.proxy(update, $self)();
  346. clicks = 0;
  347. }, delay);
  348. } else {
  349. clearTimeout(timer);
  350. var $checkbox = $(this).find('.checkbox');
  351. var $checkboxes = $(this).parent().find('.checkbox.checked');
  352. var checkedCount = $checkboxes.length;
  353. if (checkedCount === 1 && $checkbox.hasClass('checked')) {
  354. $(this).parent().find('.checkbox').addClass('checked');
  355. } else {
  356. $(this).parent().find('.checkbox').removeClass('checked');
  357. $checkbox.addClass('checked');
  358. }
  359. var checkboxes = [];
  360. $(this).parent().find('.checkbox:not(.checked)').each(function () {
  361. checkboxes.push($(this).next('.legend-item').html());
  362. });
  363. settings.hiddenBars = checkboxes;
  364. //self.update();
  365. $.proxy(update, $self)();
  366. clicks = 0;
  367. }
  368. });
  369. $legendItemWrapper.on('dblclick', function (e) {
  370. e.preventDefault();
  371. });
  372. return this;
  373. };
  374. // dateformat to dd/mm/yyyy
  375. function formatDate(dt) {
  376. var dd = dt.getDate();
  377. var mm = dt.getMonth() + 1;
  378. var yyyy = dt.getFullYear().toString().substring(2);
  379. return [dd, mm, yyyy].join('.');
  380. };
  381. }(jQuery));