ko.charts.js 31 KB

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