ko.charts.js 30 KB

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