ko.charts.js 32 KB

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