ko.charts.js 32 KB

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