ko.charts.js 29 KB

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