ko.charts.js 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  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. GRADIENTMAP: "gradientmap",
  24. SCATTERCHART: "scatter"
  25. }
  26. };
  27. ko.bindingHandlers.pieChart = {
  28. update: function (element, valueAccessor) {
  29. var _options = valueAccessor();
  30. var _data = _options.transformer(_options.data);
  31. $(element).css("marginLeft", "auto");
  32. $(element).css("marginRight", "auto");
  33. if (typeof _options.maxWidth != "undefined") {
  34. var _max = _options.maxWidth * 1;
  35. $(element).width(Math.min($(element).parent().width(), _max));
  36. }
  37. if ($(element).find("svg").length > 0 && _data.length == 0) {
  38. $(element).find("svg").empty();
  39. }
  40. if (_data.length > 0 && isNaN(_data[0].value)) {
  41. _data = [];
  42. $(element).find("svg").empty();
  43. }
  44. if ($(element).is(":visible")) {
  45. nv.addGraph(function () {
  46. var _chart = nv.models.growingPieChart()
  47. .x(function (d) {
  48. return d.label
  49. })
  50. .y(function (d) {
  51. return d.value
  52. })
  53. .height($(element).width())
  54. .showLabels(true).showLegend(false);
  55. var _d3 = ($(element).find("svg").length > 0) ? d3.select($(element).find("svg")[0]) : d3.select($(element)[0]).append("svg");
  56. _d3.datum(_data)
  57. .transition().duration(150)
  58. .each("end", _options.onComplete != null ? _options.onComplete : void(0))
  59. .call(_chart);
  60. if (_options.fqs) {
  61. $.each(_options.fqs(), function (cnt, item) {
  62. if (item.field() == _options.field()) {
  63. _chart.selectSlices($.map(item.filter(), function (it) {
  64. return it.value();
  65. }));
  66. }
  67. });
  68. }
  69. var _resizeTimeout = -1;
  70. nv.utils.windowResize(function(){
  71. window.clearTimeout(_resizeTimeout);
  72. _resizeTimeout = window.setTimeout(function(){
  73. _chart.update();
  74. }, 200);
  75. });
  76. $(element).on("forceUpdate", function(){
  77. _chart.update();
  78. });
  79. $(element).height($(element).width());
  80. var _parentSelector = typeof _options.parentSelector != "undefined" ? _options.parentSelector : ".card-widget";
  81. $(element).parents(_parentSelector).on("resize", function () {
  82. if (typeof _options.maxWidth != "undefined") {
  83. var _max = _options.maxWidth * 1;
  84. $(element).width(Math.min($(element).parent().width(), _max));
  85. }
  86. $(element).height($(element).width());
  87. _chart.update();
  88. });
  89. return _chart;
  90. }, function () {
  91. var _d3 = ($(element).find("svg").length > 0) ? d3.select($(element).find("svg")[0]) : d3.select($(element)[0]).append("svg");
  92. _d3.selectAll(".nv-slice").on("click",
  93. function (d, i) {
  94. if (typeof _options.onClick != "undefined") {
  95. chartsUpdatingState();
  96. _options.onClick(d);
  97. }
  98. });
  99. });
  100. }
  101. }
  102. };
  103. ko.bindingHandlers.barChart = {
  104. update: function (element, valueAccessor) {
  105. barChartBuilder(element, valueAccessor(), false);
  106. }
  107. };
  108. ko.bindingHandlers.timelineChart = {
  109. update: function (element, valueAccessor) {
  110. barChartBuilder(element, valueAccessor(), true);
  111. }
  112. };
  113. ko.bindingHandlers.lineChart = {
  114. update: function (element, valueAccessor) {
  115. lineChartBuilder(element, valueAccessor());
  116. }
  117. };
  118. ko.bindingHandlers.leafletMapChart = {
  119. update: function (element, valueAccessor) {
  120. var _options = valueAccessor();
  121. var _data = _options.transformer(valueAccessor().datum);
  122. function getMapBounds(lats, lngs) {
  123. lats = lats.sort();
  124. lngs = lngs.sort();
  125. return [
  126. [lats[lats.length - 1], lngs[lngs.length - 1]], // north-east
  127. [lats[0], lngs[0]] // south-west
  128. ]
  129. }
  130. if ($(element).data("map") != null) {
  131. try {
  132. $(element).data("map").remove();
  133. }
  134. catch (err) {
  135. if (typeof console != "undefined") {
  136. console.error(err);
  137. }
  138. }
  139. }
  140. var _lats = [];
  141. _data.forEach(function (item) {
  142. if (item.lat != null && $.isNumeric(item.lat)) {
  143. _lats.push(item.lat);
  144. }
  145. });
  146. var _lngs = [];
  147. _data.forEach(function (item) {
  148. if (item.lng != null && $.isNumeric(item.lng)) {
  149. _lngs.push(item.lng);
  150. }
  151. });
  152. if (_options.height != null){
  153. $(element).height(_options.height*1);
  154. }
  155. else {
  156. if ($(element).parents(".tab-pane").length > 0) {
  157. $(element).height($(element).parents(".tab-pane").height() - 100);
  158. }
  159. else {
  160. $(element).height(300);
  161. }
  162. }
  163. if (((_options.visible != null && _options.visible) || _options.visible == null || typeof _options == "undefined") && _data.length > 0) {
  164. $(element).show();
  165. }
  166. else {
  167. $(element).hide();
  168. }
  169. var _map = null;
  170. if (element._map != null) {
  171. element._leaflet = false;
  172. element._map.remove();
  173. }
  174. if (_lats.length > 0 && _lngs.length > 0) {
  175. try {
  176. if (_map == null) {
  177. _map = L.map(element);
  178. L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
  179. attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  180. }).addTo(_map);
  181. }
  182. _map.fitBounds(getMapBounds(_lats, _lngs));
  183. _data.forEach(function (item) {
  184. if (item.lng != null && item.lat != null) {
  185. var _addMarker = false;
  186. try {
  187. var _latLngObj = L.latLng(item.lat, item.lng);
  188. _addMarker = true;
  189. }
  190. catch (e) {
  191. if (typeof console != "undefined") {
  192. console.error(e);
  193. }
  194. }
  195. if (_addMarker) {
  196. var _marker = L.marker([item.lat, item.lng]).addTo(_map);
  197. if (item.label != null) {
  198. _marker.bindPopup(item.label);
  199. }
  200. }
  201. }
  202. });
  203. if (_options.onComplete != null) {
  204. _options.onComplete();
  205. }
  206. }
  207. catch (err) {
  208. $.jHueNotify.error(err.message);
  209. }
  210. }
  211. element._map = _map;
  212. }
  213. };
  214. ko.bindingHandlers.mapChart = {
  215. render: function (element, valueAccessor) {
  216. var _options = valueAccessor();
  217. $(element).empty();
  218. $(element).css("position", "relative");
  219. $(element).css("marginLeft", "auto");
  220. $(element).css("marginRight", "auto");
  221. if (typeof _options.maxWidth != "undefined") {
  222. var _max = _options.maxWidth * 1;
  223. $(element).width(Math.min($(element).parent().width(), _max));
  224. }
  225. $(element).height($(element).width() / 2.23);
  226. var _scope = typeof _options.data.scope != "undefined" ? String(_options.data.scope) : "world";
  227. var _data = _options.transformer(_options.data);
  228. var _maxWeight = 0;
  229. $(_data).each(function (cnt, item) {
  230. if (item.value > _maxWeight) _maxWeight = item.value;
  231. });
  232. var _chunk = _maxWeight / _data.length;
  233. var _mapdata = {};
  234. var _maphovers = {};
  235. var _fills = {};
  236. var _noncountries = [];
  237. if (_options.isScale) {
  238. _fills["defaultFill"] = HueColors.WHITE;
  239. var _colors = HueColors.scale(HueColors.LIGHT_BLUE, HueColors.DARK_BLUE, _data.length);
  240. $(_colors).each(function (cnt, item) {
  241. _fills["fill_" + cnt] = item;
  242. });
  243. $(_data).each(function (cnt, item) {
  244. var _place = typeof item.label == "String" ? item.label.toUpperCase() : item.label;
  245. if (_place != null) {
  246. _mapdata[_place] = {
  247. fillKey: "fill_" + (Math.floor(item.value / _chunk) - 1),
  248. id: _place,
  249. cat: item.obj.cat,
  250. value: item.obj.value,
  251. selected: item.obj.selected
  252. };
  253. _maphovers[_place] = item.value;
  254. }
  255. else {
  256. _noncountries.push(item);
  257. }
  258. });
  259. }
  260. else {
  261. _fills["defaultFill"] = HueColors.LIGHT_BLUE;
  262. _fills["selected"] = HueColors.DARK_BLUE;
  263. $(_data).each(function (cnt, item) {
  264. var _place = item.label.toUpperCase();
  265. if (_place != null) {
  266. _mapdata[_place] = {
  267. fillKey: "selected",
  268. id: _place,
  269. cat: item.obj.cat,
  270. value: item.obj.value,
  271. selected: item.obj.selected
  272. };
  273. _maphovers[_place] = item.value;
  274. }
  275. else {
  276. _noncountries.push(item);
  277. }
  278. });
  279. }
  280. var _map = null;
  281. function createDatamap(element, options, fills, mapData, nonCountries, mapHovers) {
  282. _map = new Datamap({
  283. element: element,
  284. fills: fills,
  285. scope: _scope,
  286. data: mapData,
  287. onClick: function (data) {
  288. if (typeof options.onClick != "undefined") {
  289. chartsUpdatingState();
  290. options.onClick(data);
  291. }
  292. },
  293. done: function (datamap) {
  294. var _bubbles = [];
  295. if (options.enableGeocoding) {
  296. $(nonCountries).each(function (cnt, item) {
  297. HueGeo.getCityCoordinates(item.label, function (lat, lng) {
  298. _bubbles.push({
  299. fillKey: "selected",
  300. label: item.label,
  301. value: item.value,
  302. radius: 4,
  303. latitude: lat,
  304. longitude: lng
  305. });
  306. _map.bubbles(_bubbles, {
  307. popupTemplate: function (geo, data) {
  308. return '<div class="hoverinfo" style="text-align: center"><strong>' + data.label + '</strong><br/>' + item.value + '</div>'
  309. }
  310. });
  311. });
  312. });
  313. }
  314. },
  315. geographyConfig: {
  316. hideAntarctica: true,
  317. borderWidth: 1,
  318. borderColor: HueColors.DARK_BLUE,
  319. highlightOnHover: true,
  320. highlightFillColor: HueColors.DARK_BLUE,
  321. highlightBorderColor: HueColors.BLUE,
  322. selectedFillColor: HueColors.DARKER_BLUE,
  323. selectedBorderColor: HueColors.DARKER_BLUE,
  324. popupTemplate: function (geography, data) {
  325. var _hover = '';
  326. if (data != null) {
  327. _hover = '<br/>' + mapHovers[data.id];
  328. }
  329. return '<div class="hoverinfo" style="text-align: center"><strong>' + geography.properties.name + '</strong>' + _hover + '</div>'
  330. }
  331. }
  332. });
  333. if (options.onComplete != null) {
  334. options.onComplete();
  335. }
  336. }
  337. createDatamap(element, _options, _fills, _mapdata, _noncountries, _maphovers)
  338. var _parentSelector = typeof _options.parentSelector != "undefined" ? _options.parentSelector : ".card-widget";
  339. $(element).parents(_parentSelector).one("resize", function () {
  340. ko.bindingHandlers.mapChart.render(element, valueAccessor);
  341. });
  342. },
  343. init: function (element, valueAccessor) {
  344. ko.bindingHandlers.mapChart.render(element, valueAccessor);
  345. },
  346. update: function (element, valueAccessor, allBindingsAccessor) {
  347. if (typeof allBindingsAccessor().mapChart.visible != "undefined"){
  348. if ((typeof allBindingsAccessor().mapChart.visible == "boolean" && allBindingsAccessor().mapChart.visible) || (typeof allBindingsAccessor().mapChart.visible == "function" && allBindingsAccessor().mapChart.visible())) {
  349. $(element).show();
  350. ko.bindingHandlers.mapChart.render(element, valueAccessor);
  351. }
  352. else {
  353. $(element).hide();
  354. }
  355. }
  356. }
  357. };
  358. ko.bindingHandlers.scatterChart = {
  359. update: function (element, valueAccessor) {
  360. var options = valueAccessor();
  361. var _datum = options.transformer(options.datum);
  362. $(element).height(300);
  363. if ($(element).find("svg").length > 0 && (_datum.length == 0 || _datum[0].values.length == 0)) {
  364. $(element).find("svg").empty();
  365. }
  366. if (_datum.length > 0 && _datum[0].values.length > 0 && (isNaN(_datum[0].values[0].x) || isNaN(_datum[0].values[0].y))) {
  367. _datum = [];
  368. $(element).find("svg").empty();
  369. }
  370. if ($(element).is(":visible")) {
  371. nv.addGraph(function () {
  372. var _chart = nv.models.scatterChart()
  373. .transitionDuration(350)
  374. .color(d3.scale.category10().range());
  375. _chart.tooltipContent(function(key, x, y, obj) {
  376. return '<h3>' + key + '</h3><div class="center">' + obj.point.size + '</div>';
  377. });
  378. _chart.xAxis.tickFormat(d3.format('.02f'));
  379. _chart.yAxis.tickFormat(d3.format('.02f'));
  380. _chart.scatter.onlyCircles(true);
  381. var _d3 = ($(element).find("svg").length > 0) ? d3.select($(element).find("svg")[0]) : d3.select($(element)[0]).append("svg");
  382. _d3.datum(_datum)
  383. .transition().duration(150)
  384. .each("end", options.onComplete != null ? options.onComplete : void(0))
  385. .call(_chart);
  386. var _resizeTimeout = -1;
  387. nv.utils.windowResize(function(){
  388. window.clearTimeout(_resizeTimeout);
  389. _resizeTimeout = window.setTimeout(function(){
  390. _chart.update();
  391. }, 200);
  392. });
  393. $(element).on("forceUpdate", function(){
  394. _chart.update();
  395. });
  396. return _chart;
  397. });
  398. }
  399. }
  400. };
  401. function lineChartBuilder(element, options) {
  402. var _datum = options.transformer(options.datum);
  403. $(element).height(300);
  404. if ($(element).find("svg").length > 0 && (_datum.length == 0 || _datum[0].values.length == 0)) {
  405. $(element).find("svg").empty();
  406. }
  407. if (_datum.length > 0 && _datum[0].values.length > 0 && (isNaN(_datum[0].values[0].x) || isNaN(_datum[0].values[0].y))) {
  408. _datum = [];
  409. $(element).find("svg").empty();
  410. }
  411. if ($(element).is(":visible")) {
  412. nv.addGraph(function () {
  413. var _chart = nv.models.lineWithBrushChart();
  414. if (_datum.length > 0 && _datum[0].values.length > 10) {
  415. _chart.enableSelection();
  416. }
  417. if (options.showControls != null) {
  418. _chart.showControls(false);
  419. }
  420. _chart.onSelectRange(function (from, to) {
  421. chartsUpdatingState();
  422. options.onSelectRange(from, to);
  423. });
  424. _chart.xAxis.showMaxMin(false);
  425. _chart.yAxis
  426. .tickFormat(d3.format(",0f"));
  427. var _d3 = ($(element).find("svg").length > 0) ? d3.select($(element).find("svg")[0]) : d3.select($(element)[0]).append("svg");
  428. _d3.datum(_datum)
  429. .transition().duration(150)
  430. .each("end", options.onComplete != null ? options.onComplete : void(0))
  431. .call(_chart);
  432. var _resizeTimeout = -1;
  433. nv.utils.windowResize(function(){
  434. window.clearTimeout(_resizeTimeout);
  435. _resizeTimeout = window.setTimeout(function(){
  436. _chart.update();
  437. }, 200);
  438. });
  439. $(element).on("forceUpdate", function(){
  440. _chart.update();
  441. });
  442. return _chart;
  443. }, function () {
  444. var _d3 = ($(element).find("svg").length > 0) ? d3.select($(element).find("svg")[0]) : d3.select($(element)[0]).append("svg");
  445. _d3.selectAll(".nv-line").on("click",
  446. function (d, i) {
  447. if (typeof options.onClick != "undefined") {
  448. chartsUpdatingState();
  449. options.onClick(d);
  450. }
  451. });
  452. });
  453. }
  454. }
  455. function barChartBuilder(element, options, isTimeline) {
  456. var _datum = options.transformer(options.datum);
  457. $(element).height(300);
  458. var _isPivot = options.isPivot != null ? options.isPivot : false;
  459. var _hideSelection = options.hideSelection != null ? options.hideSelection : false;
  460. if ($(element).find("svg").length > 0 && (_datum.length == 0 || _datum[0].values.length == 0)) {
  461. $(element).find("svg").empty();
  462. }
  463. if (_datum.length > 0 && _datum[0].values.length > 0 && isNaN(_datum[0].values[0].y)) {
  464. _datum = [];
  465. $(element).find("svg").empty();
  466. }
  467. if ($(element).is(":visible")) {
  468. nv.addGraph(function () {
  469. var _chart;
  470. var insertLinebreaks = function (d) {
  471. var _el = d3.select(this);
  472. var _mom = moment(d);
  473. if (_mom != null && _mom.isValid()) {
  474. var _words = _mom.format("HH:mm:ss YYYY-MM-DD").split(" ");
  475. _el.text("");
  476. for (var i = 0; i < _words.length; i++) {
  477. var tspan = _el.append("tspan").text(_words[i]);
  478. if (i > 0) {
  479. tspan.attr("x", 0).attr("dy", "15");
  480. }
  481. }
  482. }
  483. };
  484. if (isTimeline) {
  485. if ($(element).find("svg").length > 0 && $(element).find(".nv-discreteBarWithAxes").length > 0) {
  486. $(element).find("svg").empty();
  487. }
  488. _chart = nv.models.multiBarWithBrushChart();
  489. if (_datum.length > 0 && _datum[0].values.length > 10) {
  490. _chart.enableSelection();
  491. }
  492. _chart.onSelectRange(function (from, to) {
  493. chartsUpdatingState();
  494. options.onSelectRange(from, to);
  495. });
  496. _chart.xAxis.tickFormat(d3.time.format("%Y-%m-%d %H:%M:%S"));
  497. _chart.multibar.hideable(true);
  498. _chart.multibar.stacked(typeof options.stacked != "undefined" ? options.stacked : false);
  499. _chart.onStateChange(options.onStateChange);
  500. _chart.onChartUpdate(function () {
  501. _d3.selectAll("g.nv-x.nv-axis g text").each(insertLinebreaks);
  502. });
  503. }
  504. else {
  505. var _isDiscrete = false;
  506. for (var j = 0; j < _datum.length; j++) {
  507. for (var i = 0; i < _datum[j].values.length; i++) {
  508. if (isNaN(_datum[j].values[i].x * 1)) {
  509. _isDiscrete = true;
  510. break;
  511. }
  512. }
  513. }
  514. if (_isDiscrete && !_isPivot) {
  515. if ($(element).find("svg").length > 0 && $(element).find(".nv-multiBarWithLegend").length > 0) {
  516. $(element).find("svg").empty();
  517. }
  518. _chart = nv.models.growingDiscreteBarChart()
  519. .x(function (d) {
  520. return d.x
  521. })
  522. .y(function (d) {
  523. return d.y
  524. })
  525. .staggerLabels(true);
  526. }
  527. else {
  528. if ($(element).find("svg").length > 0 && $(element).find(".nv-discreteBarWithAxes").length > 0) {
  529. $(element).find("svg").empty();
  530. }
  531. _chart = nv.models.multiBarWithBrushChart();
  532. if (_datum.length > 0 && _datum[0].values.length > 10) {
  533. _chart.enableSelection();
  534. }
  535. if (_isPivot || _hideSelection) {
  536. _chart.hideSelection();
  537. }
  538. else {
  539. _chart.xAxis.showMaxMin(false).tickFormat(d3.format(",0f"));
  540. }
  541. _chart.multibar.hideable(true);
  542. _chart.multibar.stacked(typeof options.stacked != "undefined" ? options.stacked : false);
  543. _chart.onStateChange(options.onStateChange);
  544. _chart.onSelectRange(function (from, to) {
  545. chartsUpdatingState();
  546. options.onSelectRange(from, to);
  547. });
  548. }
  549. }
  550. if ($(element).width() < 300 && typeof _chart.showLegend != "undefined"){
  551. _chart.showLegend(false);
  552. }
  553. _chart.transitionDuration(0);
  554. _chart.yAxis
  555. .tickFormat(d3.format(",0f"));
  556. var _d3 = ($(element).find("svg").length > 0) ? d3.select($(element).find("svg")[0]) : d3.select($(element)[0]).append("svg");
  557. _d3.datum(_datum)
  558. .transition().duration(150)
  559. .each("end", function () {
  560. if (options.onComplete != null) {
  561. options.onComplete();
  562. }
  563. if (isTimeline) {
  564. _d3.selectAll("g.nv-x.nv-axis g text").each(insertLinebreaks);
  565. }
  566. }).call(_chart);
  567. if (_chart.selectBars) {
  568. $.each(options.fqs(), function (cnt, item) {
  569. if (item.field() == options.field) {
  570. _chart.selectBars($.map(item.filter(), function (it) {
  571. return it.value();
  572. }));
  573. }
  574. if (item.field().indexOf(":") > -1) {
  575. _chart.selectBars({
  576. field: item.field(),
  577. selected: $.map(item.filter(), function (it) {
  578. return it.value();
  579. })
  580. });
  581. }
  582. });
  583. }
  584. var _resizeTimeout = -1;
  585. nv.utils.windowResize(function(){
  586. window.clearTimeout(_resizeTimeout);
  587. _resizeTimeout = window.setTimeout(function(){
  588. _chart.update();
  589. }, 200);
  590. });
  591. $(element).on("forceUpdate", function(){
  592. _chart.update();
  593. });
  594. return _chart;
  595. }, function () {
  596. var _d3 = ($(element).find("svg").length > 0) ? d3.select($(element).find("svg")[0]) : d3.select($(element)[0]).append("svg");
  597. _d3.selectAll(".nv-bar").on("click",
  598. function (d, i) {
  599. if (typeof options.onClick != "undefined") {
  600. chartsUpdatingState();
  601. options.onClick(d);
  602. }
  603. });
  604. });
  605. }
  606. }
  607. ko.bindingHandlers.partitionChart = {
  608. update: function (element, valueAccessor) {
  609. var MIN_HEIGHT_FOR_TOOLTIP = 24;
  610. var _options = valueAccessor();
  611. var _data = _options.transformer(valueAccessor().datum);
  612. var _w = $(element).width(),
  613. _h = 300,
  614. _x = d3.scale.linear().range([0, _w]),
  615. _y = d3.scale.linear().range([0, _h]);
  616. var _tip = d3.tip()
  617. .attr("class", "d3-tip")
  618. .html(function (d) {
  619. if (d.depth == 0) {
  620. return _options.tooltip || "";
  621. }
  622. else if (d.depth > 0 && d.depth < 2) {
  623. return d.name + " (" + d.value + ")";
  624. }
  625. else {
  626. return d.parent.name + " - " + d.name + " (" + d.value + ")";
  627. }
  628. })
  629. .offset([-12, 0])
  630. var _svg = d3.select(element).append("svg:svg");
  631. _svg.call(_tip);
  632. var _vis = ($(element).find("svg").length > 0) ? d3.select($(element).find("svg")[0]) : d3.select($(element)[0]).append("svg");
  633. _vis.attr("class", "partitionChart")
  634. .style("width", _w + "px")
  635. .style("height", _h + "px")
  636. .append("svg:svg")
  637. .attr("width", _w)
  638. .attr("height", _h);
  639. var _partition = d3.layout.partition()
  640. .value(function (d) {
  641. return d.size;
  642. });
  643. var g = _vis.selectAll("g")
  644. .data(_partition.nodes(_data))
  645. .enter().append("svg:g")
  646. .attr("transform", function (d) {
  647. return "translate(" + _x(d.y) + "," + _y(d.x) + ")";
  648. })
  649. .on("mouseover", function (d, i) {
  650. if (element.querySelectorAll("rect")[i].getBBox().height < MIN_HEIGHT_FOR_TOOLTIP || d.depth == 0) {
  651. _tip.attr("class", "d3-tip").show(d);
  652. }
  653. if (this.__data__.parent == undefined) return;
  654. d3.select(this).select("rect").classed("mouseover", true)
  655. })
  656. .on("mouseout", function (d, i) {
  657. if (element.querySelectorAll("rect")[i].getBBox().height < MIN_HEIGHT_FOR_TOOLTIP || d.depth == 0) {
  658. _tip.attr("class", "d3-tip").show(d);
  659. _tip.hide();
  660. }
  661. d3.select(this).select("rect").classed("mouseover", false)
  662. });
  663. if (typeof _options.zoomable == "undefined" || _options.zoomable) {
  664. g.on("click", click)
  665. .on("dblclick", function (d, i) {
  666. if (typeof _options.onClick != "undefined" && d.depth > 0) {
  667. chartsUpdatingState();
  668. _options.onClick(d);
  669. }
  670. });
  671. }
  672. else {
  673. g.on("click", function (d, i) {
  674. if (typeof _options.onClick != "undefined" && d.depth > 0) {
  675. chartsUpdatingState();
  676. _options.onClick(d);
  677. }
  678. });
  679. }
  680. var _kx = _w / _data.dx,
  681. _ky = _h / 1;
  682. var _colors = HueColors.scale(HueColors.DARK_BLUE, HueColors.BLUE, 5)
  683. g.append("svg:rect")
  684. .attr("width", _data.dy * _kx)
  685. .attr("height", function (d) {
  686. return d.dx * _ky;
  687. })
  688. .attr("class", function (d) {
  689. return d.children ? "parent" : "child";
  690. })
  691. .attr("stroke", function (d) {
  692. return HueColors.DARK_BLUE;
  693. })
  694. .attr("fill", function (d, i) {
  695. var _fill = _colors[d.depth] || _colors[_colors.length - 1];
  696. if (d.obj && _options.fqs) {
  697. $.each(_options.fqs(), function (cnt, item) {
  698. $.each(item.filter(), function (icnt, filter) {
  699. if (filter.value() == d.obj.fq_values) {
  700. _fill = HueColors.ORANGE;
  701. }
  702. });
  703. });
  704. }
  705. return _fill;
  706. });
  707. g.append("svg:text")
  708. .attr("transform", transform)
  709. .attr("dy", ".35em")
  710. .style("opacity", function (d) {
  711. return d.dx * _ky > 12 ? 1 : 0;
  712. })
  713. .text(function (d) {
  714. if (d.depth < 2) {
  715. return d.name + " (" + d.value + ")";
  716. }
  717. else {
  718. return d.parent.name + " - " + d.name + " (" + d.value + ")";
  719. }
  720. });
  721. d3.select(window)
  722. .on("click", function () {
  723. click(_data);
  724. });
  725. function click(d) {
  726. _tip.hide();
  727. if (!d.children) return;
  728. _kx = (d.y ? _w - 40 : _w) / (1 - d.y);
  729. _ky = _h / d.dx;
  730. _x.domain([d.y, 1]).range([d.y ? 40 : 0, _w]);
  731. _y.domain([d.x, d.x + d.dx]);
  732. var t = g.transition()
  733. .duration(d3.event.altKey ? 7500 : 750)
  734. .attr("transform", function (d) {
  735. return "translate(" + _x(d.y) + "," + _y(d.x) + ")";
  736. });
  737. t.select("rect")
  738. .attr("width", d.dy * _kx)
  739. .attr("height", function (d) {
  740. return d.dx * _ky;
  741. });
  742. t.select("text")
  743. .attr("transform", transform)
  744. .style("opacity", function (d) {
  745. return d.dx * _ky > 12 ? 1 : 0;
  746. });
  747. d3.event.stopPropagation();
  748. }
  749. function transform(d) {
  750. return "translate(8," + d.dx * _ky / 2 + ")";
  751. }
  752. }
  753. };
  754. function chartsUpdatingState() {
  755. $(document).find("svg").css("opacity", "0.5");
  756. }
  757. var tipBuilder = function () {
  758. var direction = d3_tip_direction,
  759. offset = d3_tip_offset,
  760. html = d3_tip_html,
  761. node = initNode(),
  762. svg = null,
  763. point = null,
  764. target = null
  765. function tip(vis) {
  766. svg = getSVGNode(vis)
  767. point = svg.createSVGPoint()
  768. document.body.appendChild(node)
  769. }
  770. // Public - show the tooltip on the screen
  771. //
  772. // Returns a tip
  773. tip.show = function () {
  774. var args = Array.prototype.slice.call(arguments)
  775. if (args[args.length - 1] instanceof SVGElement) target = args.pop()
  776. var content = html.apply(this, args),
  777. poffset = offset.apply(this, args),
  778. dir = direction.apply(this, args),
  779. nodel = d3.select(node), i = 0,
  780. coords
  781. nodel.html(content)
  782. .style({ opacity: 1, "pointer-events": "all" })
  783. while (i--) nodel.classed(directions[i], false)
  784. coords = direction_callbacks.get(dir).apply(this)
  785. nodel.classed(dir, true).style({
  786. top: (coords.top + poffset[0]) + "px",
  787. left: (coords.left + poffset[1]) + "px"
  788. })
  789. return tip
  790. }
  791. // Public - hide the tooltip
  792. //
  793. // Returns a tip
  794. tip.hide = function () {
  795. nodel = d3.select(node)
  796. nodel.style({ opacity: 0, "pointer-events": "none" })
  797. return tip
  798. }
  799. // Public: Proxy attr calls to the d3 tip container. Sets or gets attribute value.
  800. //
  801. // n - name of the attribute
  802. // v - value of the attribute
  803. //
  804. // Returns tip or attribute value
  805. tip.attr = function (n, v) {
  806. if (arguments.length < 2 && typeof n === "string") {
  807. return d3.select(node).attr(n)
  808. } else {
  809. var args = Array.prototype.slice.call(arguments)
  810. d3.selection.prototype.attr.apply(d3.select(node), args)
  811. }
  812. return tip
  813. }
  814. // Public: Proxy style calls to the d3 tip container. Sets or gets a style value.
  815. //
  816. // n - name of the property
  817. // v - value of the property
  818. //
  819. // Returns tip or style property value
  820. tip.style = function (n, v) {
  821. if (arguments.length < 2 && typeof n === "string") {
  822. return d3.select(node).style(n)
  823. } else {
  824. var args = Array.prototype.slice.call(arguments)
  825. d3.selection.prototype.style.apply(d3.select(node), args)
  826. }
  827. return tip
  828. }
  829. // Public: Set or get the direction of the tooltip
  830. //
  831. // v - One of n(north), s(south), e(east), or w(west), nw(northwest),
  832. // sw(southwest), ne(northeast) or se(southeast)
  833. //
  834. // Returns tip or direction
  835. tip.direction = function (v) {
  836. if (!arguments.length) return direction
  837. direction = v == null ? v : d3.functor(v)
  838. return tip
  839. }
  840. // Public: Sets or gets the offset of the tip
  841. //
  842. // v - Array of [x, y] offset
  843. //
  844. // Returns offset or
  845. tip.offset = function (v) {
  846. if (!arguments.length) return offset
  847. offset = v == null ? v : d3.functor(v)
  848. return tip
  849. }
  850. // Public: sets or gets the html value of the tooltip
  851. //
  852. // v - String value of the tip
  853. //
  854. // Returns html value or tip
  855. tip.html = function (v) {
  856. if (!arguments.length) return html
  857. html = v == null ? v : d3.functor(v)
  858. return tip
  859. }
  860. function d3_tip_direction() {
  861. return "n"
  862. }
  863. function d3_tip_offset() {
  864. return [0, 0]
  865. }
  866. function d3_tip_html() {
  867. return " "
  868. }
  869. var direction_callbacks = d3.map({
  870. n: direction_n,
  871. s: direction_s,
  872. e: direction_e,
  873. w: direction_w,
  874. nw: direction_nw,
  875. ne: direction_ne,
  876. sw: direction_sw,
  877. se: direction_se
  878. }),
  879. directions = direction_callbacks.keys()
  880. function direction_n() {
  881. var bbox = getScreenBBox()
  882. return {
  883. top: bbox.n.y - node.offsetHeight,
  884. left: bbox.n.x - node.offsetWidth / 2
  885. }
  886. }
  887. function direction_s() {
  888. var bbox = getScreenBBox()
  889. return {
  890. top: bbox.s.y,
  891. left: bbox.s.x - node.offsetWidth / 2
  892. }
  893. }
  894. function direction_e() {
  895. var bbox = getScreenBBox()
  896. return {
  897. top: bbox.e.y - node.offsetHeight / 2,
  898. left: bbox.e.x
  899. }
  900. }
  901. function direction_w() {
  902. var bbox = getScreenBBox()
  903. return {
  904. top: bbox.w.y - node.offsetHeight / 2,
  905. left: bbox.w.x - node.offsetWidth
  906. }
  907. }
  908. function direction_nw() {
  909. var bbox = getScreenBBox()
  910. return {
  911. top: bbox.nw.y - node.offsetHeight,
  912. left: bbox.nw.x - node.offsetWidth
  913. }
  914. }
  915. function direction_ne() {
  916. var bbox = getScreenBBox()
  917. return {
  918. top: bbox.ne.y - node.offsetHeight,
  919. left: bbox.ne.x
  920. }
  921. }
  922. function direction_sw() {
  923. var bbox = getScreenBBox()
  924. return {
  925. top: bbox.sw.y,
  926. left: bbox.sw.x - node.offsetWidth
  927. }
  928. }
  929. function direction_se() {
  930. var bbox = getScreenBBox()
  931. return {
  932. top: bbox.se.y,
  933. left: bbox.e.x
  934. }
  935. }
  936. function initNode() {
  937. var node = d3.select(document.createElement("div"))
  938. node.style({
  939. position: "absolute",
  940. opacity: 0,
  941. pointerEvents: "none",
  942. boxSizing: "border-box"
  943. })
  944. return node.node()
  945. }
  946. function getSVGNode(el) {
  947. el = el.node()
  948. if (el != null) {
  949. if (el.tagName != null && el.tagName.toLowerCase() == "svg")
  950. return el
  951. return el.ownerSVGElement
  952. }
  953. }
  954. // Private - gets the screen coordinates of a shape
  955. //
  956. // Given a shape on the screen, will return an SVGPoint for the directions
  957. // n(north), s(south), e(east), w(west), ne(northeast), se(southeast), nw(northwest),
  958. // sw(southwest).
  959. //
  960. // +-+-+
  961. // | |
  962. // + +
  963. // | |
  964. // +-+-+
  965. //
  966. // Returns an Object {n, s, e, w, nw, sw, ne, se}
  967. function getScreenBBox() {
  968. var targetel = target || d3.event.target,
  969. bbox = {},
  970. matrix = targetel.getScreenCTM(),
  971. tbbox = targetel.getBBox(),
  972. width = tbbox.width,
  973. height = tbbox.height,
  974. x = tbbox.x,
  975. y = tbbox.y,
  976. scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
  977. scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft
  978. point.x = x + scrollLeft
  979. point.y = y + scrollTop
  980. bbox.nw = point.matrixTransform(matrix)
  981. point.x += width
  982. bbox.ne = point.matrixTransform(matrix)
  983. point.y += height
  984. bbox.se = point.matrixTransform(matrix)
  985. point.x -= width
  986. bbox.sw = point.matrixTransform(matrix)
  987. point.y -= height / 2
  988. bbox.w = point.matrixTransform(matrix)
  989. point.x += width
  990. bbox.e = point.matrixTransform(matrix)
  991. point.x -= width / 2
  992. point.y -= height / 2
  993. bbox.n = point.matrixTransform(matrix)
  994. point.y += height
  995. bbox.s = point.matrixTransform(matrix)
  996. return bbox
  997. }
  998. return tip
  999. };
  1000. d3.tip = tipBuilder;