ko.charts.js 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  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. var _hideSelection = options.hideSelection != null ? options.hideSelection : false;
  382. if ($(element).find("svg").length > 0 && (_datum.length == 0 || _datum[0].values.length == 0)) {
  383. $(element).find("svg").empty();
  384. }
  385. if (_datum.length > 0 && _datum[0].values.length > 0 && isNaN(_datum[0].values[0].y)) {
  386. _datum = [];
  387. $(element).find("svg").empty();
  388. }
  389. if ($(element).is(":visible")) {
  390. nv.addGraph(function () {
  391. var _chart;
  392. var insertLinebreaks = function (d) {
  393. var _el = d3.select(this);
  394. var _mom = moment(d);
  395. if (_mom != null && _mom.isValid()) {
  396. var _words = _mom.format("HH:mm:ss YYYY-MM-DD").split(" ");
  397. _el.text("");
  398. for (var i = 0; i < _words.length; i++) {
  399. var tspan = _el.append("tspan").text(_words[i]);
  400. if (i > 0) {
  401. tspan.attr("x", 0).attr("dy", "15");
  402. }
  403. }
  404. }
  405. };
  406. if (isTimeline) {
  407. if ($(element).find("svg").length > 0 && $(element).find(".nv-discreteBarWithAxes").length > 0) {
  408. $(element).find("svg").empty();
  409. }
  410. _chart = nv.models.multiBarWithBrushChart();
  411. if (_datum.length > 0 && _datum[0].values.length > 10) {
  412. _chart.enableSelection();
  413. }
  414. _chart.onSelectRange(function (from, to) {
  415. chartsUpdatingState();
  416. options.onSelectRange(from, to);
  417. });
  418. _chart.xAxis.tickFormat(d3.time.format("%Y-%m-%d %H:%M:%S"));
  419. _chart.multibar.hideable(true);
  420. _chart.multibar.stacked(typeof options.stacked != "undefined" ? options.stacked : false);
  421. _chart.onStateChange(options.onStateChange);
  422. _chart.onChartUpdate(function () {
  423. _d3.selectAll("g.nv-x.nv-axis g text").each(insertLinebreaks);
  424. });
  425. }
  426. else {
  427. var _isDiscrete = false;
  428. for (var j = 0; j < _datum.length; j++) {
  429. for (var i = 0; i < _datum[j].values.length; i++) {
  430. if (isNaN(_datum[j].values[i].x * 1)) {
  431. _isDiscrete = true;
  432. break;
  433. }
  434. }
  435. }
  436. if (_isDiscrete && !_isPivot) {
  437. if ($(element).find("svg").length > 0 && $(element).find(".nv-multiBarWithLegend").length > 0) {
  438. $(element).find("svg").empty();
  439. }
  440. _chart = nv.models.growingDiscreteBarChart()
  441. .x(function (d) {
  442. return d.x
  443. })
  444. .y(function (d) {
  445. return d.y
  446. })
  447. .staggerLabels(true);
  448. }
  449. else {
  450. if ($(element).find("svg").length > 0 && $(element).find(".nv-discreteBarWithAxes").length > 0) {
  451. $(element).find("svg").empty();
  452. }
  453. _chart = nv.models.multiBarWithBrushChart();
  454. if (_datum.length > 0 && _datum[0].values.length > 10) {
  455. _chart.enableSelection();
  456. }
  457. if (_isPivot || _hideSelection) {
  458. _chart.hideSelection();
  459. }
  460. else {
  461. _chart.xAxis.showMaxMin(false).tickFormat(d3.format(",0f"));
  462. }
  463. _chart.multibar.hideable(true);
  464. _chart.multibar.stacked(typeof options.stacked != "undefined" ? options.stacked : false);
  465. _chart.onStateChange(options.onStateChange);
  466. _chart.onSelectRange(function (from, to) {
  467. chartsUpdatingState();
  468. options.onSelectRange(from, to);
  469. });
  470. }
  471. }
  472. if ($(element).width() < 300 && typeof _chart.showLegend != "undefined"){
  473. _chart.showLegend(false);
  474. }
  475. _chart.transitionDuration(0);
  476. _chart.yAxis
  477. .tickFormat(d3.format(",0f"));
  478. var _d3 = ($(element).find("svg").length > 0) ? d3.select($(element).find("svg")[0]) : d3.select($(element)[0]).append("svg");
  479. _d3.datum(_datum)
  480. .transition().duration(150)
  481. .each("end", function () {
  482. if (options.onComplete != null) {
  483. options.onComplete();
  484. }
  485. if (isTimeline) {
  486. _d3.selectAll("g.nv-x.nv-axis g text").each(insertLinebreaks);
  487. }
  488. }).call(_chart);
  489. if (_chart.selectBars) {
  490. $.each(options.fqs(), function (cnt, item) {
  491. if (item.field() == options.field) {
  492. _chart.selectBars($.map(item.filter(), function (it) {
  493. return it.value();
  494. }));
  495. }
  496. if (item.field().indexOf(":") > -1) {
  497. _chart.selectBars({
  498. field: item.field(),
  499. selected: $.map(item.filter(), function (it) {
  500. return it.value();
  501. })
  502. });
  503. }
  504. });
  505. }
  506. nv.utils.windowResize(_chart.update);
  507. return _chart;
  508. }, function () {
  509. var _d3 = ($(element).find("svg").length > 0) ? d3.select($(element).find("svg")[0]) : d3.select($(element)[0]).append("svg");
  510. _d3.selectAll(".nv-bar").on("click",
  511. function (d, i) {
  512. if (typeof options.onClick != "undefined") {
  513. chartsUpdatingState();
  514. options.onClick(d);
  515. }
  516. });
  517. });
  518. }
  519. }
  520. ko.bindingHandlers.partitionChart = {
  521. update: function (element, valueAccessor) {
  522. var MIN_HEIGHT_FOR_TOOLTIP = 24;
  523. var _options = valueAccessor();
  524. var _data = _options.transformer(valueAccessor().datum);
  525. var _w = $(element).width(),
  526. _h = 300,
  527. _x = d3.scale.linear().range([0, _w]),
  528. _y = d3.scale.linear().range([0, _h]);
  529. var _tip = d3.tip()
  530. .attr("class", "d3-tip")
  531. .html(function (d) {
  532. if (d.depth == 0) {
  533. return _options.tooltip || "";
  534. }
  535. else if (d.depth > 0 && d.depth < 2) {
  536. return d.name + " (" + d.value + ")";
  537. }
  538. else {
  539. return d.parent.name + " - " + d.name + " (" + d.value + ")";
  540. }
  541. })
  542. .offset([-12, 0])
  543. var _svg = d3.select(element).append("svg:svg");
  544. _svg.call(_tip);
  545. var _vis = ($(element).find("svg").length > 0) ? d3.select($(element).find("svg")[0]) : d3.select($(element)[0]).append("svg");
  546. _vis.attr("class", "partitionChart")
  547. .style("width", _w + "px")
  548. .style("height", _h + "px")
  549. .append("svg:svg")
  550. .attr("width", _w)
  551. .attr("height", _h);
  552. var _partition = d3.layout.partition()
  553. .value(function (d) {
  554. return d.size;
  555. });
  556. var g = _vis.selectAll("g")
  557. .data(_partition.nodes(_data))
  558. .enter().append("svg:g")
  559. .attr("transform", function (d) {
  560. return "translate(" + _x(d.y) + "," + _y(d.x) + ")";
  561. })
  562. .on("mouseover", function (d, i) {
  563. if (element.querySelectorAll("rect")[i].getBBox().height < MIN_HEIGHT_FOR_TOOLTIP || d.depth == 0) {
  564. _tip.attr("class", "d3-tip").show(d);
  565. }
  566. if (this.__data__.parent == undefined) return;
  567. d3.select(this).select("rect").classed("mouseover", true)
  568. })
  569. .on("mouseout", function (d, i) {
  570. if (element.querySelectorAll("rect")[i].getBBox().height < MIN_HEIGHT_FOR_TOOLTIP || d.depth == 0) {
  571. _tip.attr("class", "d3-tip").show(d);
  572. _tip.hide();
  573. }
  574. d3.select(this).select("rect").classed("mouseover", false)
  575. });
  576. if (typeof _options.zoomable == "undefined" || _options.zoomable) {
  577. g.on("click", click)
  578. .on("dblclick", function (d, i) {
  579. if (typeof _options.onClick != "undefined" && d.depth > 0) {
  580. chartsUpdatingState();
  581. _options.onClick(d);
  582. }
  583. });
  584. }
  585. else {
  586. g.on("click", function (d, i) {
  587. if (typeof _options.onClick != "undefined" && d.depth > 0) {
  588. chartsUpdatingState();
  589. _options.onClick(d);
  590. }
  591. });
  592. }
  593. var _kx = _w / _data.dx,
  594. _ky = _h / 1;
  595. var _colors = HueColors.scale(HueColors.DARK_BLUE, HueColors.BLUE, 5)
  596. g.append("svg:rect")
  597. .attr("width", _data.dy * _kx)
  598. .attr("height", function (d) {
  599. return d.dx * _ky;
  600. })
  601. .attr("class", function (d) {
  602. return d.children ? "parent" : "child";
  603. })
  604. .attr("stroke", function (d) {
  605. return HueColors.DARK_BLUE;
  606. })
  607. .attr("fill", function (d, i) {
  608. var _fill = _colors[d.depth] || _colors[_colors.length - 1];
  609. if (d.obj && _options.fqs) {
  610. $.each(_options.fqs(), function (cnt, item) {
  611. $.each(item.filter(), function (icnt, filter) {
  612. if (filter.value() == d.obj.fq_values) {
  613. _fill = HueColors.ORANGE;
  614. }
  615. });
  616. });
  617. }
  618. return _fill;
  619. });
  620. g.append("svg:text")
  621. .attr("transform", transform)
  622. .attr("dy", ".35em")
  623. .style("opacity", function (d) {
  624. return d.dx * _ky > 12 ? 1 : 0;
  625. })
  626. .text(function (d) {
  627. if (d.depth < 2) {
  628. return d.name + " (" + d.value + ")";
  629. }
  630. else {
  631. return d.parent.name + " - " + d.name + " (" + d.value + ")";
  632. }
  633. });
  634. d3.select(window)
  635. .on("click", function () {
  636. click(_data);
  637. });
  638. function click(d) {
  639. _tip.hide();
  640. if (!d.children) return;
  641. _kx = (d.y ? _w - 40 : _w) / (1 - d.y);
  642. _ky = _h / d.dx;
  643. _x.domain([d.y, 1]).range([d.y ? 40 : 0, _w]);
  644. _y.domain([d.x, d.x + d.dx]);
  645. var t = g.transition()
  646. .duration(d3.event.altKey ? 7500 : 750)
  647. .attr("transform", function (d) {
  648. return "translate(" + _x(d.y) + "," + _y(d.x) + ")";
  649. });
  650. t.select("rect")
  651. .attr("width", d.dy * _kx)
  652. .attr("height", function (d) {
  653. return d.dx * _ky;
  654. });
  655. t.select("text")
  656. .attr("transform", transform)
  657. .style("opacity", function (d) {
  658. return d.dx * _ky > 12 ? 1 : 0;
  659. });
  660. d3.event.stopPropagation();
  661. }
  662. function transform(d) {
  663. return "translate(8," + d.dx * _ky / 2 + ")";
  664. }
  665. }
  666. };
  667. function chartsUpdatingState() {
  668. $(document).find("svg").css("opacity", "0.5");
  669. }
  670. var tipBuilder = function () {
  671. var direction = d3_tip_direction,
  672. offset = d3_tip_offset,
  673. html = d3_tip_html,
  674. node = initNode(),
  675. svg = null,
  676. point = null,
  677. target = null
  678. function tip(vis) {
  679. svg = getSVGNode(vis)
  680. point = svg.createSVGPoint()
  681. document.body.appendChild(node)
  682. }
  683. // Public - show the tooltip on the screen
  684. //
  685. // Returns a tip
  686. tip.show = function () {
  687. var args = Array.prototype.slice.call(arguments)
  688. if (args[args.length - 1] instanceof SVGElement) target = args.pop()
  689. var content = html.apply(this, args),
  690. poffset = offset.apply(this, args),
  691. dir = direction.apply(this, args),
  692. nodel = d3.select(node), i = 0,
  693. coords
  694. nodel.html(content)
  695. .style({ opacity: 1, "pointer-events": "all" })
  696. while (i--) nodel.classed(directions[i], false)
  697. coords = direction_callbacks.get(dir).apply(this)
  698. nodel.classed(dir, true).style({
  699. top: (coords.top + poffset[0]) + "px",
  700. left: (coords.left + poffset[1]) + "px"
  701. })
  702. return tip
  703. }
  704. // Public - hide the tooltip
  705. //
  706. // Returns a tip
  707. tip.hide = function () {
  708. nodel = d3.select(node)
  709. nodel.style({ opacity: 0, "pointer-events": "none" })
  710. return tip
  711. }
  712. // Public: Proxy attr calls to the d3 tip container. Sets or gets attribute value.
  713. //
  714. // n - name of the attribute
  715. // v - value of the attribute
  716. //
  717. // Returns tip or attribute value
  718. tip.attr = function (n, v) {
  719. if (arguments.length < 2 && typeof n === "string") {
  720. return d3.select(node).attr(n)
  721. } else {
  722. var args = Array.prototype.slice.call(arguments)
  723. d3.selection.prototype.attr.apply(d3.select(node), args)
  724. }
  725. return tip
  726. }
  727. // Public: Proxy style calls to the d3 tip container. Sets or gets a style value.
  728. //
  729. // n - name of the property
  730. // v - value of the property
  731. //
  732. // Returns tip or style property value
  733. tip.style = function (n, v) {
  734. if (arguments.length < 2 && typeof n === "string") {
  735. return d3.select(node).style(n)
  736. } else {
  737. var args = Array.prototype.slice.call(arguments)
  738. d3.selection.prototype.style.apply(d3.select(node), args)
  739. }
  740. return tip
  741. }
  742. // Public: Set or get the direction of the tooltip
  743. //
  744. // v - One of n(north), s(south), e(east), or w(west), nw(northwest),
  745. // sw(southwest), ne(northeast) or se(southeast)
  746. //
  747. // Returns tip or direction
  748. tip.direction = function (v) {
  749. if (!arguments.length) return direction
  750. direction = v == null ? v : d3.functor(v)
  751. return tip
  752. }
  753. // Public: Sets or gets the offset of the tip
  754. //
  755. // v - Array of [x, y] offset
  756. //
  757. // Returns offset or
  758. tip.offset = function (v) {
  759. if (!arguments.length) return offset
  760. offset = v == null ? v : d3.functor(v)
  761. return tip
  762. }
  763. // Public: sets or gets the html value of the tooltip
  764. //
  765. // v - String value of the tip
  766. //
  767. // Returns html value or tip
  768. tip.html = function (v) {
  769. if (!arguments.length) return html
  770. html = v == null ? v : d3.functor(v)
  771. return tip
  772. }
  773. function d3_tip_direction() {
  774. return "n"
  775. }
  776. function d3_tip_offset() {
  777. return [0, 0]
  778. }
  779. function d3_tip_html() {
  780. return " "
  781. }
  782. var direction_callbacks = d3.map({
  783. n: direction_n,
  784. s: direction_s,
  785. e: direction_e,
  786. w: direction_w,
  787. nw: direction_nw,
  788. ne: direction_ne,
  789. sw: direction_sw,
  790. se: direction_se
  791. }),
  792. directions = direction_callbacks.keys()
  793. function direction_n() {
  794. var bbox = getScreenBBox()
  795. return {
  796. top: bbox.n.y - node.offsetHeight,
  797. left: bbox.n.x - node.offsetWidth / 2
  798. }
  799. }
  800. function direction_s() {
  801. var bbox = getScreenBBox()
  802. return {
  803. top: bbox.s.y,
  804. left: bbox.s.x - node.offsetWidth / 2
  805. }
  806. }
  807. function direction_e() {
  808. var bbox = getScreenBBox()
  809. return {
  810. top: bbox.e.y - node.offsetHeight / 2,
  811. left: bbox.e.x
  812. }
  813. }
  814. function direction_w() {
  815. var bbox = getScreenBBox()
  816. return {
  817. top: bbox.w.y - node.offsetHeight / 2,
  818. left: bbox.w.x - node.offsetWidth
  819. }
  820. }
  821. function direction_nw() {
  822. var bbox = getScreenBBox()
  823. return {
  824. top: bbox.nw.y - node.offsetHeight,
  825. left: bbox.nw.x - node.offsetWidth
  826. }
  827. }
  828. function direction_ne() {
  829. var bbox = getScreenBBox()
  830. return {
  831. top: bbox.ne.y - node.offsetHeight,
  832. left: bbox.ne.x
  833. }
  834. }
  835. function direction_sw() {
  836. var bbox = getScreenBBox()
  837. return {
  838. top: bbox.sw.y,
  839. left: bbox.sw.x - node.offsetWidth
  840. }
  841. }
  842. function direction_se() {
  843. var bbox = getScreenBBox()
  844. return {
  845. top: bbox.se.y,
  846. left: bbox.e.x
  847. }
  848. }
  849. function initNode() {
  850. var node = d3.select(document.createElement("div"))
  851. node.style({
  852. position: "absolute",
  853. opacity: 0,
  854. pointerEvents: "none",
  855. boxSizing: "border-box"
  856. })
  857. return node.node()
  858. }
  859. function getSVGNode(el) {
  860. el = el.node()
  861. if (el != null) {
  862. if (el.tagName != null && el.tagName.toLowerCase() == "svg")
  863. return el
  864. return el.ownerSVGElement
  865. }
  866. }
  867. // Private - gets the screen coordinates of a shape
  868. //
  869. // Given a shape on the screen, will return an SVGPoint for the directions
  870. // n(north), s(south), e(east), w(west), ne(northeast), se(southeast), nw(northwest),
  871. // sw(southwest).
  872. //
  873. // +-+-+
  874. // | |
  875. // + +
  876. // | |
  877. // +-+-+
  878. //
  879. // Returns an Object {n, s, e, w, nw, sw, ne, se}
  880. function getScreenBBox() {
  881. var targetel = target || d3.event.target,
  882. bbox = {},
  883. matrix = targetel.getScreenCTM(),
  884. tbbox = targetel.getBBox(),
  885. width = tbbox.width,
  886. height = tbbox.height,
  887. x = tbbox.x,
  888. y = tbbox.y,
  889. scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
  890. scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft
  891. point.x = x + scrollLeft
  892. point.y = y + scrollTop
  893. bbox.nw = point.matrixTransform(matrix)
  894. point.x += width
  895. bbox.ne = point.matrixTransform(matrix)
  896. point.y += height
  897. bbox.se = point.matrixTransform(matrix)
  898. point.x -= width
  899. bbox.sw = point.matrixTransform(matrix)
  900. point.y -= height / 2
  901. bbox.w = point.matrixTransform(matrix)
  902. point.x += width
  903. bbox.e = point.matrixTransform(matrix)
  904. point.x -= width / 2
  905. point.y -= height / 2
  906. bbox.n = point.matrixTransform(matrix)
  907. point.y += height
  908. bbox.s = point.matrixTransform(matrix)
  909. return bbox
  910. }
  911. return tip
  912. };
  913. d3.tip = tipBuilder;