ko.charts.js 28 KB

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