chartkick.js 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  1. /*
  2. * Chartkick.js
  3. * Create beautiful JavaScript charts with minimal code
  4. * https://github.com/ankane/chartkick.js
  5. * v2.0.0
  6. * MIT License
  7. */
  8. /*jslint browser: true, indent: 2, plusplus: true, vars: true */
  9. (function (window) {
  10. 'use strict';
  11. var config = window.Chartkick || {};
  12. var Chartkick, ISO8601_PATTERN, DECIMAL_SEPARATOR, adapters = [];
  13. var DATE_PATTERN = /^(\d\d\d\d)(\-)?(\d\d)(\-)?(\d\d)$/i;
  14. var GoogleChartsAdapter, HighchartsAdapter, ChartjsAdapter;
  15. // helpers
  16. function isArray(variable) {
  17. return Object.prototype.toString.call(variable) === "[object Array]";
  18. }
  19. function isFunction(variable) {
  20. return variable instanceof Function;
  21. }
  22. function isPlainObject(variable) {
  23. return !isFunction(variable) && variable instanceof Object;
  24. }
  25. // https://github.com/madrobby/zepto/blob/master/src/zepto.js
  26. function extend(target, source) {
  27. var key;
  28. for (key in source) {
  29. if (isPlainObject(source[key]) || isArray(source[key])) {
  30. if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
  31. target[key] = {};
  32. }
  33. if (isArray(source[key]) && !isArray(target[key])) {
  34. target[key] = [];
  35. }
  36. extend(target[key], source[key]);
  37. } else if (source[key] !== undefined) {
  38. target[key] = source[key];
  39. }
  40. }
  41. }
  42. function merge(obj1, obj2) {
  43. var target = {};
  44. extend(target, obj1);
  45. extend(target, obj2);
  46. return target;
  47. }
  48. // https://github.com/Do/iso8601.js
  49. ISO8601_PATTERN = /(\d\d\d\d)(\-)?(\d\d)(\-)?(\d\d)(T)?(\d\d)(:)?(\d\d)?(:)?(\d\d)?([\.,]\d+)?($|Z|([\+\-])(\d\d)(:)?(\d\d)?)/i;
  50. DECIMAL_SEPARATOR = String(1.5).charAt(1);
  51. function parseISO8601(input) {
  52. var day, hour, matches, milliseconds, minutes, month, offset, result, seconds, type, year;
  53. type = Object.prototype.toString.call(input);
  54. if (type === '[object Date]') {
  55. return input;
  56. }
  57. if (type !== '[object String]') {
  58. return;
  59. }
  60. matches = input.match(ISO8601_PATTERN);
  61. if (matches) {
  62. year = parseInt(matches[1], 10);
  63. month = parseInt(matches[3], 10) - 1;
  64. day = parseInt(matches[5], 10);
  65. hour = parseInt(matches[7], 10);
  66. minutes = matches[9] ? parseInt(matches[9], 10) : 0;
  67. seconds = matches[11] ? parseInt(matches[11], 10) : 0;
  68. milliseconds = matches[12] ? parseFloat(DECIMAL_SEPARATOR + matches[12].slice(1)) * 1000 : 0;
  69. result = Date.UTC(year, month, day, hour, minutes, seconds, milliseconds);
  70. if (matches[13] && matches[14]) {
  71. offset = matches[15] * 60;
  72. if (matches[17]) {
  73. offset += parseInt(matches[17], 10);
  74. }
  75. offset *= matches[14] === '-' ? -1 : 1;
  76. result -= offset * 60 * 1000;
  77. }
  78. return new Date(result);
  79. }
  80. }
  81. // end iso8601.js
  82. function negativeValues(series) {
  83. var i, j, data;
  84. for (i = 0; i < series.length; i++) {
  85. data = series[i].data;
  86. for (j = 0; j < data.length; j++) {
  87. if (data[j][1] < 0) {
  88. return true;
  89. }
  90. }
  91. }
  92. return false;
  93. }
  94. function jsOptionsFunc(defaultOptions, hideLegend, setMin, setMax, setStacked, setXtitle, setYtitle) {
  95. return function (series, opts, chartOptions) {
  96. var options = merge({}, defaultOptions);
  97. options = merge(options, chartOptions || {});
  98. // hide legend
  99. // this is *not* an external option!
  100. if (opts.hideLegend) {
  101. hideLegend(options);
  102. }
  103. // min
  104. if ("min" in opts) {
  105. setMin(options, opts.min);
  106. } else if (!negativeValues(series)) {
  107. setMin(options, 0);
  108. }
  109. // max
  110. if (opts.max) {
  111. setMax(options, opts.max);
  112. }
  113. if ("stacked" in opts) {
  114. setStacked(options, opts.stacked);
  115. }
  116. if (opts.colors) {
  117. options.colors = opts.colors;
  118. }
  119. if (opts.xtitle) {
  120. setXtitle(options, opts.xtitle);
  121. }
  122. if (opts.ytitle) {
  123. setYtitle(options, opts.ytitle);
  124. }
  125. // merge library last
  126. options = merge(options, opts.library || {});
  127. return options;
  128. };
  129. }
  130. function setText(element, text) {
  131. if (document.body.innerText) {
  132. element.innerText = text;
  133. } else {
  134. element.textContent = text;
  135. }
  136. }
  137. function chartError(element, message) {
  138. setText(element, "Error Loading Chart: " + message);
  139. element.style.color = "#ff0000";
  140. }
  141. function getJSON(element, url, success) {
  142. var $ = window.jQuery || window.Zepto || window.$;
  143. $.ajax({
  144. dataType: "json",
  145. url: url,
  146. success: success,
  147. error: function (jqXHR, textStatus, errorThrown) {
  148. var message = (typeof errorThrown === "string") ? errorThrown : errorThrown.message;
  149. chartError(element, message);
  150. }
  151. });
  152. }
  153. function errorCatcher(chart, callback) {
  154. try {
  155. callback(chart);
  156. } catch (err) {
  157. chartError(chart.element, err.message);
  158. throw err;
  159. }
  160. }
  161. function fetchDataSource(chart, callback) {
  162. if (typeof chart.dataSource === "string") {
  163. getJSON(chart.element, chart.dataSource, function (data, textStatus, jqXHR) {
  164. chart.data = data;
  165. errorCatcher(chart, callback);
  166. });
  167. } else {
  168. chart.data = chart.dataSource;
  169. errorCatcher(chart, callback);
  170. }
  171. }
  172. // type conversions
  173. function toStr(n) {
  174. return "" + n;
  175. }
  176. function toFloat(n) {
  177. return parseFloat(n);
  178. }
  179. function toDate(n) {
  180. var matches, year, month, day;
  181. if (typeof n !== "object") {
  182. if (typeof n === "number") {
  183. n = new Date(n * 1000); // ms
  184. } else if ((matches = n.match(DATE_PATTERN))) {
  185. year = parseInt(matches[1], 10);
  186. month = parseInt(matches[3], 10) - 1;
  187. day = parseInt(matches[5], 10);
  188. return new Date(year, month, day);
  189. } else { // str
  190. // try our best to get the str into iso8601
  191. // TODO be smarter about this
  192. var str = n.replace(/ /, "T").replace(" ", "").replace("UTC", "Z");
  193. n = parseISO8601(str) || new Date(n);
  194. }
  195. }
  196. return n;
  197. }
  198. function toArr(n) {
  199. if (!isArray(n)) {
  200. var arr = [], i;
  201. for (i in n) {
  202. if (n.hasOwnProperty(i)) {
  203. arr.push([i, n[i]]);
  204. }
  205. }
  206. n = arr;
  207. }
  208. return n;
  209. }
  210. function sortByTime(a, b) {
  211. return a[0].getTime() - b[0].getTime();
  212. }
  213. function sortByNumber(a, b) {
  214. return a - b;
  215. }
  216. function loadAdapters() {
  217. if (!HighchartsAdapter && "Highcharts" in window) {
  218. HighchartsAdapter = new function () {
  219. var Highcharts = window.Highcharts;
  220. this.name = "highcharts";
  221. var defaultOptions = {
  222. chart: {},
  223. xAxis: {
  224. title: {
  225. text: null
  226. },
  227. labels: {
  228. style: {
  229. fontSize: "12px"
  230. }
  231. }
  232. },
  233. yAxis: {
  234. title: {
  235. text: null
  236. },
  237. labels: {
  238. style: {
  239. fontSize: "12px"
  240. }
  241. }
  242. },
  243. title: {
  244. text: null
  245. },
  246. credits: {
  247. enabled: false
  248. },
  249. legend: {
  250. borderWidth: 0
  251. },
  252. tooltip: {
  253. style: {
  254. fontSize: "12px"
  255. }
  256. },
  257. plotOptions: {
  258. areaspline: {},
  259. series: {
  260. marker: {}
  261. }
  262. }
  263. };
  264. var hideLegend = function (options) {
  265. options.legend.enabled = false;
  266. };
  267. var setMin = function (options, min) {
  268. options.yAxis.min = min;
  269. };
  270. var setMax = function (options, max) {
  271. options.yAxis.max = max;
  272. };
  273. var setStacked = function (options, stacked) {
  274. options.plotOptions.series.stacking = stacked ? "normal" : null;
  275. };
  276. var setXtitle = function (options, title) {
  277. options.xAxis.title.text = title;
  278. };
  279. var setYtitle = function (options, title) {
  280. options.yAxis.title.text = title;
  281. };
  282. var jsOptions = jsOptionsFunc(defaultOptions, hideLegend, setMin, setMax, setStacked, setXtitle, setYtitle);
  283. this.renderLineChart = function (chart, chartType) {
  284. chartType = chartType || "spline";
  285. var chartOptions = {};
  286. if (chartType === "areaspline") {
  287. chartOptions = {
  288. plotOptions: {
  289. areaspline: {
  290. stacking: "normal"
  291. },
  292. series: {
  293. marker: {
  294. enabled: false
  295. }
  296. }
  297. }
  298. };
  299. }
  300. var options = jsOptions(chart.data, chart.options, chartOptions), data, i, j;
  301. options.xAxis.type = chart.options.discrete ? "category" : "datetime";
  302. options.chart.type = chartType;
  303. options.chart.renderTo = chart.element.id;
  304. var series = chart.data;
  305. for (i = 0; i < series.length; i++) {
  306. data = series[i].data;
  307. if (!chart.options.discrete) {
  308. for (j = 0; j < data.length; j++) {
  309. data[j][0] = data[j][0].getTime();
  310. }
  311. }
  312. series[i].marker = {symbol: "circle"};
  313. }
  314. options.series = series;
  315. new Highcharts.Chart(options);
  316. };
  317. this.renderScatterChart = function (chart) {
  318. var chartOptions = {};
  319. var options = jsOptions(chart.data, chart.options, chartOptions);
  320. options.chart.type = 'scatter';
  321. options.chart.renderTo = chart.element.id;
  322. options.series = chart.data;
  323. new Highcharts.Chart(options);
  324. };
  325. this.renderPieChart = function (chart) {
  326. var chartOptions = {};
  327. if (chart.options.colors) {
  328. chartOptions.colors = chart.options.colors;
  329. }
  330. var options = merge(merge(defaultOptions, chartOptions), chart.options.library || {});
  331. options.chart.renderTo = chart.element.id;
  332. options.series = [{
  333. type: "pie",
  334. name: chart.options.label || "Value",
  335. data: chart.data
  336. }];
  337. new Highcharts.Chart(options);
  338. };
  339. this.renderColumnChart = function (chart, chartType) {
  340. chartType = chartType || "column";
  341. var series = chart.data;
  342. var options = jsOptions(series, chart.options), i, j, s, d, rows = [];
  343. options.chart.type = chartType;
  344. options.chart.renderTo = chart.element.id;
  345. for (i = 0; i < series.length; i++) {
  346. s = series[i];
  347. for (j = 0; j < s.data.length; j++) {
  348. d = s.data[j];
  349. if (!rows[d[0]]) {
  350. rows[d[0]] = new Array(series.length);
  351. }
  352. rows[d[0]][i] = d[1];
  353. }
  354. }
  355. var categories = [];
  356. for (i in rows) {
  357. if (rows.hasOwnProperty(i)) {
  358. categories.push(i);
  359. }
  360. }
  361. options.xAxis.categories = categories;
  362. var newSeries = [];
  363. for (i = 0; i < series.length; i++) {
  364. d = [];
  365. for (j = 0; j < categories.length; j++) {
  366. d.push(rows[categories[j]][i] || 0);
  367. }
  368. newSeries.push({
  369. name: series[i].name,
  370. data: d
  371. });
  372. }
  373. options.series = newSeries;
  374. new Highcharts.Chart(options);
  375. };
  376. var self = this;
  377. this.renderBarChart = function (chart) {
  378. self.renderColumnChart(chart, "bar");
  379. };
  380. this.renderAreaChart = function (chart) {
  381. self.renderLineChart(chart, "areaspline");
  382. };
  383. };
  384. adapters.push(HighchartsAdapter);
  385. }
  386. if (!GoogleChartsAdapter && window.google && window.google.setOnLoadCallback) {
  387. GoogleChartsAdapter = new function () {
  388. var google = window.google;
  389. this.name = "google";
  390. var loaded = {};
  391. var callbacks = [];
  392. var runCallbacks = function () {
  393. var cb, call;
  394. for (var i = 0; i < callbacks.length; i++) {
  395. cb = callbacks[i];
  396. call = google.visualization && ((cb.pack === "corechart" && google.visualization.LineChart) || (cb.pack === "timeline" && google.visualization.Timeline));
  397. if (call) {
  398. cb.callback();
  399. callbacks.splice(i, 1);
  400. i--;
  401. }
  402. }
  403. };
  404. var waitForLoaded = function (pack, callback) {
  405. if (!callback) {
  406. callback = pack;
  407. pack = "corechart";
  408. }
  409. callbacks.push({pack: pack, callback: callback});
  410. if (loaded[pack]) {
  411. runCallbacks();
  412. } else {
  413. loaded[pack] = true;
  414. // https://groups.google.com/forum/#!topic/google-visualization-api/fMKJcyA2yyI
  415. var loadOptions = {
  416. packages: [pack],
  417. callback: runCallbacks
  418. };
  419. if (config.language) {
  420. loadOptions.language = config.language;
  421. }
  422. google.load("visualization", "1", loadOptions);
  423. }
  424. };
  425. // Set chart options
  426. var defaultOptions = {
  427. chartArea: {},
  428. fontName: "'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helvetica, sans-serif",
  429. pointSize: 6,
  430. legend: {
  431. textStyle: {
  432. fontSize: 12,
  433. color: "#444"
  434. },
  435. alignment: "center",
  436. position: "right"
  437. },
  438. curveType: "function",
  439. hAxis: {
  440. textStyle: {
  441. color: "#666",
  442. fontSize: 12
  443. },
  444. titleTextStyle: {},
  445. gridlines: {
  446. color: "transparent"
  447. },
  448. baselineColor: "#ccc",
  449. viewWindow: {}
  450. },
  451. vAxis: {
  452. textStyle: {
  453. color: "#666",
  454. fontSize: 12
  455. },
  456. titleTextStyle: {},
  457. baselineColor: "#ccc",
  458. viewWindow: {}
  459. },
  460. tooltip: {
  461. textStyle: {
  462. color: "#666",
  463. fontSize: 12
  464. }
  465. }
  466. };
  467. var hideLegend = function (options) {
  468. options.legend.position = "none";
  469. };
  470. var setMin = function (options, min) {
  471. options.vAxis.viewWindow.min = min;
  472. };
  473. var setMax = function (options, max) {
  474. options.vAxis.viewWindow.max = max;
  475. };
  476. var setBarMin = function (options, min) {
  477. options.hAxis.viewWindow.min = min;
  478. };
  479. var setBarMax = function (options, max) {
  480. options.hAxis.viewWindow.max = max;
  481. };
  482. var setStacked = function (options, stacked) {
  483. options.isStacked = !!stacked;
  484. };
  485. var setXtitle = function (options, title) {
  486. options.hAxis.title = title;
  487. options.hAxis.titleTextStyle.italic = false;
  488. };
  489. var setYtitle = function (options, title) {
  490. options.vAxis.title = title;
  491. options.vAxis.titleTextStyle.italic = false;
  492. };
  493. var jsOptions = jsOptionsFunc(defaultOptions, hideLegend, setMin, setMax, setStacked, setXtitle, setYtitle);
  494. // cant use object as key
  495. var createDataTable = function (series, columnType) {
  496. var i, j, s, d, key, rows = [];
  497. for (i = 0; i < series.length; i++) {
  498. s = series[i];
  499. for (j = 0; j < s.data.length; j++) {
  500. d = s.data[j];
  501. key = (columnType === "datetime") ? d[0].getTime() : d[0];
  502. if (!rows[key]) {
  503. rows[key] = new Array(series.length);
  504. }
  505. rows[key][i] = toFloat(d[1]);
  506. }
  507. }
  508. var rows2 = [];
  509. var day = true;
  510. var value;
  511. for (i in rows) {
  512. if (rows.hasOwnProperty(i)) {
  513. if (columnType === "datetime") {
  514. value = new Date(toFloat(i));
  515. day = day && isDay(value);
  516. } else if (columnType === "number") {
  517. value = toFloat(i);
  518. } else {
  519. value = i;
  520. }
  521. rows2.push([value].concat(rows[i]));
  522. }
  523. }
  524. if (columnType === "datetime") {
  525. rows2.sort(sortByTime);
  526. }
  527. // create datatable
  528. var data = new google.visualization.DataTable();
  529. columnType = columnType === "datetime" && day ? "date" : columnType;
  530. data.addColumn(columnType, "");
  531. for (i = 0; i < series.length; i++) {
  532. data.addColumn("number", series[i].name);
  533. }
  534. data.addRows(rows2);
  535. return data;
  536. };
  537. var resize = function (callback) {
  538. if (window.attachEvent) {
  539. window.attachEvent("onresize", callback);
  540. } else if (window.addEventListener) {
  541. window.addEventListener("resize", callback, true);
  542. }
  543. callback();
  544. };
  545. this.renderLineChart = function (chart) {
  546. waitForLoaded(function () {
  547. var options = jsOptions(chart.data, chart.options);
  548. var data = createDataTable(chart.data, chart.options.discrete ? "string" : "datetime");
  549. chart.chart = new google.visualization.LineChart(chart.element);
  550. resize(function () {
  551. chart.chart.draw(data, options);
  552. });
  553. });
  554. };
  555. this.renderPieChart = function (chart) {
  556. waitForLoaded(function () {
  557. var chartOptions = {
  558. chartArea: {
  559. top: "10%",
  560. height: "80%"
  561. }
  562. };
  563. if (chart.options.colors) {
  564. chartOptions.colors = chart.options.colors;
  565. }
  566. var options = merge(merge(defaultOptions, chartOptions), chart.options.library || {});
  567. var data = new google.visualization.DataTable();
  568. data.addColumn("string", "");
  569. data.addColumn("number", "Value");
  570. data.addRows(chart.data);
  571. chart.chart = new google.visualization.PieChart(chart.element);
  572. resize(function () {
  573. chart.chart.draw(data, options);
  574. });
  575. });
  576. };
  577. this.renderColumnChart = function (chart) {
  578. waitForLoaded(function () {
  579. var options = jsOptions(chart.data, chart.options);
  580. var data = createDataTable(chart.data, "string");
  581. chart.chart = new google.visualization.ColumnChart(chart.element);
  582. resize(function () {
  583. chart.chart.draw(data, options);
  584. });
  585. });
  586. };
  587. this.renderBarChart = function (chart) {
  588. waitForLoaded(function () {
  589. var chartOptions = {
  590. hAxis: {
  591. gridlines: {
  592. color: "#ccc"
  593. }
  594. }
  595. };
  596. var options = jsOptionsFunc(defaultOptions, hideLegend, setBarMin, setBarMax, setStacked)(chart.data, chart.options, chartOptions);
  597. var data = createDataTable(chart.data, "string");
  598. chart.chart = new google.visualization.BarChart(chart.element);
  599. resize(function () {
  600. chart.chart.draw(data, options);
  601. });
  602. });
  603. };
  604. this.renderAreaChart = function (chart) {
  605. waitForLoaded(function () {
  606. var chartOptions = {
  607. isStacked: true,
  608. pointSize: 0,
  609. areaOpacity: 0.5
  610. };
  611. var options = jsOptions(chart.data, chart.options, chartOptions);
  612. var data = createDataTable(chart.data, chart.options.discrete ? "string" : "datetime");
  613. chart.chart = new google.visualization.AreaChart(chart.element);
  614. resize(function () {
  615. chart.chart.draw(data, options);
  616. });
  617. });
  618. };
  619. this.renderGeoChart = function (chart) {
  620. waitForLoaded(function () {
  621. var chartOptions = {
  622. legend: "none",
  623. colorAxis: {
  624. colors: chart.options.colors || ["#f6c7b6", "#ce502d"]
  625. }
  626. };
  627. var options = merge(merge(defaultOptions, chartOptions), chart.options.library || {});
  628. var data = new google.visualization.DataTable();
  629. data.addColumn("string", "");
  630. data.addColumn("number", chart.options.label || "Value");
  631. data.addRows(chart.data);
  632. chart.chart = new google.visualization.GeoChart(chart.element);
  633. resize(function () {
  634. chart.chart.draw(data, options);
  635. });
  636. });
  637. };
  638. this.renderScatterChart = function (chart) {
  639. waitForLoaded(function () {
  640. var chartOptions = {};
  641. var options = jsOptions(chart.data, chart.options, chartOptions);
  642. var data = createDataTable(chart.data, "number");
  643. chart.chart = new google.visualization.ScatterChart(chart.element);
  644. resize(function () {
  645. chart.chart.draw(data, options);
  646. });
  647. });
  648. };
  649. this.renderTimeline = function (chart) {
  650. waitForLoaded("timeline", function () {
  651. var chartOptions = {
  652. legend: "none"
  653. };
  654. if (chart.options.colors) {
  655. chartOptions.colors = chart.options.colors;
  656. }
  657. var options = merge(merge(defaultOptions, chartOptions), chart.options.library || {});
  658. var data = new google.visualization.DataTable();
  659. data.addColumn({type: "string", id: "Name"});
  660. data.addColumn({type: "date", id: "Start"});
  661. data.addColumn({type: "date", id: "End"});
  662. data.addRows(chart.data);
  663. chart.element.style.lineHeight = "normal";
  664. chart.chart = new google.visualization.Timeline(chart.element);
  665. resize(function () {
  666. chart.chart.draw(data, options);
  667. });
  668. });
  669. };
  670. };
  671. adapters.push(GoogleChartsAdapter);
  672. }
  673. if (!ChartjsAdapter && "Chart" in window) {
  674. ChartjsAdapter = new function () {
  675. var Chart = window.Chart;
  676. this.name = "chartjs";
  677. var baseOptions = {
  678. maintainAspectRatio: false,
  679. animation: false
  680. };
  681. var defaultOptions = {
  682. scales: {
  683. yAxes: [
  684. {
  685. ticks: {
  686. maxTicksLimit: 4
  687. },
  688. scaleLabel: {
  689. fontSize: 16,
  690. // fontStyle: "bold",
  691. fontColor: "#333"
  692. }
  693. }
  694. ],
  695. xAxes: [
  696. {
  697. gridLines: {
  698. drawOnChartArea: false
  699. },
  700. scaleLabel: {
  701. fontSize: 16,
  702. // fontStyle: "bold",
  703. fontColor: "#333"
  704. },
  705. time: {},
  706. ticks: {}
  707. }
  708. ]
  709. },
  710. legend: {}
  711. };
  712. // http://there4.io/2012/05/02/google-chart-color-list/
  713. var defaultColors = [
  714. "#3366CC", "#DC3912", "#FF9900", "#109618", "#990099", "#3B3EAC", "#0099C6",
  715. "#DD4477", "#66AA00", "#B82E2E", "#316395", "#994499", "#22AA99", "#AAAA11",
  716. "#6633CC", "#E67300", "#8B0707", "#329262", "#5574A6", "#3B3EAC"
  717. ];
  718. var hideLegend = function (options) {
  719. options.legend.display = false;
  720. };
  721. var setMin = function (options, min) {
  722. if (min !== null) {
  723. options.scales.yAxes[0].ticks.min = min;
  724. }
  725. };
  726. var setMax = function (options, max) {
  727. options.scales.yAxes[0].ticks.max = max;
  728. };
  729. var setBarMin = function (options, min) {
  730. if (min !== null) {
  731. options.scales.xAxes[0].ticks.min = min;
  732. }
  733. };
  734. var setBarMax = function (options, max) {
  735. options.scales.xAxes[0].ticks.max = max;
  736. };
  737. var setStacked = function (options, stacked) {
  738. options.scales.xAxes[0].stacked = !!stacked;
  739. options.scales.yAxes[0].stacked = !!stacked;
  740. };
  741. var setXtitle = function (options, title) {
  742. options.scales.xAxes[0].scaleLabel.display = true;
  743. options.scales.xAxes[0].scaleLabel.labelString = title;
  744. };
  745. var setYtitle = function (options, title) {
  746. options.scales.yAxes[0].scaleLabel.display = true;
  747. options.scales.yAxes[0].scaleLabel.labelString = title;
  748. };
  749. var drawChart = function(chart, type, data, options) {
  750. chart.element.innerHTML = "<canvas></canvas>";
  751. var ctx = chart.element.getElementsByTagName("CANVAS")[0];
  752. chart.chart = new Chart(ctx, {
  753. type: type,
  754. data: data,
  755. options: options
  756. });
  757. };
  758. // http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
  759. var addOpacity = function(hex, opacity) {
  760. var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  761. return result ? "rgba(" + parseInt(result[1], 16) + ", " + parseInt(result[2], 16) + ", " + parseInt(result[3], 16) + ", " + opacity + ")" : hex;
  762. };
  763. var setLabelSize = function (chart, data, options) {
  764. var maxLabelSize = Math.ceil(chart.element.offsetWidth / 4.0 / data.labels.length);
  765. if (maxLabelSize > 25) {
  766. maxLabelSize = 25;
  767. }
  768. options.scales.xAxes[0].ticks.callback = function (value) {
  769. value = toStr(value);
  770. if (value.length > maxLabelSize) {
  771. return value.substring(0, maxLabelSize - 2) + "...";
  772. } else {
  773. return value;
  774. }
  775. };
  776. };
  777. var jsOptions = jsOptionsFunc(merge(baseOptions, defaultOptions), hideLegend, setMin, setMax, setStacked, setXtitle, setYtitle);
  778. var createDataTable = function (chart, options, chartType) {
  779. var datasets = [];
  780. var labels = [];
  781. var colors = chart.options.colors || defaultColors;
  782. var day = true;
  783. var week = true;
  784. var dayOfWeek;
  785. var month = true;
  786. var year = true;
  787. var hour = true;
  788. var minute = true;
  789. var detectType = (chartType === "line" || chartType === "area") && !chart.options.discrete;
  790. var series = chart.data;
  791. var sortedLabels = [];
  792. var i, j, s, d, key, rows = [];
  793. for (i = 0; i < series.length; i++) {
  794. s = series[i];
  795. for (j = 0; j < s.data.length; j++) {
  796. d = s.data[j];
  797. key = detectType ? d[0].getTime() : d[0];
  798. if (!rows[key]) {
  799. rows[key] = new Array(series.length);
  800. }
  801. rows[key][i] = toFloat(d[1]);
  802. if (sortedLabels.indexOf(key) === -1) {
  803. sortedLabels.push(key);
  804. }
  805. }
  806. }
  807. if (detectType) {
  808. sortedLabels.sort(sortByNumber);
  809. }
  810. var rows2 = [];
  811. for (j = 0; j < series.length; j++) {
  812. rows2.push([]);
  813. }
  814. var value;
  815. var k;
  816. for (k = 0; k < sortedLabels.length; k++) {
  817. i = sortedLabels[k];
  818. if (detectType) {
  819. value = new Date(toFloat(i));
  820. // TODO make this efficient
  821. day = day && isDay(value);
  822. if (!dayOfWeek) {
  823. dayOfWeek = value.getDay();
  824. }
  825. week = week && isWeek(value, dayOfWeek);
  826. month = month && isMonth(value);
  827. year = year && isYear(value);
  828. hour = hour && isHour(value);
  829. minute = minute && isMinute(value);
  830. } else {
  831. value = i;
  832. }
  833. labels.push(value);
  834. for (j = 0; j < series.length; j++) {
  835. rows2[j].push(rows[i][j]);
  836. }
  837. }
  838. for (i = 0; i < series.length; i++) {
  839. s = series[i];
  840. var backgroundColor = chartType !== "line" ? addOpacity(colors[i], 0.5) : colors[i];
  841. var dataset = {
  842. label: s.name,
  843. data: rows2[i],
  844. fill: chartType === "area",
  845. borderColor: colors[i],
  846. backgroundColor: backgroundColor,
  847. pointBackgroundColor: colors[i],
  848. borderWidth: 2
  849. };
  850. datasets.push(merge(dataset, s.library || {}));
  851. }
  852. if (detectType && labels.length > 0) {
  853. var minTime = labels[0].getTime();
  854. var maxTime = labels[0].getTime();
  855. for (i = 1; i < labels.length; i++) {
  856. value = labels[i].getTime();
  857. if (value < minTime) {
  858. minTime = value;
  859. }
  860. if (value > maxTime) {
  861. maxTime = value;
  862. }
  863. }
  864. var timeDiff = (maxTime - minTime) / (86400 * 1000.0);
  865. if (!options.scales.xAxes[0].time.unit) {
  866. var step;
  867. if (year || timeDiff > 365 * 10) {
  868. options.scales.xAxes[0].time.unit = "year";
  869. step = 365;
  870. } else if (month || timeDiff > 30 * 10) {
  871. options.scales.xAxes[0].time.unit = "month";
  872. step = 30;
  873. } else if (day || timeDiff > 10) {
  874. options.scales.xAxes[0].time.unit = "day";
  875. step = 1;
  876. } else if (hour) {
  877. options.scales.xAxes[0].time.unit = "hour";
  878. step = 1 / 24.0;
  879. } else if (minute) {
  880. options.scales.xAxes[0].time.displayFormats = {minute: "h:mm a"};
  881. options.scales.xAxes[0].time.unit = "minute";
  882. step = 1 / 24.0 / 60.0;
  883. }
  884. if (step && timeDiff > 0) {
  885. var unitStepSize = Math.ceil(timeDiff / step / (chart.element.offsetWidth / 100.0));
  886. if (week && step === 1) {
  887. unitStepSize = Math.ceil(unitStepSize / 7.0) * 7;
  888. }
  889. options.scales.xAxes[0].time.unitStepSize = unitStepSize;
  890. }
  891. }
  892. if (!options.scales.xAxes[0].time.tooltipFormat) {
  893. if (day) {
  894. options.scales.xAxes[0].time.tooltipFormat = "ll";
  895. } else if (hour) {
  896. options.scales.xAxes[0].time.tooltipFormat = "MMM D, h a";
  897. } else if (minute) {
  898. options.scales.xAxes[0].time.tooltipFormat = "h:mm a";
  899. }
  900. }
  901. }
  902. var data = {
  903. labels: labels,
  904. datasets: datasets
  905. };
  906. return data;
  907. };
  908. this.renderLineChart = function (chart, chartType) {
  909. var areaOptions = {};
  910. if (chartType === "area") {
  911. // TODO fix area stacked
  912. // areaOptions.stacked = true;
  913. }
  914. // fix for https://github.com/chartjs/Chart.js/issues/2441
  915. if (!chart.options.max && allZeros(chart.data)) {
  916. chart.options.max = 1;
  917. }
  918. var options = jsOptions(chart.data, merge(areaOptions, chart.options));
  919. var data = createDataTable(chart, options, chartType || "line");
  920. options.scales.xAxes[0].type = chart.options.discrete ? "category" : "time";
  921. drawChart(chart, "line", data, options);
  922. };
  923. this.renderPieChart = function (chart) {
  924. var options = merge(baseOptions, chart.options.library || {});
  925. var labels = [];
  926. var values = [];
  927. for (var i = 0; i < chart.data.length; i++) {
  928. var point = chart.data[i];
  929. labels.push(point[0]);
  930. values.push(point[1]);
  931. }
  932. var data = {
  933. labels: labels,
  934. datasets: [
  935. {
  936. data: values,
  937. backgroundColor: chart.options.colors || defaultColors
  938. }
  939. ]
  940. };
  941. drawChart(chart, "pie", data, options);
  942. };
  943. this.renderColumnChart = function (chart, chartType) {
  944. var options;
  945. if (chartType === "bar") {
  946. options = jsOptionsFunc(merge(baseOptions, defaultOptions), hideLegend, setBarMin, setBarMax, setStacked)(chart.data, chart.options);
  947. } else {
  948. options = jsOptions(chart.data, chart.options);
  949. }
  950. var data = createDataTable(chart, options, "column");
  951. setLabelSize(chart, data, options);
  952. drawChart(chart, (chartType === "bar" ? "horizontalBar" : "bar"), data, options);
  953. };
  954. var self = this;
  955. this.renderAreaChart = function (chart) {
  956. self.renderLineChart(chart, "area");
  957. };
  958. this.renderBarChart = function (chart) {
  959. self.renderColumnChart(chart, "bar");
  960. };
  961. };
  962. adapters.unshift(ChartjsAdapter);
  963. }
  964. }
  965. // TODO remove chartType if cross-browser way
  966. // to get the name of the chart class
  967. function renderChart(chartType, chart) {
  968. var i, adapter, fnName, adapterName;
  969. fnName = "render" + chartType;
  970. adapterName = chart.options.adapter;
  971. loadAdapters();
  972. for (i = 0; i < adapters.length; i++) {
  973. adapter = adapters[i];
  974. if ((!adapterName || adapterName === adapter.name) && isFunction(adapter[fnName])) {
  975. return adapter[fnName](chart);
  976. }
  977. }
  978. throw new Error("No adapter found");
  979. }
  980. // process data
  981. var toFormattedKey = function (key, keyType) {
  982. if (keyType === "number") {
  983. key = toFloat(key);
  984. } else if (keyType === "datetime") {
  985. key = toDate(key);
  986. } else {
  987. key = toStr(key);
  988. }
  989. return key;
  990. };
  991. var formatSeriesData = function (data, keyType) {
  992. var r = [], key, j;
  993. for (j = 0; j < data.length; j++) {
  994. key = toFormattedKey(data[j][0], keyType);
  995. r.push([key, toFloat(data[j][1])]);
  996. }
  997. if (keyType === "datetime") {
  998. r.sort(sortByTime);
  999. }
  1000. return r;
  1001. };
  1002. function isMinute(d) {
  1003. return d.getMilliseconds() === 0 && d.getSeconds() === 0;
  1004. }
  1005. function isHour(d) {
  1006. return isMinute(d) && d.getMinutes() === 0;
  1007. }
  1008. function isDay(d) {
  1009. return isHour(d) && d.getHours() === 0;
  1010. }
  1011. function isWeek(d, dayOfWeek) {
  1012. return isDay(d) && d.getDay() === dayOfWeek;
  1013. }
  1014. function isMonth(d) {
  1015. return isDay(d) && d.getDate() === 1;
  1016. }
  1017. function isYear(d) {
  1018. return isMonth(d) && d.getMonth() === 0;
  1019. }
  1020. function isDate(obj) {
  1021. return !isNaN(toDate(obj)) && toStr(obj).length >= 6;
  1022. }
  1023. function allZeros(data) {
  1024. var i, j, d;
  1025. for (i = 0; i < data.length; i++) {
  1026. d = data[i].data;
  1027. for (j = 0; j < d.length; j++) {
  1028. if (d[j][1] != 0) {
  1029. return false;
  1030. }
  1031. }
  1032. }
  1033. return true;
  1034. }
  1035. function detectDiscrete(series) {
  1036. var i, j, data;
  1037. for (i = 0; i < series.length; i++) {
  1038. data = toArr(series[i].data);
  1039. for (j = 0; j < data.length; j++) {
  1040. if (!isDate(data[j][0])) {
  1041. return true;
  1042. }
  1043. }
  1044. }
  1045. return false;
  1046. }
  1047. function processSeries(series, opts, keyType) {
  1048. var i;
  1049. // see if one series or multiple
  1050. if (!isArray(series) || typeof series[0] !== "object" || isArray(series[0])) {
  1051. series = [{name: opts.label || "Value", data: series}];
  1052. opts.hideLegend = true;
  1053. } else {
  1054. opts.hideLegend = false;
  1055. }
  1056. if ((opts.discrete === null || opts.discrete === undefined)) {
  1057. opts.discrete = detectDiscrete(series);
  1058. }
  1059. if (opts.discrete) {
  1060. keyType = "string";
  1061. }
  1062. // right format
  1063. for (i = 0; i < series.length; i++) {
  1064. series[i].data = formatSeriesData(toArr(series[i].data), keyType);
  1065. }
  1066. return series;
  1067. }
  1068. function processSimple(data) {
  1069. var perfectData = toArr(data), i;
  1070. for (i = 0; i < perfectData.length; i++) {
  1071. perfectData[i] = [toStr(perfectData[i][0]), toFloat(perfectData[i][1])];
  1072. }
  1073. return perfectData;
  1074. }
  1075. function processTime(data)
  1076. {
  1077. var i;
  1078. for (i = 0; i < data.length; i++) {
  1079. data[i][1] = toDate(data[i][1]);
  1080. data[i][2] = toDate(data[i][2]);
  1081. }
  1082. return data;
  1083. }
  1084. function processLineData(chart) {
  1085. chart.data = processSeries(chart.data, chart.options, "datetime");
  1086. renderChart("LineChart", chart);
  1087. }
  1088. function processColumnData(chart) {
  1089. chart.data = processSeries(chart.data, chart.options, "string");
  1090. renderChart("ColumnChart", chart);
  1091. }
  1092. function processPieData(chart) {
  1093. chart.data = processSimple(chart.data);
  1094. renderChart("PieChart", chart);
  1095. }
  1096. function processBarData(chart) {
  1097. chart.data = processSeries(chart.data, chart.options, "string");
  1098. renderChart("BarChart", chart);
  1099. }
  1100. function processAreaData(chart) {
  1101. chart.data = processSeries(chart.data, chart.options, "datetime");
  1102. renderChart("AreaChart", chart);
  1103. }
  1104. function processGeoData(chart) {
  1105. chart.data = processSimple(chart.data);
  1106. renderChart("GeoChart", chart);
  1107. }
  1108. function processScatterData(chart) {
  1109. chart.data = processSeries(chart.data, chart.options, "number");
  1110. renderChart("ScatterChart", chart);
  1111. }
  1112. function processTimelineData(chart) {
  1113. chart.data = processTime(chart.data);
  1114. renderChart("Timeline", chart);
  1115. }
  1116. function setElement(chart, element, dataSource, opts, callback) {
  1117. var elementId;
  1118. if (typeof element === "string") {
  1119. elementId = element;
  1120. element = document.getElementById(element);
  1121. if (!element) {
  1122. throw new Error("No element with id " + elementId);
  1123. }
  1124. }
  1125. chart.element = element;
  1126. chart.options = opts || {};
  1127. chart.dataSource = dataSource;
  1128. chart.getElement = function () {
  1129. return element;
  1130. };
  1131. chart.getData = function () {
  1132. return chart.data;
  1133. };
  1134. chart.getOptions = function () {
  1135. return opts || {};
  1136. };
  1137. chart.getChartObject = function () {
  1138. return chart.chart;
  1139. };
  1140. Chartkick.charts[element.id] = chart;
  1141. fetchDataSource(chart, callback);
  1142. }
  1143. // define classes
  1144. Chartkick = {
  1145. LineChart: function (element, dataSource, opts) {
  1146. setElement(this, element, dataSource, opts, processLineData);
  1147. },
  1148. PieChart: function (element, dataSource, opts) {
  1149. setElement(this, element, dataSource, opts, processPieData);
  1150. },
  1151. ColumnChart: function (element, dataSource, opts) {
  1152. setElement(this, element, dataSource, opts, processColumnData);
  1153. },
  1154. BarChart: function (element, dataSource, opts) {
  1155. setElement(this, element, dataSource, opts, processBarData);
  1156. },
  1157. AreaChart: function (element, dataSource, opts) {
  1158. setElement(this, element, dataSource, opts, processAreaData);
  1159. },
  1160. GeoChart: function (element, dataSource, opts) {
  1161. setElement(this, element, dataSource, opts, processGeoData);
  1162. },
  1163. ScatterChart: function (element, dataSource, opts) {
  1164. setElement(this, element, dataSource, opts, processScatterData);
  1165. },
  1166. Timeline: function (element, dataSource, opts) {
  1167. setElement(this, element, dataSource, opts, processTimelineData);
  1168. },
  1169. charts: {}
  1170. };
  1171. if (typeof module === "object" && typeof module.exports === "object") {
  1172. module.exports = Chartkick;
  1173. } else {
  1174. window.Chartkick = Chartkick;
  1175. }
  1176. }(window));