ko.charts.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. // Licensed to Cloudera, Inc. under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. Cloudera, Inc. licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. ko.HUE_CHARTS = {
  17. TYPES: {
  18. LINECHART: "lines",
  19. BARCHART: "bars",
  20. POINTCHART: "points",
  21. PIECHART: "pie",
  22. MAP: "map"
  23. }
  24. };
  25. ko.bindingHandlers.pieChart = {
  26. update: function (element, valueAccessor) {
  27. var _options = valueAccessor();
  28. var _data = _options.transformer(_options.data);
  29. $(element).css("marginLeft", "auto");
  30. $(element).css("marginRight", "auto");
  31. if (typeof _options.maxWidth != "undefined") {
  32. var _max = _options.maxWidth * 1;
  33. $(element).width(Math.min($(element).parent().width(), _max));
  34. }
  35. if ($(element).find('svg').length > 0 && _data.length == 0) {
  36. $(element).find('svg').empty();
  37. }
  38. if (_data.length > 0 && isNaN(_data[0].value)) {
  39. _data = [];
  40. $(element).find('svg').empty();
  41. }
  42. if ($(element).is(":visible")) {
  43. nv.addGraph(function () {
  44. var _chart = nv.models.growingPieChart()
  45. .x(function (d) {
  46. return d.label
  47. })
  48. .y(function (d) {
  49. return d.value
  50. })
  51. .height($(element).width())
  52. .showLabels(true).showLegend(false);
  53. var _d3 = ($(element).find('svg').length > 0) ? d3.select($(element).find('svg')[0]) : d3.select($(element)[0]).append('svg');
  54. _d3.datum(_data)
  55. .transition().duration(150)
  56. .each("end", _options.onComplete != null ? _options.onComplete : void(0))
  57. .call(_chart);
  58. if (_options.fqs) {
  59. $.each(_options.fqs(), function (cnt, item) {
  60. if (item.field() == _options.field()) {
  61. _chart.selectSlices(item.filter());
  62. }
  63. });
  64. }
  65. nv.utils.windowResize(_chart.update);
  66. $(element).height($(element).width());
  67. $(element).parents(".card-widget").on("resize", function () {
  68. if (typeof _options.maxWidth != "undefined") {
  69. var _max = _options.maxWidth * 1;
  70. $(element).width(Math.min($(element).parent().width(), _max));
  71. }
  72. $(element).height($(element).width());
  73. _chart.update();
  74. });
  75. return _chart;
  76. }, function () {
  77. var _d3 = ($(element).find('svg').length > 0) ? d3.select($(element).find('svg')[0]) : d3.select($(element)[0]).append('svg');
  78. _d3.selectAll(".nv-slice").on('click',
  79. function (d, i) {
  80. if (typeof _options.onClick != "undefined") {
  81. chartsUpdatingState();
  82. _options.onClick(d);
  83. }
  84. });
  85. });
  86. }
  87. }
  88. };
  89. ko.bindingHandlers.barChart = {
  90. update: function (element, valueAccessor) {
  91. barChartBuilder(element, valueAccessor(), false);
  92. }
  93. };
  94. ko.bindingHandlers.timelineChart = {
  95. update: function (element, valueAccessor) {
  96. barChartBuilder(element, valueAccessor(), true);
  97. }
  98. };
  99. ko.bindingHandlers.lineChart = {
  100. update: function (element, valueAccessor) {
  101. lineChartBuilder(element, valueAccessor());
  102. }
  103. };
  104. ko.bindingHandlers.leafletMapChart = {
  105. update: function (element, valueAccessor) {
  106. var _options = valueAccessor();
  107. var _data = _options.transformer(valueAccessor().datum);
  108. function getMapBounds(lats, lngs) {
  109. lats = lats.sort();
  110. lngs = lngs.sort();
  111. return [
  112. [lats[lats.length - 1], lngs[lngs.length - 1]], // north-east
  113. [lats[0], lngs[0]] // south-west
  114. ]
  115. }
  116. if ($(element).data("map") != null) {
  117. try {
  118. $(element).data("map").remove();
  119. }
  120. catch (err) {
  121. if (typeof console != "undefined") {
  122. console.error(err);
  123. }
  124. }
  125. }
  126. var _lats = [];
  127. _data.forEach(function (item) {
  128. if (item.lat != null) {
  129. _lats.push(item.lat);
  130. }
  131. });
  132. var _lngs = [];
  133. _data.forEach(function (item) {
  134. if (item.lng != null) {
  135. _lngs.push(item.lng);
  136. }
  137. });
  138. $(element).height($(element).parents(".tab-pane").height() - 100);
  139. var _map = null;
  140. if (element._map != null) {
  141. element._leaflet = false;
  142. element._map.remove();
  143. }
  144. if (_lats.length > 0 && _lngs.length > 0) {
  145. try {
  146. if (_map == null) {
  147. _map = L.map($(element).attr("id"));
  148. L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
  149. attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributorss'
  150. }).addTo(_map);
  151. }
  152. _map.fitBounds(getMapBounds(_lats, _lngs));
  153. _data.forEach(function (item) {
  154. if (item.lng != null && item.lat != null) {
  155. var _marker = L.marker([item.lat, item.lng]).addTo(_map);
  156. if (item.label != null) {
  157. _marker.bindPopup(item.label);
  158. }
  159. }
  160. });
  161. }
  162. catch (err) {
  163. $.jHueNotify.error(err.message);
  164. }
  165. }
  166. element._map = _map;
  167. }
  168. };
  169. ko.bindingHandlers.mapChart = {
  170. render: function (element, valueAccessor) {
  171. var _options = valueAccessor();
  172. $(element).empty();
  173. $(element).css("position", "relative");
  174. $(element).css("marginLeft", "auto");
  175. $(element).css("marginRight", "auto");
  176. if (typeof _options.maxWidth != "undefined") {
  177. var _max = _options.maxWidth * 1;
  178. $(element).width(Math.min($(element).parent().width(), _max));
  179. }
  180. $(element).height($(element).width() / 2.23);
  181. var _scope = typeof _options.data.scope != "undefined" ? String(_options.data.scope) : "world";
  182. var _data = _options.transformer(_options.data);
  183. var _maxWeight = 0;
  184. $(_data).each(function (cnt, item) {
  185. if (item.value > _maxWeight) _maxWeight = item.value;
  186. });
  187. var _chunk = _maxWeight / _data.length;
  188. var _mapdata = {};
  189. var _maphovers = {};
  190. var _fills = {};
  191. var _noncountries = [];
  192. if (_options.isScale) {
  193. _fills["defaultFill"] = HueColors.WHITE;
  194. var _colors = HueColors.scale(HueColors.LIGHT_BLUE, HueColors.DARK_BLUE, _data.length);
  195. $(_colors).each(function (cnt, item) {
  196. _fills["fill_" + cnt] = item;
  197. });
  198. $(_data).each(function (cnt, item) {
  199. var _place = item.label.toUpperCase();
  200. if (_place != null) {
  201. _mapdata[_place] = {
  202. fillKey: "fill_" + (Math.floor(item.value / _chunk) - 1),
  203. id: _place,
  204. cat: item.obj.cat,
  205. value: item.obj.value,
  206. selected: item.obj.selected
  207. };
  208. _maphovers[_place] = item.value;
  209. }
  210. else {
  211. _noncountries.push(item);
  212. }
  213. });
  214. }
  215. else {
  216. _fills["defaultFill"] = HueColors.LIGHT_BLUE;
  217. _fills["selected"] = HueColors.DARK_BLUE;
  218. $(_data).each(function (cnt, item) {
  219. var _place = item.label.toUpperCase();
  220. if (_place != null) {
  221. _mapdata[_place] = {
  222. fillKey: "selected",
  223. id: _place,
  224. cat: item.obj.cat,
  225. value: item.obj.value,
  226. selected: item.obj.selected
  227. };
  228. _maphovers[_place] = item.value;
  229. }
  230. else {
  231. _noncountries.push(item);
  232. }
  233. });
  234. }
  235. var _map = null;
  236. function createDatamap(element, options, fills, mapData, nonCountries, mapHovers) {
  237. _map = new Datamap({
  238. element: element,
  239. fills: fills,
  240. scope: _scope,
  241. data: mapData,
  242. onClick: function (data) {
  243. if (typeof options.onClick != "undefined") {
  244. chartsUpdatingState();
  245. options.onClick(data);
  246. }
  247. },
  248. done: function (datamap) {
  249. var _bubbles = [];
  250. if (options.enableGeocoding) {
  251. $(nonCountries).each(function (cnt, item) {
  252. HueGeo.getCityCoordinates(item.label, function (lat, lng) {
  253. _bubbles.push({
  254. fillKey: "selected",
  255. label: item.label,
  256. value: item.value,
  257. radius: 4,
  258. latitude: lat,
  259. longitude: lng
  260. });
  261. _map.bubbles(_bubbles, {
  262. popupTemplate: function (geo, data) {
  263. return '<div class="hoverinfo" style="text-align: center"><strong>' + data.label + '</strong><br/>' + item.value + '</div>'
  264. }
  265. });
  266. });
  267. });
  268. }
  269. },
  270. geographyConfig: {
  271. hideAntarctica: true,
  272. borderWidth: 1,
  273. borderColor: HueColors.DARK_BLUE,
  274. highlightOnHover: true,
  275. highlightFillColor: HueColors.DARK_BLUE,
  276. highlightBorderColor: HueColors.BLUE,
  277. selectedFillColor: HueColors.DARKER_BLUE,
  278. selectedBorderColor: HueColors.DARKER_BLUE,
  279. popupTemplate: function (geography, data) {
  280. var _hover = '';
  281. if (data != null) {
  282. _hover = '<br/>' + mapHovers[data.id];
  283. }
  284. return '<div class="hoverinfo" style="text-align: center"><strong>' + geography.properties.name + '</strong>' + _hover + '</div>'
  285. }
  286. }
  287. });
  288. if (options.onComplete != null) {
  289. options.onComplete();
  290. }
  291. }
  292. createDatamap(element, _options, _fills, _mapdata, _noncountries, _maphovers)
  293. $(element).parents(".card-widget").one("resize", function () {
  294. ko.bindingHandlers.mapChart.render(element, valueAccessor);
  295. });
  296. },
  297. init: function (element, valueAccessor) {
  298. ko.bindingHandlers.mapChart.render(element, valueAccessor)
  299. },
  300. update: function (element, valueAccessor) {
  301. ko.bindingHandlers.mapChart.render(element, valueAccessor);
  302. }
  303. };
  304. function lineChartBuilder(element, options) {
  305. var _datum = options.transformer(options.datum);
  306. $(element).height(300);
  307. if ($(element).find('svg').length > 0 && (_datum.length == 0 || _datum[0].values.length == 0)) {
  308. $(element).find('svg').empty();
  309. }
  310. if (_datum.length > 0 && _datum[0].values.length > 0 && (isNaN(_datum[0].values[0].x) || isNaN(_datum[0].values[0].y))) {
  311. _datum = [];
  312. $(element).find('svg').empty();
  313. }
  314. if ($(element).is(":visible")) {
  315. nv.addGraph(function () {
  316. var _chart = nv.models.lineWithBrushChart();
  317. if (_datum.length > 0 && _datum[0].values.length > 10) {
  318. _chart.enableSelection();
  319. }
  320. if (options.showControls != null) {
  321. _chart.showControls(false);
  322. }
  323. _chart.onSelectRange(function (from, to) {
  324. chartsUpdatingState();
  325. options.onSelectRange(from, to);
  326. });
  327. _chart.xAxis.showMaxMin(false);
  328. _chart.yAxis
  329. .tickFormat(d3.format(',0f'));
  330. var _d3 = ($(element).find('svg').length > 0) ? d3.select($(element).find('svg')[0]) : d3.select($(element)[0]).append('svg');
  331. _d3.datum(_datum)
  332. .transition().duration(150)
  333. .each("end", options.onComplete != null ? options.onComplete : void(0))
  334. .call(_chart);
  335. nv.utils.windowResize(_chart.update);
  336. return _chart;
  337. }, function () {
  338. var _d3 = ($(element).find('svg').length > 0) ? d3.select($(element).find('svg')[0]) : d3.select($(element)[0]).append('svg');
  339. _d3.selectAll(".nv-line").on('click',
  340. function (d, i) {
  341. if (typeof options.onClick != "undefined") {
  342. chartsUpdatingState();
  343. options.onClick(d);
  344. }
  345. });
  346. });
  347. }
  348. }
  349. function barChartBuilder(element, options, isTimeline) {
  350. var _datum = options.transformer(options.datum);
  351. $(element).height(300);
  352. if ($(element).find('svg').length > 0 && (_datum.length == 0 || _datum[0].values.length == 0)) {
  353. $(element).find('svg').empty();
  354. }
  355. if (_datum.length > 0 && _datum[0].values.length > 0 && isNaN(_datum[0].values[0].y)) {
  356. _datum = [];
  357. $(element).find('svg').empty();
  358. }
  359. if ($(element).is(":visible")) {
  360. nv.addGraph(function () {
  361. var _chart;
  362. var insertLinebreaks = function (d) {
  363. var _el = d3.select(this);
  364. var _mom = moment(d);
  365. if (_mom != null && _mom.isValid()) {
  366. var _words = _mom.format("hh:mm:ss YYYY-MM-DD").split(" ");
  367. _el.text('');
  368. for (var i = 0; i < _words.length; i++) {
  369. var tspan = _el.append("tspan").text(_words[i]);
  370. if (i > 0) {
  371. tspan.attr("x", 0).attr("dy", '15');
  372. }
  373. }
  374. }
  375. };
  376. if (isTimeline) {
  377. if ($(element).find('svg').length > 0 && $(element).find('.nv-discreteBarWithAxes').length > 0) {
  378. $(element).find('svg').empty();
  379. }
  380. _chart = nv.models.multiBarWithBrushChart();
  381. if (_datum.length > 0 && _datum[0].values.length > 10) {
  382. _chart.enableSelection();
  383. }
  384. _chart.onSelectRange(function (from, to) {
  385. chartsUpdatingState();
  386. options.onSelectRange(from, to);
  387. });
  388. _chart.xAxis.tickFormat(d3.time.format("%Y-%m-%d %H:%M:%S"));
  389. _chart.multibar.hideable(true);
  390. _chart.multibar.stacked(typeof options.stacked != "undefined" ? options.stacked : false);
  391. _chart.onStateChange(options.onStateChange);
  392. _chart.onChartUpdate(function () {
  393. _d3.selectAll("g.nv-x.nv-axis g text").each(insertLinebreaks);
  394. });
  395. }
  396. else {
  397. var _isDiscrete = false;
  398. for (var j = 0; j < _datum.length; j++) {
  399. for (var i = 0; i < _datum[j].values.length; i++) {
  400. if (isNaN(_datum[j].values[i].x * 1)) {
  401. _isDiscrete = true;
  402. break;
  403. }
  404. }
  405. }
  406. if (_isDiscrete) {
  407. if ($(element).find('svg').length > 0 && $(element).find('.nv-multiBarWithLegend').length > 0) {
  408. $(element).find('svg').empty();
  409. }
  410. _chart = nv.models.growingDiscreteBarChart()
  411. .x(function (d) {
  412. return d.x
  413. })
  414. .y(function (d) {
  415. return d.y
  416. })
  417. .staggerLabels(true);
  418. }
  419. else {
  420. if ($(element).find('svg').length > 0 && $(element).find('.nv-discreteBarWithAxes').length > 0) {
  421. $(element).find('svg').empty();
  422. }
  423. _chart = nv.models.multiBarWithBrushChart();
  424. if (_datum.length > 0 && _datum[0].values.length > 10) {
  425. _chart.enableSelection();
  426. }
  427. _chart.xAxis.showMaxMin(false).tickFormat(d3.format(',0f'));
  428. _chart.multibar.hideable(true);
  429. _chart.multibar.stacked(typeof options.stacked != "undefined" ? options.stacked : false);
  430. _chart.onStateChange(options.onStateChange);
  431. _chart.onSelectRange(function (from, to) {
  432. chartsUpdatingState();
  433. options.onSelectRange(from, to);
  434. });
  435. }
  436. }
  437. _chart.transitionDuration(0);
  438. _chart.yAxis
  439. .tickFormat(d3.format(',0f'));
  440. var _d3 = ($(element).find('svg').length > 0) ? d3.select($(element).find('svg')[0]) : d3.select($(element)[0]).append('svg');
  441. _d3.datum(_datum)
  442. .transition().duration(150)
  443. .each("end", function () {
  444. if (options.onComplete != null) {
  445. options.onComplete();
  446. }
  447. if (isTimeline) {
  448. _d3.selectAll("g.nv-x.nv-axis g text").each(insertLinebreaks);
  449. }
  450. }).call(_chart);
  451. $.each(options.fqs(), function (cnt, item) {
  452. if (item.field() == options.field) {
  453. _chart.selectBars(item.filter());
  454. }
  455. });
  456. nv.utils.windowResize(_chart.update);
  457. return _chart;
  458. }, function () {
  459. var _d3 = ($(element).find('svg').length > 0) ? d3.select($(element).find('svg')[0]) : d3.select($(element)[0]).append('svg');
  460. _d3.selectAll(".nv-bar").on("click",
  461. function (d, i) {
  462. if (typeof options.onClick != "undefined") {
  463. chartsUpdatingState();
  464. options.onClick(d);
  465. }
  466. });
  467. });
  468. }
  469. }
  470. function chartsUpdatingState() {
  471. $(document).find("svg").css("opacity", "0.5");
  472. }