ko.charts.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. if ($(element).parents(".tab-pane").length > 0){
  139. $(element).height($(element).parents(".tab-pane").height() - 100);
  140. }
  141. else {
  142. $(element).height(300);
  143. }
  144. var _map = null;
  145. if (element._map != null) {
  146. element._leaflet = false;
  147. element._map.remove();
  148. }
  149. if (_lats.length > 0 && _lngs.length > 0) {
  150. try {
  151. if (_map == null) {
  152. _map = L.map(element);
  153. L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
  154. attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributorss'
  155. }).addTo(_map);
  156. }
  157. _map.fitBounds(getMapBounds(_lats, _lngs));
  158. _data.forEach(function (item) {
  159. if (item.lng != null && item.lat != null) {
  160. var _marker = L.marker([item.lat, item.lng]).addTo(_map);
  161. if (item.label != null) {
  162. _marker.bindPopup(item.label);
  163. }
  164. }
  165. });
  166. if (_options.onComplete != null) {
  167. _options.onComplete();
  168. }
  169. }
  170. catch (err) {
  171. $.jHueNotify.error(err.message);
  172. }
  173. }
  174. element._map = _map;
  175. }
  176. };
  177. ko.bindingHandlers.mapChart = {
  178. render: function (element, valueAccessor) {
  179. var _options = valueAccessor();
  180. $(element).empty();
  181. $(element).css("position", "relative");
  182. $(element).css("marginLeft", "auto");
  183. $(element).css("marginRight", "auto");
  184. if (typeof _options.maxWidth != "undefined") {
  185. var _max = _options.maxWidth * 1;
  186. $(element).width(Math.min($(element).parent().width(), _max));
  187. }
  188. $(element).height($(element).width() / 2.23);
  189. var _scope = typeof _options.data.scope != "undefined" ? String(_options.data.scope) : "world";
  190. var _data = _options.transformer(_options.data);
  191. var _maxWeight = 0;
  192. $(_data).each(function (cnt, item) {
  193. if (item.value > _maxWeight) _maxWeight = item.value;
  194. });
  195. var _chunk = _maxWeight / _data.length;
  196. var _mapdata = {};
  197. var _maphovers = {};
  198. var _fills = {};
  199. var _noncountries = [];
  200. if (_options.isScale) {
  201. _fills["defaultFill"] = HueColors.WHITE;
  202. var _colors = HueColors.scale(HueColors.LIGHT_BLUE, HueColors.DARK_BLUE, _data.length);
  203. $(_colors).each(function (cnt, item) {
  204. _fills["fill_" + cnt] = item;
  205. });
  206. $(_data).each(function (cnt, item) {
  207. var _place = item.label.toUpperCase();
  208. if (_place != null) {
  209. _mapdata[_place] = {
  210. fillKey: "fill_" + (Math.floor(item.value / _chunk) - 1),
  211. id: _place,
  212. cat: item.obj.cat,
  213. value: item.obj.value,
  214. selected: item.obj.selected
  215. };
  216. _maphovers[_place] = item.value;
  217. }
  218. else {
  219. _noncountries.push(item);
  220. }
  221. });
  222. }
  223. else {
  224. _fills["defaultFill"] = HueColors.LIGHT_BLUE;
  225. _fills["selected"] = HueColors.DARK_BLUE;
  226. $(_data).each(function (cnt, item) {
  227. var _place = item.label.toUpperCase();
  228. if (_place != null) {
  229. _mapdata[_place] = {
  230. fillKey: "selected",
  231. id: _place,
  232. cat: item.obj.cat,
  233. value: item.obj.value,
  234. selected: item.obj.selected
  235. };
  236. _maphovers[_place] = item.value;
  237. }
  238. else {
  239. _noncountries.push(item);
  240. }
  241. });
  242. }
  243. var _map = null;
  244. function createDatamap(element, options, fills, mapData, nonCountries, mapHovers) {
  245. _map = new Datamap({
  246. element: element,
  247. fills: fills,
  248. scope: _scope,
  249. data: mapData,
  250. onClick: function (data) {
  251. if (typeof options.onClick != "undefined") {
  252. chartsUpdatingState();
  253. options.onClick(data);
  254. }
  255. },
  256. done: function (datamap) {
  257. var _bubbles = [];
  258. if (options.enableGeocoding) {
  259. $(nonCountries).each(function (cnt, item) {
  260. HueGeo.getCityCoordinates(item.label, function (lat, lng) {
  261. _bubbles.push({
  262. fillKey: "selected",
  263. label: item.label,
  264. value: item.value,
  265. radius: 4,
  266. latitude: lat,
  267. longitude: lng
  268. });
  269. _map.bubbles(_bubbles, {
  270. popupTemplate: function (geo, data) {
  271. return '<div class="hoverinfo" style="text-align: center"><strong>' + data.label + '</strong><br/>' + item.value + '</div>'
  272. }
  273. });
  274. });
  275. });
  276. }
  277. },
  278. geographyConfig: {
  279. hideAntarctica: true,
  280. borderWidth: 1,
  281. borderColor: HueColors.DARK_BLUE,
  282. highlightOnHover: true,
  283. highlightFillColor: HueColors.DARK_BLUE,
  284. highlightBorderColor: HueColors.BLUE,
  285. selectedFillColor: HueColors.DARKER_BLUE,
  286. selectedBorderColor: HueColors.DARKER_BLUE,
  287. popupTemplate: function (geography, data) {
  288. var _hover = '';
  289. if (data != null) {
  290. _hover = '<br/>' + mapHovers[data.id];
  291. }
  292. return '<div class="hoverinfo" style="text-align: center"><strong>' + geography.properties.name + '</strong>' + _hover + '</div>'
  293. }
  294. }
  295. });
  296. if (options.onComplete != null) {
  297. options.onComplete();
  298. }
  299. }
  300. createDatamap(element, _options, _fills, _mapdata, _noncountries, _maphovers)
  301. $(element).parents(".card-widget").one("resize", function () {
  302. ko.bindingHandlers.mapChart.render(element, valueAccessor);
  303. });
  304. },
  305. init: function (element, valueAccessor) {
  306. ko.bindingHandlers.mapChart.render(element, valueAccessor)
  307. },
  308. update: function (element, valueAccessor) {
  309. ko.bindingHandlers.mapChart.render(element, valueAccessor);
  310. }
  311. };
  312. function lineChartBuilder(element, options) {
  313. var _datum = options.transformer(options.datum);
  314. $(element).height(300);
  315. if ($(element).find('svg').length > 0 && (_datum.length == 0 || _datum[0].values.length == 0)) {
  316. $(element).find('svg').empty();
  317. }
  318. if (_datum.length > 0 && _datum[0].values.length > 0 && (isNaN(_datum[0].values[0].x) || isNaN(_datum[0].values[0].y))) {
  319. _datum = [];
  320. $(element).find('svg').empty();
  321. }
  322. if ($(element).is(":visible")) {
  323. nv.addGraph(function () {
  324. var _chart = nv.models.lineWithBrushChart();
  325. if (_datum.length > 0 && _datum[0].values.length > 10) {
  326. _chart.enableSelection();
  327. }
  328. if (options.showControls != null) {
  329. _chart.showControls(false);
  330. }
  331. _chart.onSelectRange(function (from, to) {
  332. chartsUpdatingState();
  333. options.onSelectRange(from, to);
  334. });
  335. _chart.xAxis.showMaxMin(false);
  336. _chart.yAxis
  337. .tickFormat(d3.format(',0f'));
  338. var _d3 = ($(element).find('svg').length > 0) ? d3.select($(element).find('svg')[0]) : d3.select($(element)[0]).append('svg');
  339. _d3.datum(_datum)
  340. .transition().duration(150)
  341. .each("end", options.onComplete != null ? options.onComplete : void(0))
  342. .call(_chart);
  343. nv.utils.windowResize(_chart.update);
  344. return _chart;
  345. }, function () {
  346. var _d3 = ($(element).find('svg').length > 0) ? d3.select($(element).find('svg')[0]) : d3.select($(element)[0]).append('svg');
  347. _d3.selectAll(".nv-line").on('click',
  348. function (d, i) {
  349. if (typeof options.onClick != "undefined") {
  350. chartsUpdatingState();
  351. options.onClick(d);
  352. }
  353. });
  354. });
  355. }
  356. }
  357. function barChartBuilder(element, options, isTimeline) {
  358. var _datum = options.transformer(options.datum);
  359. $(element).height(300);
  360. if ($(element).find('svg').length > 0 && (_datum.length == 0 || _datum[0].values.length == 0)) {
  361. $(element).find('svg').empty();
  362. }
  363. if (_datum.length > 0 && _datum[0].values.length > 0 && isNaN(_datum[0].values[0].y)) {
  364. _datum = [];
  365. $(element).find('svg').empty();
  366. }
  367. if ($(element).is(":visible")) {
  368. nv.addGraph(function () {
  369. var _chart;
  370. var insertLinebreaks = function (d) {
  371. var _el = d3.select(this);
  372. var _mom = moment(d);
  373. if (_mom != null && _mom.isValid()) {
  374. var _words = _mom.format("hh:mm:ss YYYY-MM-DD").split(" ");
  375. _el.text('');
  376. for (var i = 0; i < _words.length; i++) {
  377. var tspan = _el.append("tspan").text(_words[i]);
  378. if (i > 0) {
  379. tspan.attr("x", 0).attr("dy", '15');
  380. }
  381. }
  382. }
  383. };
  384. if (isTimeline) {
  385. if ($(element).find('svg').length > 0 && $(element).find('.nv-discreteBarWithAxes').length > 0) {
  386. $(element).find('svg').empty();
  387. }
  388. _chart = nv.models.multiBarWithBrushChart();
  389. if (_datum.length > 0 && _datum[0].values.length > 10) {
  390. _chart.enableSelection();
  391. }
  392. _chart.onSelectRange(function (from, to) {
  393. chartsUpdatingState();
  394. options.onSelectRange(from, to);
  395. });
  396. _chart.xAxis.tickFormat(d3.time.format("%Y-%m-%d %H:%M:%S"));
  397. _chart.multibar.hideable(true);
  398. _chart.multibar.stacked(typeof options.stacked != "undefined" ? options.stacked : false);
  399. _chart.onStateChange(options.onStateChange);
  400. _chart.onChartUpdate(function () {
  401. _d3.selectAll("g.nv-x.nv-axis g text").each(insertLinebreaks);
  402. });
  403. }
  404. else {
  405. var _isDiscrete = false;
  406. for (var j = 0; j < _datum.length; j++) {
  407. for (var i = 0; i < _datum[j].values.length; i++) {
  408. if (isNaN(_datum[j].values[i].x * 1)) {
  409. _isDiscrete = true;
  410. break;
  411. }
  412. }
  413. }
  414. if (_isDiscrete) {
  415. if ($(element).find('svg').length > 0 && $(element).find('.nv-multiBarWithLegend').length > 0) {
  416. $(element).find('svg').empty();
  417. }
  418. _chart = nv.models.growingDiscreteBarChart()
  419. .x(function (d) {
  420. return d.x
  421. })
  422. .y(function (d) {
  423. return d.y
  424. })
  425. .staggerLabels(true);
  426. }
  427. else {
  428. if ($(element).find('svg').length > 0 && $(element).find('.nv-discreteBarWithAxes').length > 0) {
  429. $(element).find('svg').empty();
  430. }
  431. _chart = nv.models.multiBarWithBrushChart();
  432. if (_datum.length > 0 && _datum[0].values.length > 10) {
  433. _chart.enableSelection();
  434. }
  435. _chart.xAxis.showMaxMin(false).tickFormat(d3.format(',0f'));
  436. _chart.multibar.hideable(true);
  437. _chart.multibar.stacked(typeof options.stacked != "undefined" ? options.stacked : false);
  438. _chart.onStateChange(options.onStateChange);
  439. _chart.onSelectRange(function (from, to) {
  440. chartsUpdatingState();
  441. options.onSelectRange(from, to);
  442. });
  443. }
  444. }
  445. _chart.transitionDuration(0);
  446. _chart.yAxis
  447. .tickFormat(d3.format(',0f'));
  448. var _d3 = ($(element).find('svg').length > 0) ? d3.select($(element).find('svg')[0]) : d3.select($(element)[0]).append('svg');
  449. _d3.datum(_datum)
  450. .transition().duration(150)
  451. .each("end", function () {
  452. if (options.onComplete != null) {
  453. options.onComplete();
  454. }
  455. if (isTimeline) {
  456. _d3.selectAll("g.nv-x.nv-axis g text").each(insertLinebreaks);
  457. }
  458. }).call(_chart);
  459. $.each(options.fqs(), function (cnt, item) {
  460. if (item.field() == options.field) {
  461. _chart.selectBars(item.filter());
  462. }
  463. });
  464. nv.utils.windowResize(_chart.update);
  465. return _chart;
  466. }, function () {
  467. var _d3 = ($(element).find('svg').length > 0) ? d3.select($(element).find('svg')[0]) : d3.select($(element)[0]).append('svg');
  468. _d3.selectAll(".nv-bar").on("click",
  469. function (d, i) {
  470. if (typeof options.onClick != "undefined") {
  471. chartsUpdatingState();
  472. options.onClick(d);
  473. }
  474. });
  475. });
  476. }
  477. }
  478. function chartsUpdatingState() {
  479. $(document).find("svg").css("opacity", "0.5");
  480. }