ko.charts.js 29 KB

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