File manager - Edit - /home/newsbmcs.com/public_html/static/img/logo/charts.zip
Back
PK ɫ�ZqD#�e3 e3 morris/morris.jsnu �[��� /* @license morris.js v0.5.0 Copyright 2014 Olly Smith All rights reserved. Licensed under the BSD-2-Clause License. */ (function() { var $, Morris, minutesSpecHelper, secondsSpecHelper, __slice = [].slice, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; Morris = window.Morris = {}; $ = jQuery; Morris.EventEmitter = (function() { function EventEmitter() {} EventEmitter.prototype.on = function(name, handler) { if (this.handlers == null) { this.handlers = {}; } if (this.handlers[name] == null) { this.handlers[name] = []; } this.handlers[name].push(handler); return this; }; EventEmitter.prototype.fire = function() { var args, handler, name, _i, _len, _ref, _results; name = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; if ((this.handlers != null) && (this.handlers[name] != null)) { _ref = this.handlers[name]; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { handler = _ref[_i]; _results.push(handler.apply(null, args)); } return _results; } }; return EventEmitter; })(); Morris.commas = function(num) { var absnum, intnum, ret, strabsnum; if (num != null) { ret = num < 0 ? "-" : ""; absnum = Math.abs(num); intnum = Math.floor(absnum).toFixed(0); ret += intnum.replace(/(?=(?:\d{3})+$)(?!^)/g, ','); strabsnum = absnum.toString(); if (strabsnum.length > intnum.length) { ret += strabsnum.slice(intnum.length); } return ret; } else { return '-'; } }; Morris.pad2 = function(number) { return (number < 10 ? '0' : '') + number; }; Morris.Grid = (function(_super) { __extends(Grid, _super); function Grid(options) { this.resizeHandler = __bind(this.resizeHandler, this); var _this = this; if (typeof options.element === 'string') { this.el = $(document.getElementById(options.element)); } else { this.el = $(options.element); } if ((this.el == null) || this.el.length === 0) { throw new Error("Graph container element not found"); } if (this.el.css('position') === 'static') { this.el.css('position', 'relative'); } this.options = $.extend({}, this.gridDefaults, this.defaults || {}, options); if (typeof this.options.units === 'string') { this.options.postUnits = options.units; } this.raphael = new Raphael(this.el[0]); this.elementWidth = null; this.elementHeight = null; this.dirty = false; this.selectFrom = null; if (this.init) { this.init(); } this.setData(this.options.data); this.el.bind('mousemove', function(evt) { var left, offset, right, width, x; offset = _this.el.offset(); x = evt.pageX - offset.left; if (_this.selectFrom) { left = _this.data[_this.hitTest(Math.min(x, _this.selectFrom))]._x; right = _this.data[_this.hitTest(Math.max(x, _this.selectFrom))]._x; width = right - left; return _this.selectionRect.attr({ x: left, width: width }); } else { return _this.fire('hovermove', x, evt.pageY - offset.top); } }); this.el.bind('mouseleave', function(evt) { if (_this.selectFrom) { _this.selectionRect.hide(); _this.selectFrom = null; } return _this.fire('hoverout'); }); this.el.bind('touchstart touchmove touchend', function(evt) { var offset, touch; touch = evt.originalEvent.touches[0] || evt.originalEvent.changedTouches[0]; offset = _this.el.offset(); return _this.fire('hovermove', touch.pageX - offset.left, touch.pageY - offset.top); }); this.el.bind('click', function(evt) { var offset; offset = _this.el.offset(); return _this.fire('gridclick', evt.pageX - offset.left, evt.pageY - offset.top); }); if (this.options.rangeSelect) { this.selectionRect = this.raphael.rect(0, 0, 0, this.el.innerHeight()).attr({ fill: this.options.rangeSelectColor, stroke: false }).toBack().hide(); this.el.bind('mousedown', function(evt) { var offset; offset = _this.el.offset(); return _this.startRange(evt.pageX - offset.left); }); this.el.bind('mouseup', function(evt) { var offset; offset = _this.el.offset(); _this.endRange(evt.pageX - offset.left); return _this.fire('hovermove', evt.pageX - offset.left, evt.pageY - offset.top); }); } if (this.options.resize) { $(window).bind('resize', function(evt) { if (_this.timeoutId != null) { window.clearTimeout(_this.timeoutId); } return _this.timeoutId = window.setTimeout(_this.resizeHandler, 100); }); } this.el.css('-webkit-tap-highlight-color', 'rgba(0,0,0,0)'); if (this.postInit) { this.postInit(); } } Grid.prototype.gridDefaults = { dateFormat: null, axes: true, grid: true, gridLineColor: '#aaa', gridStrokeWidth: 0.5, gridTextColor: '#888', gridTextSize: 12, gridTextFamily: 'sans-serif', gridTextWeight: 'normal', hideHover: false, yLabelFormat: null, xLabelAngle: 0, numLines: 5, padding: 25, parseTime: true, postUnits: '', preUnits: '', ymax: 'auto', ymin: 'auto 0', goals: [], goalStrokeWidth: 1.0, goalLineColors: ['#666633', '#999966', '#cc6666', '#663333'], events: [], eventStrokeWidth: 1.0, eventLineColors: ['#005a04', '#ccffbb', '#3a5f0b', '#005502'], rangeSelect: null, rangeSelectColor: '#eef', resize: false }; Grid.prototype.setData = function(data, redraw) { var e, idx, index, maxGoal, minGoal, ret, row, step, total, y, ykey, ymax, ymin, yval, _ref; if (redraw == null) { redraw = true; } this.options.data = data; if ((data == null) || data.length === 0) { this.data = []; this.raphael.clear(); if (this.hover != null) { this.hover.hide(); } return; } ymax = this.cumulative ? 0 : null; ymin = this.cumulative ? 0 : null; if (this.options.goals.length > 0) { minGoal = Math.min.apply(Math, this.options.goals); maxGoal = Math.max.apply(Math, this.options.goals); ymin = ymin != null ? Math.min(ymin, minGoal) : minGoal; ymax = ymax != null ? Math.max(ymax, maxGoal) : maxGoal; } this.data = (function() { var _i, _len, _results; _results = []; for (index = _i = 0, _len = data.length; _i < _len; index = ++_i) { row = data[index]; ret = { src: row }; ret.label = row[this.options.xkey]; if (this.options.parseTime) { ret.x = Morris.parseDate(ret.label); if (this.options.dateFormat) { ret.label = this.options.dateFormat(ret.x); } else if (typeof ret.label === 'number') { ret.label = new Date(ret.label).toString(); } } else { ret.x = index; if (this.options.xLabelFormat) { ret.label = this.options.xLabelFormat(ret); } } total = 0; ret.y = (function() { var _j, _len1, _ref, _results1; _ref = this.options.ykeys; _results1 = []; for (idx = _j = 0, _len1 = _ref.length; _j < _len1; idx = ++_j) { ykey = _ref[idx]; yval = row[ykey]; if (typeof yval === 'string') { yval = parseFloat(yval); } if ((yval != null) && typeof yval !== 'number') { yval = null; } if (yval != null) { if (this.cumulative) { total += yval; } else { if (ymax != null) { ymax = Math.max(yval, ymax); ymin = Math.min(yval, ymin); } else { ymax = ymin = yval; } } } if (this.cumulative && (total != null)) { ymax = Math.max(total, ymax); ymin = Math.min(total, ymin); } _results1.push(yval); } return _results1; }).call(this); _results.push(ret); } return _results; }).call(this); if (this.options.parseTime) { this.data = this.data.sort(function(a, b) { return (a.x > b.x) - (b.x > a.x); }); } this.xmin = this.data[0].x; this.xmax = this.data[this.data.length - 1].x; this.events = []; if (this.options.events.length > 0) { if (this.options.parseTime) { this.events = (function() { var _i, _len, _ref, _results; _ref = this.options.events; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { e = _ref[_i]; _results.push(Morris.parseDate(e)); } return _results; }).call(this); } else { this.events = this.options.events; } this.xmax = Math.max(this.xmax, Math.max.apply(Math, this.events)); this.xmin = Math.min(this.xmin, Math.min.apply(Math, this.events)); } if (this.xmin === this.xmax) { this.xmin -= 1; this.xmax += 1; } this.ymin = this.yboundary('min', ymin); this.ymax = this.yboundary('max', ymax); if (this.ymin === this.ymax) { if (ymin) { this.ymin -= 1; } this.ymax += 1; } if (((_ref = this.options.axes) === true || _ref === 'both' || _ref === 'y') || this.options.grid === true) { if (this.options.ymax === this.gridDefaults.ymax && this.options.ymin === this.gridDefaults.ymin) { this.grid = this.autoGridLines(this.ymin, this.ymax, this.options.numLines); this.ymin = Math.min(this.ymin, this.grid[0]); this.ymax = Math.max(this.ymax, this.grid[this.grid.length - 1]); } else { step = (this.ymax - this.ymin) / (this.options.numLines - 1); this.grid = (function() { var _i, _ref1, _ref2, _results; _results = []; for (y = _i = _ref1 = this.ymin, _ref2 = this.ymax; step > 0 ? _i <= _ref2 : _i >= _ref2; y = _i += step) { _results.push(y); } return _results; }).call(this); } } this.dirty = true; if (redraw) { return this.redraw(); } }; Grid.prototype.yboundary = function(boundaryType, currentValue) { var boundaryOption, suggestedValue; boundaryOption = this.options["y" + boundaryType]; if (typeof boundaryOption === 'string') { if (boundaryOption.slice(0, 4) === 'auto') { if (boundaryOption.length > 5) { suggestedValue = parseInt(boundaryOption.slice(5), 10); if (currentValue == null) { return suggestedValue; } return Math[boundaryType](currentValue, suggestedValue); } else { if (currentValue != null) { return currentValue; } else { return 0; } } } else { return parseInt(boundaryOption, 10); } } else { return boundaryOption; } }; Grid.prototype.autoGridLines = function(ymin, ymax, nlines) { var gmax, gmin, grid, smag, span, step, unit, y, ymag; span = ymax - ymin; ymag = Math.floor(Math.log(span) / Math.log(10)); unit = Math.pow(10, ymag); gmin = Math.floor(ymin / unit) * unit; gmax = Math.ceil(ymax / unit) * unit; step = (gmax - gmin) / (nlines - 1); if (unit === 1 && step > 1 && Math.ceil(step) !== step) { step = Math.ceil(step); gmax = gmin + step * (nlines - 1); } if (gmin < 0 && gmax > 0) { gmin = Math.floor(ymin / step) * step; gmax = Math.ceil(ymax / step) * step; } if (step < 1) { smag = Math.floor(Math.log(step) / Math.log(10)); grid = (function() { var _i, _results; _results = []; for (y = _i = gmin; step > 0 ? _i <= gmax : _i >= gmax; y = _i += step) { _results.push(parseFloat(y.toFixed(1 - smag))); } return _results; })(); } else { grid = (function() { var _i, _results; _results = []; for (y = _i = gmin; step > 0 ? _i <= gmax : _i >= gmax; y = _i += step) { _results.push(y); } return _results; })(); } return grid; }; Grid.prototype._calc = function() { var bottomOffsets, gridLine, h, i, w, yLabelWidths, _ref, _ref1; w = this.el.width(); h = this.el.height(); if (this.elementWidth !== w || this.elementHeight !== h || this.dirty) { this.elementWidth = w; this.elementHeight = h; this.dirty = false; this.left = this.options.padding; this.right = this.elementWidth - this.options.padding; this.top = this.options.padding; this.bottom = this.elementHeight - this.options.padding; if ((_ref = this.options.axes) === true || _ref === 'both' || _ref === 'y') { yLabelWidths = (function() { var _i, _len, _ref1, _results; _ref1 = this.grid; _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { gridLine = _ref1[_i]; _results.push(this.measureText(this.yAxisFormat(gridLine)).width); } return _results; }).call(this); this.left += Math.max.apply(Math, yLabelWidths); } if ((_ref1 = this.options.axes) === true || _ref1 === 'both' || _ref1 === 'x') { bottomOffsets = (function() { var _i, _ref2, _results; _results = []; for (i = _i = 0, _ref2 = this.data.length; 0 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 0 <= _ref2 ? ++_i : --_i) { _results.push(this.measureText(this.data[i].text, -this.options.xLabelAngle).height); } return _results; }).call(this); this.bottom -= Math.max.apply(Math, bottomOffsets); } this.width = Math.max(1, this.right - this.left); this.height = Math.max(1, this.bottom - this.top); this.dx = this.width / (this.xmax - this.xmin); this.dy = this.height / (this.ymax - this.ymin); if (this.calc) { return this.calc(); } } }; Grid.prototype.transY = function(y) { return this.bottom - (y - this.ymin) * this.dy; }; Grid.prototype.transX = function(x) { if (this.data.length === 1) { return (this.left + this.right) / 2; } else { return this.left + (x - this.xmin) * this.dx; } }; Grid.prototype.redraw = function() { this.raphael.clear(); this._calc(); this.drawGrid(); this.drawGoals(); this.drawEvents(); if (this.draw) { return this.draw(); } }; Grid.prototype.measureText = function(text, angle) { var ret, tt; if (angle == null) { angle = 0; } tt = this.raphael.text(100, 100, text).attr('font-size', this.options.gridTextSize).attr('font-family', this.options.gridTextFamily).attr('font-weight', this.options.gridTextWeight).rotate(angle); ret = tt.getBBox(); tt.remove(); return ret; }; Grid.prototype.yAxisFormat = function(label) { return this.yLabelFormat(label); }; Grid.prototype.yLabelFormat = function(label) { if (typeof this.options.yLabelFormat === 'function') { return this.options.yLabelFormat(label); } else { return "" + this.options.preUnits + (Morris.commas(label)) + this.options.postUnits; } }; Grid.prototype.drawGrid = function() { var lineY, y, _i, _len, _ref, _ref1, _ref2, _results; if (this.options.grid === false && ((_ref = this.options.axes) !== true && _ref !== 'both' && _ref !== 'y')) { return; } _ref1 = this.grid; _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { lineY = _ref1[_i]; y = this.transY(lineY); if ((_ref2 = this.options.axes) === true || _ref2 === 'both' || _ref2 === 'y') { this.drawYAxisLabel(this.left - this.options.padding / 2, y, this.yAxisFormat(lineY)); } if (this.options.grid) { _results.push(this.drawGridLine("M" + this.left + "," + y + "H" + (this.left + this.width))); } else { _results.push(void 0); } } return _results; }; Grid.prototype.drawGoals = function() { var color, goal, i, _i, _len, _ref, _results; _ref = this.options.goals; _results = []; for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { goal = _ref[i]; color = this.options.goalLineColors[i % this.options.goalLineColors.length]; _results.push(this.drawGoal(goal, color)); } return _results; }; Grid.prototype.drawEvents = function() { var color, event, i, _i, _len, _ref, _results; _ref = this.events; _results = []; for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { event = _ref[i]; color = this.options.eventLineColors[i % this.options.eventLineColors.length]; _results.push(this.drawEvent(event, color)); } return _results; }; Grid.prototype.drawGoal = function(goal, color) { return this.raphael.path("M" + this.left + "," + (this.transY(goal)) + "H" + this.right).attr('stroke', color).attr('stroke-width', this.options.goalStrokeWidth); }; Grid.prototype.drawEvent = function(event, color) { return this.raphael.path("M" + (this.transX(event)) + "," + this.bottom + "V" + this.top).attr('stroke', color).attr('stroke-width', this.options.eventStrokeWidth); }; Grid.prototype.drawYAxisLabel = function(xPos, yPos, text) { return this.raphael.text(xPos, yPos, text).attr('font-size', this.options.gridTextSize).attr('font-family', this.options.gridTextFamily).attr('font-weight', this.options.gridTextWeight).attr('fill', this.options.gridTextColor).attr('text-anchor', 'end'); }; Grid.prototype.drawGridLine = function(path) { return this.raphael.path(path).attr('stroke', this.options.gridLineColor).attr('stroke-width', this.options.gridStrokeWidth); }; Grid.prototype.startRange = function(x) { this.hover.hide(); this.selectFrom = x; return this.selectionRect.attr({ x: x, width: 0 }).show(); }; Grid.prototype.endRange = function(x) { var end, start; if (this.selectFrom) { start = Math.min(this.selectFrom, x); end = Math.max(this.selectFrom, x); this.options.rangeSelect.call(this.el, { start: this.data[this.hitTest(start)].x, end: this.data[this.hitTest(end)].x }); return this.selectFrom = null; } }; Grid.prototype.resizeHandler = function() { this.timeoutId = null; this.raphael.setSize(this.el.width(), this.el.height()); return this.redraw(); }; return Grid; })(Morris.EventEmitter); Morris.parseDate = function(date) { var isecs, m, msecs, n, o, offsetmins, p, q, r, ret, secs; if (typeof date === 'number') { return date; } m = date.match(/^(\d+) Q(\d)$/); n = date.match(/^(\d+)-(\d+)$/); o = date.match(/^(\d+)-(\d+)-(\d+)$/); p = date.match(/^(\d+) W(\d+)$/); q = date.match(/^(\d+)-(\d+)-(\d+)[ T](\d+):(\d+)(Z|([+-])(\d\d):?(\d\d))?$/); r = date.match(/^(\d+)-(\d+)-(\d+)[ T](\d+):(\d+):(\d+(\.\d+)?)(Z|([+-])(\d\d):?(\d\d))?$/); if (m) { return new Date(parseInt(m[1], 10), parseInt(m[2], 10) * 3 - 1, 1).getTime(); } else if (n) { return new Date(parseInt(n[1], 10), parseInt(n[2], 10) - 1, 1).getTime(); } else if (o) { return new Date(parseInt(o[1], 10), parseInt(o[2], 10) - 1, parseInt(o[3], 10)).getTime(); } else if (p) { ret = new Date(parseInt(p[1], 10), 0, 1); if (ret.getDay() !== 4) { ret.setMonth(0, 1 + ((4 - ret.getDay()) + 7) % 7); } return ret.getTime() + parseInt(p[2], 10) * 604800000; } else if (q) { if (!q[6]) { return new Date(parseInt(q[1], 10), parseInt(q[2], 10) - 1, parseInt(q[3], 10), parseInt(q[4], 10), parseInt(q[5], 10)).getTime(); } else { offsetmins = 0; if (q[6] !== 'Z') { offsetmins = parseInt(q[8], 10) * 60 + parseInt(q[9], 10); if (q[7] === '+') { offsetmins = 0 - offsetmins; } } return Date.UTC(parseInt(q[1], 10), parseInt(q[2], 10) - 1, parseInt(q[3], 10), parseInt(q[4], 10), parseInt(q[5], 10) + offsetmins); } } else if (r) { secs = parseFloat(r[6]); isecs = Math.floor(secs); msecs = Math.round((secs - isecs) * 1000); if (!r[8]) { return new Date(parseInt(r[1], 10), parseInt(r[2], 10) - 1, parseInt(r[3], 10), parseInt(r[4], 10), parseInt(r[5], 10), isecs, msecs).getTime(); } else { offsetmins = 0; if (r[8] !== 'Z') { offsetmins = parseInt(r[10], 10) * 60 + parseInt(r[11], 10); if (r[9] === '+') { offsetmins = 0 - offsetmins; } } return Date.UTC(parseInt(r[1], 10), parseInt(r[2], 10) - 1, parseInt(r[3], 10), parseInt(r[4], 10), parseInt(r[5], 10) + offsetmins, isecs, msecs); } } else { return new Date(parseInt(date, 10), 0, 1).getTime(); } }; Morris.Hover = (function() { Hover.defaults = { "class": 'morris-hover morris-default-style' }; function Hover(options) { if (options == null) { options = {}; } this.options = $.extend({}, Morris.Hover.defaults, options); this.el = $("<div class='" + this.options["class"] + "'></div>"); this.el.hide(); this.options.parent.append(this.el); } Hover.prototype.update = function(html, x, y) { if (!html) { return this.hide(); } else { this.html(html); this.show(); return this.moveTo(x, y); } }; Hover.prototype.html = function(content) { return this.el.html(content); }; Hover.prototype.moveTo = function(x, y) { var hoverHeight, hoverWidth, left, parentHeight, parentWidth, top; parentWidth = this.options.parent.innerWidth(); parentHeight = this.options.parent.innerHeight(); hoverWidth = this.el.outerWidth(); hoverHeight = this.el.outerHeight(); left = Math.min(Math.max(0, x - hoverWidth / 2), parentWidth - hoverWidth); if (y != null) { top = y - hoverHeight - 10; if (top < 0) { top = y + 10; if (top + hoverHeight > parentHeight) { top = parentHeight / 2 - hoverHeight / 2; } } } else { top = parentHeight / 2 - hoverHeight / 2; } return this.el.css({ left: left + "px", top: parseInt(top) + "px" }); }; Hover.prototype.show = function() { return this.el.show(); }; Hover.prototype.hide = function() { return this.el.hide(); }; return Hover; })(); Morris.Line = (function(_super) { __extends(Line, _super); function Line(options) { this.hilight = __bind(this.hilight, this); this.onHoverOut = __bind(this.onHoverOut, this); this.onHoverMove = __bind(this.onHoverMove, this); this.onGridClick = __bind(this.onGridClick, this); if (!(this instanceof Morris.Line)) { return new Morris.Line(options); } Line.__super__.constructor.call(this, options); } Line.prototype.init = function() { if (this.options.hideHover !== 'always') { this.hover = new Morris.Hover({ parent: this.el }); this.on('hovermove', this.onHoverMove); this.on('hoverout', this.onHoverOut); return this.on('gridclick', this.onGridClick); } }; Line.prototype.defaults = { lineWidth: 3, pointSize: 4, lineColors: ['#0b62a4', '#7A92A3', '#4da74d', '#afd8f8', '#edc240', '#cb4b4b', '#9440ed'], pointStrokeWidths: [1], pointStrokeColors: ['#ffffff'], pointFillColors: [], smooth: true, xLabels: 'auto', xLabelFormat: null, xLabelMargin: 24, hideHover: false }; Line.prototype.calc = function() { this.calcPoints(); return this.generatePaths(); }; Line.prototype.calcPoints = function() { var row, y, _i, _len, _ref, _results; _ref = this.data; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { row = _ref[_i]; row._x = this.transX(row.x); row._y = (function() { var _j, _len1, _ref1, _results1; _ref1 = row.y; _results1 = []; for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { y = _ref1[_j]; if (y != null) { _results1.push(this.transY(y)); } else { _results1.push(y); } } return _results1; }).call(this); _results.push(row._ymax = Math.min.apply(Math, [this.bottom].concat((function() { var _j, _len1, _ref1, _results1; _ref1 = row._y; _results1 = []; for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { y = _ref1[_j]; if (y != null) { _results1.push(y); } } return _results1; })()))); } return _results; }; Line.prototype.hitTest = function(x) { var index, r, _i, _len, _ref; if (this.data.length === 0) { return null; } _ref = this.data.slice(1); for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) { r = _ref[index]; if (x < (r._x + this.data[index]._x) / 2) { break; } } return index; }; Line.prototype.onGridClick = function(x, y) { var index; index = this.hitTest(x); return this.fire('click', index, this.data[index].src, x, y); }; Line.prototype.onHoverMove = function(x, y) { var index; index = this.hitTest(x); return this.displayHoverForRow(index); }; Line.prototype.onHoverOut = function() { if (this.options.hideHover !== false) { return this.displayHoverForRow(null); } }; Line.prototype.displayHoverForRow = function(index) { var _ref; if (index != null) { (_ref = this.hover).update.apply(_ref, this.hoverContentForRow(index)); return this.hilight(index); } else { this.hover.hide(); return this.hilight(); } }; Line.prototype.hoverContentForRow = function(index) { var content, j, row, y, _i, _len, _ref; row = this.data[index]; content = "<div class='morris-hover-row-label'>" + row.label + "</div>"; _ref = row.y; for (j = _i = 0, _len = _ref.length; _i < _len; j = ++_i) { y = _ref[j]; content += "<div class='morris-hover-point' style='color: " + (this.colorFor(row, j, 'label')) + "'>\n " + this.options.labels[j] + ":\n " + (this.yLabelFormat(y)) + "\n</div>"; } if (typeof this.options.hoverCallback === 'function') { content = this.options.hoverCallback(index, this.options, content, row.src); } return [content, row._x, row._ymax]; }; Line.prototype.generatePaths = function() { var coords, i, r, smooth; return this.paths = (function() { var _i, _ref, _ref1, _results; _results = []; for (i = _i = 0, _ref = this.options.ykeys.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { smooth = typeof this.options.smooth === "boolean" ? this.options.smooth : (_ref1 = this.options.ykeys[i], __indexOf.call(this.options.smooth, _ref1) >= 0); coords = (function() { var _j, _len, _ref2, _results1; _ref2 = this.data; _results1 = []; for (_j = 0, _len = _ref2.length; _j < _len; _j++) { r = _ref2[_j]; if (r._y[i] !== void 0) { _results1.push({ x: r._x, y: r._y[i] }); } } return _results1; }).call(this); if (coords.length > 1) { _results.push(Morris.Line.createPath(coords, smooth, this.bottom)); } else { _results.push(null); } } return _results; }).call(this); }; Line.prototype.draw = function() { var _ref; if ((_ref = this.options.axes) === true || _ref === 'both' || _ref === 'x') { this.drawXAxis(); } this.drawSeries(); if (this.options.hideHover === false) { return this.displayHoverForRow(this.data.length - 1); } }; Line.prototype.drawXAxis = function() { var drawLabel, l, labels, prevAngleMargin, prevLabelMargin, row, ypos, _i, _len, _results, _this = this; ypos = this.bottom + this.options.padding / 2; prevLabelMargin = null; prevAngleMargin = null; drawLabel = function(labelText, xpos) { var label, labelBox, margin, offset, textBox; label = _this.drawXAxisLabel(_this.transX(xpos), ypos, labelText); textBox = label.getBBox(); label.transform("r" + (-_this.options.xLabelAngle)); labelBox = label.getBBox(); label.transform("t0," + (labelBox.height / 2) + "..."); if (_this.options.xLabelAngle !== 0) { offset = -0.5 * textBox.width * Math.cos(_this.options.xLabelAngle * Math.PI / 180.0); label.transform("t" + offset + ",0..."); } labelBox = label.getBBox(); if (((prevLabelMargin == null) || prevLabelMargin >= labelBox.x + labelBox.width || (prevAngleMargin != null) && prevAngleMargin >= labelBox.x) && labelBox.x >= 0 && (labelBox.x + labelBox.width) < _this.el.width()) { if (_this.options.xLabelAngle !== 0) { margin = 1.25 * _this.options.gridTextSize / Math.sin(_this.options.xLabelAngle * Math.PI / 180.0); prevAngleMargin = labelBox.x - margin; } return prevLabelMargin = labelBox.x - _this.options.xLabelMargin; } else { return label.remove(); } }; if (this.options.parseTime) { if (this.data.length === 1 && this.options.xLabels === 'auto') { labels = [[this.data[0].label, this.data[0].x]]; } else { labels = Morris.labelSeries(this.xmin, this.xmax, this.width, this.options.xLabels, this.options.xLabelFormat); } } else { labels = (function() { var _i, _len, _ref, _results; _ref = this.data; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { row = _ref[_i]; _results.push([row.label, row.x]); } return _results; }).call(this); } labels.reverse(); _results = []; for (_i = 0, _len = labels.length; _i < _len; _i++) { l = labels[_i]; _results.push(drawLabel(l[0], l[1])); } return _results; }; Line.prototype.drawSeries = function() { var i, _i, _j, _ref, _ref1, _results; this.seriesPoints = []; for (i = _i = _ref = this.options.ykeys.length - 1; _ref <= 0 ? _i <= 0 : _i >= 0; i = _ref <= 0 ? ++_i : --_i) { this._drawLineFor(i); } _results = []; for (i = _j = _ref1 = this.options.ykeys.length - 1; _ref1 <= 0 ? _j <= 0 : _j >= 0; i = _ref1 <= 0 ? ++_j : --_j) { _results.push(this._drawPointFor(i)); } return _results; }; Line.prototype._drawPointFor = function(index) { var circle, row, _i, _len, _ref, _results; this.seriesPoints[index] = []; _ref = this.data; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { row = _ref[_i]; circle = null; if (row._y[index] != null) { circle = this.drawLinePoint(row._x, row._y[index], this.colorFor(row, index, 'point'), index); } _results.push(this.seriesPoints[index].push(circle)); } return _results; }; Line.prototype._drawLineFor = function(index) { var path; path = this.paths[index]; if (path !== null) { return this.drawLinePath(path, this.colorFor(null, index, 'line'), index); } }; Line.createPath = function(coords, smooth, bottom) { var coord, g, grads, i, ix, lg, path, prevCoord, x1, x2, y1, y2, _i, _len; path = ""; if (smooth) { grads = Morris.Line.gradients(coords); } prevCoord = { y: null }; for (i = _i = 0, _len = coords.length; _i < _len; i = ++_i) { coord = coords[i]; if (coord.y != null) { if (prevCoord.y != null) { if (smooth) { g = grads[i]; lg = grads[i - 1]; ix = (coord.x - prevCoord.x) / 4; x1 = prevCoord.x + ix; y1 = Math.min(bottom, prevCoord.y + ix * lg); x2 = coord.x - ix; y2 = Math.min(bottom, coord.y - ix * g); path += "C" + x1 + "," + y1 + "," + x2 + "," + y2 + "," + coord.x + "," + coord.y; } else { path += "L" + coord.x + "," + coord.y; } } else { if (!smooth || (grads[i] != null)) { path += "M" + coord.x + "," + coord.y; } } } prevCoord = coord; } return path; }; Line.gradients = function(coords) { var coord, grad, i, nextCoord, prevCoord, _i, _len, _results; grad = function(a, b) { return (a.y - b.y) / (a.x - b.x); }; _results = []; for (i = _i = 0, _len = coords.length; _i < _len; i = ++_i) { coord = coords[i]; if (coord.y != null) { nextCoord = coords[i + 1] || { y: null }; prevCoord = coords[i - 1] || { y: null }; if ((prevCoord.y != null) && (nextCoord.y != null)) { _results.push(grad(prevCoord, nextCoord)); } else if (prevCoord.y != null) { _results.push(grad(prevCoord, coord)); } else if (nextCoord.y != null) { _results.push(grad(coord, nextCoord)); } else { _results.push(null); } } else { _results.push(null); } } return _results; }; Line.prototype.hilight = function(index) { var i, _i, _j, _ref, _ref1; if (this.prevHilight !== null && this.prevHilight !== index) { for (i = _i = 0, _ref = this.seriesPoints.length - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) { if (this.seriesPoints[i][this.prevHilight]) { this.seriesPoints[i][this.prevHilight].animate(this.pointShrinkSeries(i)); } } } if (index !== null && this.prevHilight !== index) { for (i = _j = 0, _ref1 = this.seriesPoints.length - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; i = 0 <= _ref1 ? ++_j : --_j) { if (this.seriesPoints[i][index]) { this.seriesPoints[i][index].animate(this.pointGrowSeries(i)); } } } return this.prevHilight = index; }; Line.prototype.colorFor = function(row, sidx, type) { if (typeof this.options.lineColors === 'function') { return this.options.lineColors.call(this, row, sidx, type); } else if (type === 'point') { return this.options.pointFillColors[sidx % this.options.pointFillColors.length] || this.options.lineColors[sidx % this.options.lineColors.length]; } else { return this.options.lineColors[sidx % this.options.lineColors.length]; } }; Line.prototype.drawXAxisLabel = function(xPos, yPos, text) { return this.raphael.text(xPos, yPos, text).attr('font-size', this.options.gridTextSize).attr('font-family', this.options.gridTextFamily).attr('font-weight', this.options.gridTextWeight).attr('fill', this.options.gridTextColor); }; Line.prototype.drawLinePath = function(path, lineColor, lineIndex) { return this.raphael.path(path).attr('stroke', lineColor).attr('stroke-width', this.lineWidthForSeries(lineIndex)); }; Line.prototype.drawLinePoint = function(xPos, yPos, pointColor, lineIndex) { return this.raphael.circle(xPos, yPos, this.pointSizeForSeries(lineIndex)).attr('fill', pointColor).attr('stroke-width', this.pointStrokeWidthForSeries(lineIndex)).attr('stroke', this.pointStrokeColorForSeries(lineIndex)); }; Line.prototype.pointStrokeWidthForSeries = function(index) { return this.options.pointStrokeWidths[index % this.options.pointStrokeWidths.length]; }; Line.prototype.pointStrokeColorForSeries = function(index) { return this.options.pointStrokeColors[index % this.options.pointStrokeColors.length]; }; Line.prototype.lineWidthForSeries = function(index) { if (this.options.lineWidth instanceof Array) { return this.options.lineWidth[index % this.options.lineWidth.length]; } else { return this.options.lineWidth; } }; Line.prototype.pointSizeForSeries = function(index) { if (this.options.pointSize instanceof Array) { return this.options.pointSize[index % this.options.pointSize.length]; } else { return this.options.pointSize; } }; Line.prototype.pointGrowSeries = function(index) { return Raphael.animation({ r: this.pointSizeForSeries(index) + 3 }, 25, 'linear'); }; Line.prototype.pointShrinkSeries = function(index) { return Raphael.animation({ r: this.pointSizeForSeries(index) }, 25, 'linear'); }; return Line; })(Morris.Grid); Morris.labelSeries = function(dmin, dmax, pxwidth, specName, xLabelFormat) { var d, d0, ddensity, name, ret, s, spec, t, _i, _len, _ref; ddensity = 200 * (dmax - dmin) / pxwidth; d0 = new Date(dmin); spec = Morris.LABEL_SPECS[specName]; if (spec === void 0) { _ref = Morris.AUTO_LABEL_ORDER; for (_i = 0, _len = _ref.length; _i < _len; _i++) { name = _ref[_i]; s = Morris.LABEL_SPECS[name]; if (ddensity >= s.span) { spec = s; break; } } } if (spec === void 0) { spec = Morris.LABEL_SPECS["second"]; } if (xLabelFormat) { spec = $.extend({}, spec, { fmt: xLabelFormat }); } d = spec.start(d0); ret = []; while ((t = d.getTime()) <= dmax) { if (t >= dmin) { ret.push([spec.fmt(d), t]); } spec.incr(d); } return ret; }; minutesSpecHelper = function(interval) { return { span: interval * 60 * 1000, start: function(d) { return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours()); }, fmt: function(d) { return "" + (Morris.pad2(d.getHours())) + ":" + (Morris.pad2(d.getMinutes())); }, incr: function(d) { return d.setUTCMinutes(d.getUTCMinutes() + interval); } }; }; secondsSpecHelper = function(interval) { return { span: interval * 1000, start: function(d) { return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes()); }, fmt: function(d) { return "" + (Morris.pad2(d.getHours())) + ":" + (Morris.pad2(d.getMinutes())) + ":" + (Morris.pad2(d.getSeconds())); }, incr: function(d) { return d.setUTCSeconds(d.getUTCSeconds() + interval); } }; }; Morris.LABEL_SPECS = { "decade": { span: 172800000000, start: function(d) { return new Date(d.getFullYear() - d.getFullYear() % 10, 0, 1); }, fmt: function(d) { return "" + (d.getFullYear()); }, incr: function(d) { return d.setFullYear(d.getFullYear() + 10); } }, "year": { span: 17280000000, start: function(d) { return new Date(d.getFullYear(), 0, 1); }, fmt: function(d) { return "" + (d.getFullYear()); }, incr: function(d) { return d.setFullYear(d.getFullYear() + 1); } }, "month": { span: 2419200000, start: function(d) { return new Date(d.getFullYear(), d.getMonth(), 1); }, fmt: function(d) { return "" + (d.getFullYear()) + "-" + (Morris.pad2(d.getMonth() + 1)); }, incr: function(d) { return d.setMonth(d.getMonth() + 1); } }, "week": { span: 604800000, start: function(d) { return new Date(d.getFullYear(), d.getMonth(), d.getDate()); }, fmt: function(d) { return "" + (d.getFullYear()) + "-" + (Morris.pad2(d.getMonth() + 1)) + "-" + (Morris.pad2(d.getDate())); }, incr: function(d) { return d.setDate(d.getDate() + 7); } }, "day": { span: 86400000, start: function(d) { return new Date(d.getFullYear(), d.getMonth(), d.getDate()); }, fmt: function(d) { return "" + (d.getFullYear()) + "-" + (Morris.pad2(d.getMonth() + 1)) + "-" + (Morris.pad2(d.getDate())); }, incr: function(d) { return d.setDate(d.getDate() + 1); } }, "hour": minutesSpecHelper(60), "30min": minutesSpecHelper(30), "15min": minutesSpecHelper(15), "10min": minutesSpecHelper(10), "5min": minutesSpecHelper(5), "minute": minutesSpecHelper(1), "30sec": secondsSpecHelper(30), "15sec": secondsSpecHelper(15), "10sec": secondsSpecHelper(10), "5sec": secondsSpecHelper(5), "second": secondsSpecHelper(1) }; Morris.AUTO_LABEL_ORDER = ["decade", "year", "month", "week", "day", "hour", "30min", "15min", "10min", "5min", "minute", "30sec", "15sec", "10sec", "5sec", "second"]; Morris.Area = (function(_super) { var areaDefaults; __extends(Area, _super); areaDefaults = { fillOpacity: 'auto', behaveLikeLine: false }; function Area(options) { var areaOptions; if (!(this instanceof Morris.Area)) { return new Morris.Area(options); } areaOptions = $.extend({}, areaDefaults, options); this.cumulative = !areaOptions.behaveLikeLine; if (areaOptions.fillOpacity === 'auto') { areaOptions.fillOpacity = areaOptions.behaveLikeLine ? .8 : 1; } Area.__super__.constructor.call(this, areaOptions); } Area.prototype.calcPoints = function() { var row, total, y, _i, _len, _ref, _results; _ref = this.data; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { row = _ref[_i]; row._x = this.transX(row.x); total = 0; row._y = (function() { var _j, _len1, _ref1, _results1; _ref1 = row.y; _results1 = []; for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { y = _ref1[_j]; if (this.options.behaveLikeLine) { _results1.push(this.transY(y)); } else { total += y || 0; _results1.push(this.transY(total)); } } return _results1; }).call(this); _results.push(row._ymax = Math.max.apply(Math, row._y)); } return _results; }; Area.prototype.drawSeries = function() { var i, range, _i, _j, _k, _len, _ref, _ref1, _results, _results1, _results2; this.seriesPoints = []; if (this.options.behaveLikeLine) { range = (function() { _results = []; for (var _i = 0, _ref = this.options.ykeys.length - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; 0 <= _ref ? _i++ : _i--){ _results.push(_i); } return _results; }).apply(this); } else { range = (function() { _results1 = []; for (var _j = _ref1 = this.options.ykeys.length - 1; _ref1 <= 0 ? _j <= 0 : _j >= 0; _ref1 <= 0 ? _j++ : _j--){ _results1.push(_j); } return _results1; }).apply(this); } _results2 = []; for (_k = 0, _len = range.length; _k < _len; _k++) { i = range[_k]; this._drawFillFor(i); this._drawLineFor(i); _results2.push(this._drawPointFor(i)); } return _results2; }; Area.prototype._drawFillFor = function(index) { var path; path = this.paths[index]; if (path !== null) { path = path + ("L" + (this.transX(this.xmax)) + "," + this.bottom + "L" + (this.transX(this.xmin)) + "," + this.bottom + "Z"); return this.drawFilledPath(path, this.fillForSeries(index)); } }; Area.prototype.fillForSeries = function(i) { var color; color = Raphael.rgb2hsl(this.colorFor(this.data[i], i, 'line')); return Raphael.hsl(color.h, this.options.behaveLikeLine ? color.s * 0.9 : color.s * 0.75, Math.min(0.98, this.options.behaveLikeLine ? color.l * 1.2 : color.l * 1.25)); }; Area.prototype.drawFilledPath = function(path, fill) { return this.raphael.path(path).attr('fill', fill).attr('fill-opacity', this.options.fillOpacity).attr('stroke', 'none'); }; return Area; })(Morris.Line); Morris.Bar = (function(_super) { __extends(Bar, _super); function Bar(options) { this.onHoverOut = __bind(this.onHoverOut, this); this.onHoverMove = __bind(this.onHoverMove, this); this.onGridClick = __bind(this.onGridClick, this); if (!(this instanceof Morris.Bar)) { return new Morris.Bar(options); } Bar.__super__.constructor.call(this, $.extend({}, options, { parseTime: false })); } Bar.prototype.init = function() { this.cumulative = this.options.stacked; if (this.options.hideHover !== 'always') { this.hover = new Morris.Hover({ parent: this.el }); this.on('hovermove', this.onHoverMove); this.on('hoverout', this.onHoverOut); return this.on('gridclick', this.onGridClick); } }; Bar.prototype.defaults = { barSizeRatio: 0.75, barGap: 3, barColors: ['#0b62a4', '#7a92a3', '#4da74d', '#afd8f8', '#edc240', '#cb4b4b', '#9440ed'], barOpacity: 1.0, barRadius: [0, 0, 0, 0], xLabelMargin: 50 }; Bar.prototype.calc = function() { var _ref; this.calcBars(); if (this.options.hideHover === false) { return (_ref = this.hover).update.apply(_ref, this.hoverContentForRow(this.data.length - 1)); } }; Bar.prototype.calcBars = function() { var idx, row, y, _i, _len, _ref, _results; _ref = this.data; _results = []; for (idx = _i = 0, _len = _ref.length; _i < _len; idx = ++_i) { row = _ref[idx]; row._x = this.left + this.width * (idx + 0.5) / this.data.length; _results.push(row._y = (function() { var _j, _len1, _ref1, _results1; _ref1 = row.y; _results1 = []; for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { y = _ref1[_j]; if (y != null) { _results1.push(this.transY(y)); } else { _results1.push(null); } } return _results1; }).call(this)); } return _results; }; Bar.prototype.draw = function() { var _ref; if ((_ref = this.options.axes) === true || _ref === 'both' || _ref === 'x') { this.drawXAxis(); } return this.drawSeries(); }; Bar.prototype.drawXAxis = function() { var i, label, labelBox, margin, offset, prevAngleMargin, prevLabelMargin, row, textBox, ypos, _i, _ref, _results; ypos = this.bottom + (this.options.xAxisLabelTopPadding || this.options.padding / 2); prevLabelMargin = null; prevAngleMargin = null; _results = []; for (i = _i = 0, _ref = this.data.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { row = this.data[this.data.length - 1 - i]; label = this.drawXAxisLabel(row._x, ypos, row.label); textBox = label.getBBox(); label.transform("r" + (-this.options.xLabelAngle)); labelBox = label.getBBox(); label.transform("t0," + (labelBox.height / 2) + "..."); if (this.options.xLabelAngle !== 0) { offset = -0.5 * textBox.width * Math.cos(this.options.xLabelAngle * Math.PI / 180.0); label.transform("t" + offset + ",0..."); } if (((prevLabelMargin == null) || prevLabelMargin >= labelBox.x + labelBox.width || (prevAngleMargin != null) && prevAngleMargin >= labelBox.x) && labelBox.x >= 0 && (labelBox.x + labelBox.width) < this.el.width()) { if (this.options.xLabelAngle !== 0) { margin = 1.25 * this.options.gridTextSize / Math.sin(this.options.xLabelAngle * Math.PI / 180.0); prevAngleMargin = labelBox.x - margin; } _results.push(prevLabelMargin = labelBox.x - this.options.xLabelMargin); } else { _results.push(label.remove()); } } return _results; }; Bar.prototype.drawSeries = function() { var barWidth, bottom, groupWidth, idx, lastTop, left, leftPadding, numBars, row, sidx, size, spaceLeft, top, ypos, zeroPos; groupWidth = this.width / this.options.data.length; numBars = this.options.stacked ? 1 : this.options.ykeys.length; barWidth = (groupWidth * this.options.barSizeRatio - this.options.barGap * (numBars - 1)) / numBars; if (this.options.barSize) { barWidth = Math.min(barWidth, this.options.barSize); } spaceLeft = groupWidth - barWidth * numBars - this.options.barGap * (numBars - 1); leftPadding = spaceLeft / 2; zeroPos = this.ymin <= 0 && this.ymax >= 0 ? this.transY(0) : null; return this.bars = (function() { var _i, _len, _ref, _results; _ref = this.data; _results = []; for (idx = _i = 0, _len = _ref.length; _i < _len; idx = ++_i) { row = _ref[idx]; lastTop = 0; _results.push((function() { var _j, _len1, _ref1, _results1; _ref1 = row._y; _results1 = []; for (sidx = _j = 0, _len1 = _ref1.length; _j < _len1; sidx = ++_j) { ypos = _ref1[sidx]; if (ypos !== null) { if (zeroPos) { top = Math.min(ypos, zeroPos); bottom = Math.max(ypos, zeroPos); } else { top = ypos; bottom = this.bottom; } left = this.left + idx * groupWidth + leftPadding; if (!this.options.stacked) { left += sidx * (barWidth + this.options.barGap); } size = bottom - top; if (this.options.verticalGridCondition && this.options.verticalGridCondition(row.x)) { this.drawBar(this.left + idx * groupWidth, this.top, groupWidth, Math.abs(this.top - this.bottom), this.options.verticalGridColor, this.options.verticalGridOpacity, this.options.barRadius); } if (this.options.stacked) { top -= lastTop; } this.drawBar(left, top, barWidth, size, this.colorFor(row, sidx, 'bar'), this.options.barOpacity, this.options.barRadius); _results1.push(lastTop += size); } else { _results1.push(null); } } return _results1; }).call(this)); } return _results; }).call(this); }; Bar.prototype.colorFor = function(row, sidx, type) { var r, s; if (typeof this.options.barColors === 'function') { r = { x: row.x, y: row.y[sidx], label: row.label }; s = { index: sidx, key: this.options.ykeys[sidx], label: this.options.labels[sidx] }; return this.options.barColors.call(this, r, s, type); } else { return this.options.barColors[sidx % this.options.barColors.length]; } }; Bar.prototype.hitTest = function(x) { if (this.data.length === 0) { return null; } x = Math.max(Math.min(x, this.right), this.left); return Math.min(this.data.length - 1, Math.floor((x - this.left) / (this.width / this.data.length))); }; Bar.prototype.onGridClick = function(x, y) { var index; index = this.hitTest(x); return this.fire('click', index, this.data[index].src, x, y); }; Bar.prototype.onHoverMove = function(x, y) { var index, _ref; index = this.hitTest(x); return (_ref = this.hover).update.apply(_ref, this.hoverContentForRow(index)); }; Bar.prototype.onHoverOut = function() { if (this.options.hideHover !== false) { return this.hover.hide(); } }; Bar.prototype.hoverContentForRow = function(index) { var content, j, row, x, y, _i, _len, _ref; row = this.data[index]; content = "<div class='morris-hover-row-label'>" + row.label + "</div>"; _ref = row.y; for (j = _i = 0, _len = _ref.length; _i < _len; j = ++_i) { y = _ref[j]; content += "<div class='morris-hover-point' style='color: " + (this.colorFor(row, j, 'label')) + "'>\n " + this.options.labels[j] + ":\n " + (this.yLabelFormat(y)) + "\n</div>"; } if (typeof this.options.hoverCallback === 'function') { content = this.options.hoverCallback(index, this.options, content, row.src); } x = this.left + (index + 0.5) * this.width / this.data.length; return [content, x]; }; Bar.prototype.drawXAxisLabel = function(xPos, yPos, text) { var label; return label = this.raphael.text(xPos, yPos, text).attr('font-size', this.options.gridTextSize).attr('font-family', this.options.gridTextFamily).attr('font-weight', this.options.gridTextWeight).attr('fill', this.options.gridTextColor); }; Bar.prototype.drawBar = function(xPos, yPos, width, height, barColor, opacity, radiusArray) { var maxRadius, path; maxRadius = Math.max.apply(Math, radiusArray); if (maxRadius === 0 || maxRadius > height) { path = this.raphael.rect(xPos, yPos, width, height); } else { path = this.raphael.path(this.roundedRect(xPos, yPos, width, height, radiusArray)); } return path.attr('fill', barColor).attr('fill-opacity', opacity).attr('stroke', 'none'); }; Bar.prototype.roundedRect = function(x, y, w, h, r) { if (r == null) { r = [0, 0, 0, 0]; } return ["M", x, r[0] + y, "Q", x, y, x + r[0], y, "L", x + w - r[1], y, "Q", x + w, y, x + w, y + r[1], "L", x + w, y + h - r[2], "Q", x + w, y + h, x + w - r[2], y + h, "L", x + r[3], y + h, "Q", x, y + h, x, y + h - r[3], "Z"]; }; return Bar; })(Morris.Grid); Morris.Donut = (function(_super) { __extends(Donut, _super); Donut.prototype.defaults = { colors: ['#0B62A4', '#3980B5', '#679DC6', '#95BBD7', '#B0CCE1', '#095791', '#095085', '#083E67', '#052C48', '#042135'], backgroundColor: '#FFFFFF', labelColor: '#000000', formatter: Morris.commas, resize: false }; function Donut(options) { this.resizeHandler = __bind(this.resizeHandler, this); this.select = __bind(this.select, this); this.click = __bind(this.click, this); var _this = this; if (!(this instanceof Morris.Donut)) { return new Morris.Donut(options); } this.options = $.extend({}, this.defaults, options); if (typeof options.element === 'string') { this.el = $(document.getElementById(options.element)); } else { this.el = $(options.element); } if (this.el === null || this.el.length === 0) { throw new Error("Graph placeholder not found."); } if (options.data === void 0 || options.data.length === 0) { return; } this.raphael = new Raphael(this.el[0]); if (this.options.resize) { $(window).bind('resize', function(evt) { if (_this.timeoutId != null) { window.clearTimeout(_this.timeoutId); } return _this.timeoutId = window.setTimeout(_this.resizeHandler, 100); }); } this.setData(options.data); } Donut.prototype.redraw = function() { var C, cx, cy, i, idx, last, max_value, min, next, seg, total, value, w, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _results; this.raphael.clear(); cx = this.el.width() / 2; cy = this.el.height() / 2; w = (Math.min(cx, cy) - 10) / 3; total = 0; _ref = this.values; for (_i = 0, _len = _ref.length; _i < _len; _i++) { value = _ref[_i]; total += value; } min = 5 / (2 * w); C = 1.9999 * Math.PI - min * this.data.length; last = 0; idx = 0; this.segments = []; _ref1 = this.values; for (i = _j = 0, _len1 = _ref1.length; _j < _len1; i = ++_j) { value = _ref1[i]; next = last + min + C * (value / total); seg = new Morris.DonutSegment(cx, cy, w * 2, w, last, next, this.data[i].color || this.options.colors[idx % this.options.colors.length], this.options.backgroundColor, idx, this.raphael); seg.render(); this.segments.push(seg); seg.on('hover', this.select); seg.on('click', this.click); last = next; idx += 1; } this.text1 = this.drawEmptyDonutLabel(cx, cy - 10, this.options.labelColor, 15, 800); this.text2 = this.drawEmptyDonutLabel(cx, cy + 10, this.options.labelColor, 14); max_value = Math.max.apply(Math, this.values); idx = 0; _ref2 = this.values; _results = []; for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { value = _ref2[_k]; if (value === max_value) { this.select(idx); break; } _results.push(idx += 1); } return _results; }; Donut.prototype.setData = function(data) { var row; this.data = data; this.values = (function() { var _i, _len, _ref, _results; _ref = this.data; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { row = _ref[_i]; _results.push(parseFloat(row.value)); } return _results; }).call(this); return this.redraw(); }; Donut.prototype.click = function(idx) { return this.fire('click', idx, this.data[idx]); }; Donut.prototype.select = function(idx) { var row, s, segment, _i, _len, _ref; _ref = this.segments; for (_i = 0, _len = _ref.length; _i < _len; _i++) { s = _ref[_i]; s.deselect(); } segment = this.segments[idx]; segment.select(); row = this.data[idx]; return this.setLabels(row.label, this.options.formatter(row.value, row)); }; Donut.prototype.setLabels = function(label1, label2) { var inner, maxHeightBottom, maxHeightTop, maxWidth, text1bbox, text1scale, text2bbox, text2scale; inner = (Math.min(this.el.width() / 2, this.el.height() / 2) - 10) * 2 / 3; maxWidth = 1.8 * inner; maxHeightTop = inner / 2; maxHeightBottom = inner / 3; this.text1.attr({ text: label1, transform: '' }); text1bbox = this.text1.getBBox(); text1scale = Math.min(maxWidth / text1bbox.width, maxHeightTop / text1bbox.height); this.text1.attr({ transform: "S" + text1scale + "," + text1scale + "," + (text1bbox.x + text1bbox.width / 2) + "," + (text1bbox.y + text1bbox.height) }); this.text2.attr({ text: label2, transform: '' }); text2bbox = this.text2.getBBox(); text2scale = Math.min(maxWidth / text2bbox.width, maxHeightBottom / text2bbox.height); return this.text2.attr({ transform: "S" + text2scale + "," + text2scale + "," + (text2bbox.x + text2bbox.width / 2) + "," + text2bbox.y }); }; Donut.prototype.drawEmptyDonutLabel = function(xPos, yPos, color, fontSize, fontWeight) { var text; text = this.raphael.text(xPos, yPos, '').attr('font-size', fontSize).attr('fill', color); if (fontWeight != null) { text.attr('font-weight', fontWeight); } return text; }; Donut.prototype.resizeHandler = function() { this.timeoutId = null; this.raphael.setSize(this.el.width(), this.el.height()); return this.redraw(); }; return Donut; })(Morris.EventEmitter); Morris.DonutSegment = (function(_super) { __extends(DonutSegment, _super); function DonutSegment(cx, cy, inner, outer, p0, p1, color, backgroundColor, index, raphael) { this.cx = cx; this.cy = cy; this.inner = inner; this.outer = outer; this.color = color; this.backgroundColor = backgroundColor; this.index = index; this.raphael = raphael; this.deselect = __bind(this.deselect, this); this.select = __bind(this.select, this); this.sin_p0 = Math.sin(p0); this.cos_p0 = Math.cos(p0); this.sin_p1 = Math.sin(p1); this.cos_p1 = Math.cos(p1); this.is_long = (p1 - p0) > Math.PI ? 1 : 0; this.path = this.calcSegment(this.inner + 3, this.inner + this.outer - 5); this.selectedPath = this.calcSegment(this.inner + 3, this.inner + this.outer); this.hilight = this.calcArc(this.inner); } DonutSegment.prototype.calcArcPoints = function(r) { return [this.cx + r * this.sin_p0, this.cy + r * this.cos_p0, this.cx + r * this.sin_p1, this.cy + r * this.cos_p1]; }; DonutSegment.prototype.calcSegment = function(r1, r2) { var ix0, ix1, iy0, iy1, ox0, ox1, oy0, oy1, _ref, _ref1; _ref = this.calcArcPoints(r1), ix0 = _ref[0], iy0 = _ref[1], ix1 = _ref[2], iy1 = _ref[3]; _ref1 = this.calcArcPoints(r2), ox0 = _ref1[0], oy0 = _ref1[1], ox1 = _ref1[2], oy1 = _ref1[3]; return ("M" + ix0 + "," + iy0) + ("A" + r1 + "," + r1 + ",0," + this.is_long + ",0," + ix1 + "," + iy1) + ("L" + ox1 + "," + oy1) + ("A" + r2 + "," + r2 + ",0," + this.is_long + ",1," + ox0 + "," + oy0) + "Z"; }; DonutSegment.prototype.calcArc = function(r) { var ix0, ix1, iy0, iy1, _ref; _ref = this.calcArcPoints(r), ix0 = _ref[0], iy0 = _ref[1], ix1 = _ref[2], iy1 = _ref[3]; return ("M" + ix0 + "," + iy0) + ("A" + r + "," + r + ",0," + this.is_long + ",0," + ix1 + "," + iy1); }; DonutSegment.prototype.render = function() { var _this = this; this.arc = this.drawDonutArc(this.hilight, this.color); return this.seg = this.drawDonutSegment(this.path, this.color, this.backgroundColor, function() { return _this.fire('hover', _this.index); }, function() { return _this.fire('click', _this.index); }); }; DonutSegment.prototype.drawDonutArc = function(path, color) { return this.raphael.path(path).attr({ stroke: color, 'stroke-width': 2, opacity: 0 }); }; DonutSegment.prototype.drawDonutSegment = function(path, fillColor, strokeColor, hoverFunction, clickFunction) { return this.raphael.path(path).attr({ fill: fillColor, stroke: strokeColor, 'stroke-width': 3 }).hover(hoverFunction).click(clickFunction); }; DonutSegment.prototype.select = function() { if (!this.selected) { this.seg.animate({ path: this.selectedPath }, 150, '<>'); this.arc.animate({ opacity: 1 }, 150, '<>'); return this.selected = true; } }; DonutSegment.prototype.deselect = function() { if (this.selected) { this.seg.animate({ path: this.path }, 150, '<>'); this.arc.animate({ opacity: 0 }, 150, '<>'); return this.selected = false; } }; return DonutSegment; })(Morris.EventEmitter); }).call(this); PK ɫ�ZEY��F F morris/morris.cssnu �[��� /* Morris charts */ .morris-hover { position: absolute; z-index: 1000; } .morris-hover.morris-default-style { border-radius: 10px; padding: 6px; color: #666; background: rgba(255, 255, 255, 0.8); border: solid 2px rgba(230, 230, 230, 0.8); font-family: sans-serif; font-size: 12px; text-align: center; } .morris-hover.morris-default-style .morris-hover-row-label { font-weight: bold; margin: 0.25em 0; } .morris-hover.morris-default-style .morris-hover-point { white-space: nowrap; margin: 0.1em 0; } PK ɫ�ZCw�� � morris/morris-demo.jsnu �[��� /* Morris color bar */ $(function() { "use strict"; Morris.Bar({ element: 'color-bar', data: [{ x: '2011 Q1', y: 0 }, { x: '2011 Q2', y: 1 }, { x: '2011 Q3', y: 2 }, { x: '2011 Q4', y: 3 }, { x: '2012 Q1', y: 4 }, { x: '2012 Q2', y: 5 }, { x: '2012 Q3', y: 6 }, { x: '2012 Q4', y: 7 }, { x: '2013 Q1', y: 8 }], xkey: 'x', ykeys: ['y'], labels: ['Y'], barColors: function(row, series, type) { if (type === 'bar') { var red = Math.ceil(255 * row.y / this.ymax); return 'rgb(' + red + ',155,22)'; } else { return '#000'; } } }); }); /* Morris labels bar */ $(function() { "use strict"; var day_data = [{ "period": "2012-10-01", "licensed": 3407, "sorned": 660 }, { "period": "2012-09-30", "licensed": 3351, "sorned": 629 }, { "period": "2012-09-29", "licensed": 3269, "sorned": 618 }, { "period": "2012-09-20", "licensed": 3246, "sorned": 661 }, { "period": "2012-09-19", "licensed": 3257, "sorned": 667 }, { "period": "2012-09-18", "licensed": 3248, "sorned": 627 }, { "period": "2012-09-17", "licensed": 3171, "sorned": 660 }, { "period": "2012-09-16", "licensed": 3171, "sorned": 676 }, { "period": "2012-09-15", "licensed": 3201, "sorned": 656 }, { "period": "2012-09-10", "licensed": 3215, "sorned": 622 }]; Morris.Bar({ element: 'labels-bar', data: day_data, xkey: 'period', ykeys: ['licensed', 'sorned'], labels: ['Licensed', 'SORN'], xLabelAngle: 60 }); }); /* Morris stacked bars */ $(function() { "use strict"; Morris.Bar({ element: 'stacked-bars', data: [{ x: '2011 Q1', y: 3, z: 2, a: 3 }, { x: '2011 Q2', y: 2, z: null, a: 1 }, { x: '2011 Q3', y: 0, z: 2, a: 4 }, { x: '2011 Q4', y: 2, z: 4, a: 3 }], xkey: 'x', ykeys: ['y', 'z', 'a'], labels: ['Y', 'Z', 'A'], stacked: true }); }); /* Morris donut */ $(function() { "use strict"; Morris.Donut({ element: 'donut', backgroundColor: '#fff', labelColor: '#ccc', colors: [ '#4fb2ff', '#929292', '#67C69D', '#ff9393' ], data: [{ value: 70, label: 'foo', formatted: 'at least 70%' }, { value: 15, label: 'bar', formatted: 'approx. 15%' }, { value: 10, label: 'baz', formatted: 'approx. 10%' }, { value: 5, label: 'A really really long label', formatted: 'at most 5%' }], formatter: function(x, data) { return data.formatted; } }); }); /* Morris decimal data */ $(function() { "use strict"; var decimal_data = []; for (var x = 0; x <= 360; x += 10) { decimal_data.push({ x: x, y: 1.5 + 1.5 * Math.sin(Math.PI * x / 180).toFixed(4) }); } window.m = Morris.Line({ element: 'decimal-data', data: decimal_data, xkey: 'x', ykeys: ['y'], labels: ['sin(x)'], parseTime: false, hoverCallback: function(index, options, default_content) { var row = options.data[index]; return default_content.replace("sin(x)", "1.5 + 1.5 sin(" + row.x + ")"); }, xLabelMargin: 10, integerYLabels: true }); }); /* Morris daytime */ $(function() { "use strict"; Morris.Area({ element: 'daytime-bars', data: [{ x: '2013-03-30 22:00:00', y: 3, z: 3 }, { x: '2013-03-31 00:00:00', y: 2, z: 0 }, { x: '2013-03-31 02:00:00', y: 0, z: 2 }, { x: '2013-03-31 04:00:00', y: 4, z: 4 }], xkey: 'x', ykeys: ['y', 'z'], labels: ['Y', 'Z'] }); }); /* Author: */ $(function() { // data stolen from http://howmanyleft.co.uk/vehicle/jaguar_'e'_type var tax_data = [{ "period": "2011 Q3", "licensed": 3407, "sorned": 660 }, { "period": "2011 Q2", "licensed": 3351, "sorned": 629 }, { "period": "2011 Q1", "licensed": 3269, "sorned": 618 }, { "period": "2010 Q4", "licensed": 3246, "sorned": 661 }, { "period": "2009 Q4", "licensed": 3171, "sorned": 676 }, { "period": "2008 Q4", "licensed": 3155, "sorned": 681 }, { "period": "2007 Q4", "licensed": 3226, "sorned": 620 }, { "period": "2006 Q4", "licensed": 3245, "sorned": null }, { "period": "2005 Q4", "licensed": 3289, "sorned": null }]; Morris.Line({ element: 'hero-graph', data: tax_data, xkey: 'period', ykeys: ['licensed', 'sorned'], labels: ['Licensed', 'Off the road'] }); Morris.Donut({ element: 'hero-donut', data: [{ label: 'Jam', value: 25 }, { label: 'Frosted', value: 40 }, { label: 'Custard', value: 25 }, { label: 'Sugar', value: 10 }], formatter: function(y) { return y + "%" } }); Morris.Area({ element: 'hero-area', data: [{ period: '2010 Q1', iphone: 2666, ipad: null, itouch: 2647 }, { period: '2010 Q2', iphone: 2778, ipad: 2294, itouch: 2441 }, { period: '2010 Q3', iphone: 4912, ipad: 1969, itouch: 2501 }, { period: '2010 Q4', iphone: 3767, ipad: 3597, itouch: 5689 }, { period: '2011 Q1', iphone: 6810, ipad: 1914, itouch: 2293 }, { period: '2011 Q2', iphone: 5670, ipad: 4293, itouch: 1881 }, { period: '2011 Q3', iphone: 4820, ipad: 3795, itouch: 1588 }, { period: '2011 Q4', iphone: 15073, ipad: 5967, itouch: 5175 }, { period: '2012 Q1', iphone: 10687, ipad: 4460, itouch: 2028 }, { period: '2012 Q2', iphone: 8432, ipad: 5713, itouch: 1791 }], xkey: 'period', ykeys: ['iphone', 'ipad', 'itouch'], labels: ['iPhone', 'iPad', 'iPod Touch'], pointSize: 2, hideHover: 'auto' }); Morris.Bar({ element: 'hero-bar', data: [{ device: 'iPhone', geekbench: 136 }, { device: 'iPhone 3G', geekbench: 137 }, { device: 'iPhone 3GS', geekbench: 275 }, { device: 'iPhone 4', geekbench: 380 }, { device: 'iPhone 4S', geekbench: 655 }, { device: 'iPhone 5', geekbench: 1571 }], xkey: 'device', ykeys: ['geekbench'], labels: ['Geekbench'], barRatio: 0.4, xLabelAngle: 35, hideHover: 'auto' }); }); PK ɫ�Z��N N sparklines/sparklines-demo.jsnu �[��� /* Sparklines charts */ $(function() { "use strict"; $('.sparkbar').sparkline('html', { type: 'bar', disableHiddenCheck: false, width: '36px', height: '36px' }); }); /* Sparklines */ $(function() { "use strict"; $('.bar-sparkline-btn').sparkline([ [3, 5], [4, 7], [2, 5], [3, 5], [4, 7], [4, 7], [5, 7], [2, 7], [3, 5] ], { type: 'bar', height: '53px', barWidth: '5px', barSpacing: '2px' }); }); $(function() { "use strict"; $('.bar-sparkline-btn-2').sparkline([ [3, 5], [4, 7], [2, 5], [3, 5], [4, 7], [4, 7], [5, 7], [2, 7], [3, 5] ], { type: 'bar', height: '40px', barWidth: '3px', barSpacing: '2px' }); }); $(function() { "use strict"; $('.bar-sparkline').sparkline([ [4, 8], [2, 7], [2, 6], [2, 7], [3, 5], [2, 7], [2, 6], [2, 7], [3, 5], [4, 7], [2, 5], [3, 5], [4, 7], [4, 7], [5, 7], [4, 8], [2, 7], [2, 6], [2, 7], [3, 5] ], { type: 'bar', height: '35px', barWidth: '5px', barSpacing: '2px' }); }); $(function() { "use strict"; $('.bar-sparkline-2').sparkline('html', { type: 'bar', barColor: 'black', height: '35px', barWidth: '5px', barSpacing: '2px' }); }); $(function() { "use strict"; $('.tristate-sparkline').sparkline('html', { type: 'tristate', barColor: 'black', height: '35px', barWidth: '5px', barSpacing: '2px' }); }); $(function() { "use strict"; $('.discrete-sparkline').sparkline('html', { type: 'discrete', barColor: 'black', height: '45px', barSpacing: '4px' }); }); $(function() { "use strict"; $('.pie-sparkline').sparkline('html', { type: 'pie', barColor: 'black', height: '45px', width: '45px' }); }); $(function() { "use strict"; $(".pie-sparkline-alt").sparkline('html', { type: 'pie', width: '100', height: '100', sliceColors: ['#EFEFEF', '#5BCCF6', '#FA7753'], borderWidth: 0 }); }); $(function() { "use strict"; var myvalues = [10, 8, 5, 7, 4, 4, 1]; $('.dynamic-sparkline').sparkline(myvalues, { height: '35px', width: '135px' }); }); $(function() { "use strict"; var myvalues = [10, 8, 5, 7, 4, 4, 1]; $('.dynamic-sparkline-5').sparkline(myvalues, { height: '57px', width: '100px' }); }); $(function() { "use strict"; $('.tristate-sparkline-2').sparkline('html', { type: 'tristate', posBarColor: '#ec6a00', negBarColor: '#ffc98a', zeroBarColor: '#000000', height: '35px', barWidth: '5px', barSpacing: '2px' }); }); $(function() { "use strict"; $(".infobox-sparkline").sparkline([ [3, 5], [4, 7], [2, 5], [3, 5], [4, 7], [4, 7], [5, 7], [2, 7], [3, 5] ], { type: 'bar', height: '53', barWidth: 5, barSpacing: 2, zeroAxis: false, barColor: '#ccc', negBarColor: '#ddd', zeroColor: '#ccc', stackedBarColor: ['#871010', '#ffebeb'] }); }); $(function() { "use strict"; $(".infobox-sparkline-2").sparkline([ [3, 5], [4, 7], [2, 5], [3, 5], [4, 7], [4, 7], [5, 7], [2, 7], [3, 5] ], { type: 'bar', height: '53', barWidth: 5, barSpacing: 2, zeroAxis: false, barColor: '#ccc', negBarColor: '#ddd', zeroColor: '#ccc', stackedBarColor: ['#000000', '#cccccc'] }); }); $(function() { "use strict"; $(".infobox-sparkline-pie").sparkline([1.5, 2.5, 2], { type: 'pie', width: '57', height: '57', sliceColors: ['#0d4f26', '#00712b', '#2eee76'], offset: 0, borderWidth: 0, borderColor: '#000000' }); }); $(function() { "use strict"; $(".infobox-sparkline-tri").sparkline([1, 1, 0, 1, -1, -1, 1, -1, 0, 0, 2, 1], { type: 'tristate', height: '53', posBarColor: '#1bb1fc', negBarColor: '#3d57ed', zeroBarColor: '#000000', barWidth: 5 }); }); $(function() { "use strict"; $(".sprk-1").sparkline('html', { type: 'line', width: '50%', height: '65', lineColor: '#b2b2b2', fillColor: '#ffffff', lineWidth: 1, spotColor: '#0065ff', minSpotColor: '#0065ff', maxSpotColor: '#0065ff', spotRadius: 4 }); }); $(function() { "use strict"; $(".sparkline-big").sparkline('html', { type: 'line', width: '85%', height: '80', highlightLineColor: '#ffffff', lineColor: '#ffffff', fillColor: 'transparent', lineWidth: 1, spotColor: '#ffffff', minSpotColor: '#ffffff', maxSpotColor: '#ffffff', highlightSpotColor: '#000000', spotRadius: 4 }); }); $(function() { "use strict"; $(".sparkline-big-alt").sparkline('html', { type: 'line', width: '90%', height: '110', highlightLineColor: '#accfff', lineColor: 'rgba(0,0,0,0.1)', fillColor: '#fcfeff', lineWidth: 1, spotColor: 'transparent', minSpotColor: 'transparent', maxSpotColor: 'transparent', highlightSpotColor: '#65a6ff', spotRadius: 6 }); }); $(function() { "use strict"; $(".sparkline-bar-big").sparkline('html', { type: 'bar', width: '85%', height: '90', barWidth: 6, barSpacing: 2, zeroAxis: false, barColor: '#ffffff', negBarColor: '#ffffff' }); }); $(function() { "use strict"; $(".sparkline-bar-big-color").sparkline('html', { type: 'bar', height: '90', width: '85%', barWidth: 6, barSpacing: 2, zeroAxis: false, barColor: '#9CD159', negBarColor: '#9CD159' }); }); $(function() { "use strict"; $(".sparkline-bar-big-color-2").sparkline([405, 450, 302, 405, 230, 311, 405, 342, 579, 405, 450, 302, 183, 579, 180, 311, 405, 342, 579, 405, 450, 302, 405, 230, 311, 405, 342, 579, 405, 450, 302, 405, 342, 432, 405, 450, 302, 183, 579, 180, 311, 405, 342, 579, 183, 579, 180, 311, 405, 342, 579, 405, 450, 302, 405, 230, 311, 405, 342, 579, 405, 450, 302, 405, 342, 432, 405, 450, 302, 183, 579, 180, 311, 405, 342, 579, 240, 180, 311, 450, 302, 370, 210], { type: 'bar', height: '88', width: '85%', barWidth: 6, barSpacing: 2, zeroAxis: false, barColor: '#9CD159', negBarColor: '#9CD159' }); }); PK ɫ�Zވ7w_ _ sparklines/sparklines.jsnu �[��� /** * * jquery.sparkline.js * * v2.1.2 * (c) Splunk, Inc * Contact: Gareth Watts (gareth@splunk.com) * http://omnipotent.net/jquery.sparkline/ * * Generates inline sparkline charts from data supplied either to the method * or inline in HTML * * Compatible with Internet Explorer 6.0+ and modern browsers equipped with the canvas tag * (Firefox 2.0+, Safari, Opera, etc) * * License: New BSD License * * Copyright (c) 2012, Splunk Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Splunk Inc nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * Usage: * $(selector).sparkline(values, options) * * If values is undefined or set to 'html' then the data values are read from the specified tag: * <p>Sparkline: <span class="sparkline">1,4,6,6,8,5,3,5</span></p> * $('.sparkline').sparkline(); * There must be no spaces in the enclosed data set * * Otherwise values must be an array of numbers or null values * <p>Sparkline: <span id="sparkline1">This text replaced if the browser is compatible</span></p> * $('#sparkline1').sparkline([1,4,6,6,8,5,3,5]) * $('#sparkline2').sparkline([1,4,6,null,null,5,3,5]) * * Values can also be specified in an HTML comment, or as a values attribute: * <p>Sparkline: <span class="sparkline"><!--1,4,6,6,8,5,3,5 --></span></p> * <p>Sparkline: <span class="sparkline" values="1,4,6,6,8,5,3,5"></span></p> * $('.sparkline').sparkline(); * * For line charts, x values can also be specified: * <p>Sparkline: <span class="sparkline">1:1,2.7:4,3.4:6,5:6,6:8,8.7:5,9:3,10:5</span></p> * $('#sparkline1').sparkline([ [1,1], [2.7,4], [3.4,6], [5,6], [6,8], [8.7,5], [9,3], [10,5] ]) * * By default, options should be passed in as teh second argument to the sparkline function: * $('.sparkline').sparkline([1,2,3,4], {type: 'bar'}) * * Options can also be set by passing them on the tag itself. This feature is disabled by default though * as there's a slight performance overhead: * $('.sparkline').sparkline([1,2,3,4], {enableTagOptions: true}) * <p>Sparkline: <span class="sparkline" sparkType="bar" sparkBarColor="red">loading</span></p> * Prefix all options supplied as tag attribute with "spark" (configurable by setting tagOptionPrefix) * * Supported options: * lineColor - Color of the line used for the chart * fillColor - Color used to fill in the chart - Set to '' or false for a transparent chart * width - Width of the chart - Defaults to 3 times the number of values in pixels * height - Height of the chart - Defaults to the height of the containing element * chartRangeMin - Specify the minimum value to use for the Y range of the chart - Defaults to the minimum value supplied * chartRangeMax - Specify the maximum value to use for the Y range of the chart - Defaults to the maximum value supplied * chartRangeClip - Clip out of range values to the max/min specified by chartRangeMin and chartRangeMax * chartRangeMinX - Specify the minimum value to use for the X range of the chart - Defaults to the minimum value supplied * chartRangeMaxX - Specify the maximum value to use for the X range of the chart - Defaults to the maximum value supplied * composite - If true then don't erase any existing chart attached to the tag, but draw * another chart over the top - Note that width and height are ignored if an * existing chart is detected. * tagValuesAttribute - Name of tag attribute to check for data values - Defaults to 'values' * enableTagOptions - Whether to check tags for sparkline options * tagOptionPrefix - Prefix used for options supplied as tag attributes - Defaults to 'spark' * disableHiddenCheck - If set to true, then the plugin will assume that charts will never be drawn into a * hidden dom element, avoding a browser reflow * disableInteraction - If set to true then all mouseover/click interaction behaviour will be disabled, * making the plugin perform much like it did in 1.x * disableTooltips - If set to true then tooltips will be disabled - Defaults to false (tooltips enabled) * disableHighlight - If set to true then highlighting of selected chart elements on mouseover will be disabled * defaults to false (highlights enabled) * highlightLighten - Factor to lighten/darken highlighted chart values by - Defaults to 1.4 for a 40% increase * tooltipContainer - Specify which DOM element the tooltip should be rendered into - defaults to document.body * tooltipClassname - Optional CSS classname to apply to tooltips - If not specified then a default style will be applied * tooltipOffsetX - How many pixels away from the mouse pointer to render the tooltip on the X axis * tooltipOffsetY - How many pixels away from the mouse pointer to render the tooltip on the r axis * tooltipFormatter - Optional callback that allows you to override the HTML displayed in the tooltip * callback is given arguments of (sparkline, options, fields) * tooltipChartTitle - If specified then the tooltip uses the string specified by this setting as a title * tooltipFormat - A format string or SPFormat object (or an array thereof for multiple entries) * to control the format of the tooltip * tooltipPrefix - A string to prepend to each field displayed in a tooltip * tooltipSuffix - A string to append to each field displayed in a tooltip * tooltipSkipNull - If true then null values will not have a tooltip displayed (defaults to true) * tooltipValueLookups - An object or range map to map field values to tooltip strings * (eg. to map -1 to "Lost", 0 to "Draw", and 1 to "Win") * numberFormatter - Optional callback for formatting numbers in tooltips * numberDigitGroupSep - Character to use for group separator in numbers "1,234" - Defaults to "," * numberDecimalMark - Character to use for the decimal point when formatting numbers - Defaults to "." * numberDigitGroupCount - Number of digits between group separator - Defaults to 3 * * There are 7 types of sparkline, selected by supplying a "type" option of 'line' (default), * 'bar', 'tristate', 'bullet', 'discrete', 'pie' or 'box' * line - Line chart. Options: * spotColor - Set to '' to not end each line in a circular spot * minSpotColor - If set, color of spot at minimum value * maxSpotColor - If set, color of spot at maximum value * spotRadius - Radius in pixels * lineWidth - Width of line in pixels * normalRangeMin * normalRangeMax - If set draws a filled horizontal bar between these two values marking the "normal" * or expected range of values * normalRangeColor - Color to use for the above bar * drawNormalOnTop - Draw the normal range above the chart fill color if true * defaultPixelsPerValue - Defaults to 3 pixels of width for each value in the chart * highlightSpotColor - The color to use for drawing a highlight spot on mouseover - Set to null to disable * highlightLineColor - The color to use for drawing a highlight line on mouseover - Set to null to disable * valueSpots - Specify which points to draw spots on, and in which color. Accepts a range map * * bar - Bar chart. Options: * barColor - Color of bars for postive values * negBarColor - Color of bars for negative values * zeroColor - Color of bars with zero values * nullColor - Color of bars with null values - Defaults to omitting the bar entirely * barWidth - Width of bars in pixels * colorMap - Optional mappnig of values to colors to override the *BarColor values above * can be an Array of values to control the color of individual bars or a range map * to specify colors for individual ranges of values * barSpacing - Gap between bars in pixels * zeroAxis - Centers the y-axis around zero if true * * tristate - Charts values of win (>0), lose (<0) or draw (=0) * posBarColor - Color of win values * negBarColor - Color of lose values * zeroBarColor - Color of draw values * barWidth - Width of bars in pixels * barSpacing - Gap between bars in pixels * colorMap - Optional mappnig of values to colors to override the *BarColor values above * can be an Array of values to control the color of individual bars or a range map * to specify colors for individual ranges of values * * discrete - Options: * lineHeight - Height of each line in pixels - Defaults to 30% of the graph height * thesholdValue - Values less than this value will be drawn using thresholdColor instead of lineColor * thresholdColor * * bullet - Values for bullet graphs msut be in the order: target, performance, range1, range2, range3, ... * options: * targetColor - The color of the vertical target marker * targetWidth - The width of the target marker in pixels * performanceColor - The color of the performance measure horizontal bar * rangeColors - Colors to use for each qualitative range background color * * pie - Pie chart. Options: * sliceColors - An array of colors to use for pie slices * offset - Angle in degrees to offset the first slice - Try -90 or +90 * borderWidth - Width of border to draw around the pie chart, in pixels - Defaults to 0 (no border) * borderColor - Color to use for the pie chart border - Defaults to #000 * * box - Box plot. Options: * raw - Set to true to supply pre-computed plot points as values * values should be: low_outlier, low_whisker, q1, median, q3, high_whisker, high_outlier * When set to false you can supply any number of values and the box plot will * be computed for you. Default is false. * showOutliers - Set to true (default) to display outliers as circles * outlierIQR - Interquartile range used to determine outliers. Default 1.5 * boxLineColor - Outline color of the box * boxFillColor - Fill color for the box * whiskerColor - Line color used for whiskers * outlierLineColor - Outline color of outlier circles * outlierFillColor - Fill color of the outlier circles * spotRadius - Radius of outlier circles * medianColor - Line color of the median line * target - Draw a target cross hair at the supplied value (default undefined) * * * * Examples: * $('#sparkline1').sparkline(myvalues, { lineColor: '#f00', fillColor: false }); * $('.barsparks').sparkline('html', { type:'bar', height:'40px', barWidth:5 }); * $('#tristate').sparkline([1,1,-1,1,0,0,-1], { type:'tristate' }): * $('#discrete').sparkline([1,3,4,5,5,3,4,5], { type:'discrete' }); * $('#bullet').sparkline([10,12,12,9,7], { type:'bullet' }); * $('#pie').sparkline([1,1,2], { type:'pie' }); */ /*jslint regexp: true, browser: true, jquery: true, white: true, nomen: false, plusplus: false, maxerr: 500, indent: 4 */ (function(document, Math, undefined) { // performance/minified-size optimization (function(factory) { if(typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (jQuery && !jQuery.fn.sparkline) { factory(jQuery); } } (function($) { 'use strict'; var UNSET_OPTION = {}, getDefaults, createClass, SPFormat, clipval, quartile, normalizeValue, normalizeValues, remove, isNumber, all, sum, addCSS, ensureArray, formatNumber, RangeMap, MouseHandler, Tooltip, barHighlightMixin, line, bar, tristate, discrete, bullet, pie, box, defaultStyles, initStyles, VShape, VCanvas_base, VCanvas_canvas, VCanvas_vml, pending, shapeCount = 0; /** * Default configuration settings */ getDefaults = function () { return { // Settings common to most/all chart types common: { type: 'line', lineColor: '#00f', fillColor: '#cdf', defaultPixelsPerValue: 3, width: 'auto', height: 'auto', composite: false, tagValuesAttribute: 'values', tagOptionsPrefix: 'spark', enableTagOptions: false, enableHighlight: true, highlightLighten: 1.4, tooltipSkipNull: true, tooltipPrefix: '', tooltipSuffix: '', disableHiddenCheck: false, numberFormatter: false, numberDigitGroupCount: 3, numberDigitGroupSep: ',', numberDecimalMark: '.', disableTooltips: false, disableInteraction: false }, // Defaults for line charts line: { spotColor: '#f80', highlightSpotColor: '#5f5', highlightLineColor: '#f22', spotRadius: 1.5, minSpotColor: '#f80', maxSpotColor: '#f80', lineWidth: 1, normalRangeMin: undefined, normalRangeMax: undefined, normalRangeColor: '#ccc', drawNormalOnTop: false, chartRangeMin: undefined, chartRangeMax: undefined, chartRangeMinX: undefined, chartRangeMaxX: undefined, tooltipFormat: new SPFormat('<span style="color: {{color}}">●</span> {{prefix}}{{y}}{{suffix}}') }, // Defaults for bar charts bar: { barColor: '#3366cc', negBarColor: '#f44', stackedBarColor: ['#3366cc', '#dc3912', '#ff9900', '#109618', '#66aa00', '#dd4477', '#0099c6', '#990099'], zeroColor: undefined, nullColor: undefined, zeroAxis: true, barWidth: 4, barSpacing: 1, chartRangeMax: undefined, chartRangeMin: undefined, chartRangeClip: false, colorMap: undefined, tooltipFormat: new SPFormat('<span style="color: {{color}}">●</span> {{prefix}}{{value}}{{suffix}}') }, // Defaults for tristate charts tristate: { barWidth: 4, barSpacing: 1, posBarColor: '#6f6', negBarColor: '#f44', zeroBarColor: '#999', colorMap: {}, tooltipFormat: new SPFormat('<span style="color: {{color}}">●</span> {{value:map}}'), tooltipValueLookups: { map: { '-1': 'Loss', '0': 'Draw', '1': 'Win' } } }, // Defaults for discrete charts discrete: { lineHeight: 'auto', thresholdColor: undefined, thresholdValue: 0, chartRangeMax: undefined, chartRangeMin: undefined, chartRangeClip: false, tooltipFormat: new SPFormat('{{prefix}}{{value}}{{suffix}}') }, // Defaults for bullet charts bullet: { targetColor: '#f33', targetWidth: 3, // width of the target bar in pixels performanceColor: '#33f', rangeColors: ['#d3dafe', '#a8b6ff', '#7f94ff'], base: undefined, // set this to a number to change the base start number tooltipFormat: new SPFormat('{{fieldkey:fields}} - {{value}}'), tooltipValueLookups: { fields: {r: 'Range', p: 'Performance', t: 'Target'} } }, // Defaults for pie charts pie: { offset: 0, sliceColors: ['#3366cc', '#dc3912', '#ff9900', '#109618', '#66aa00', '#dd4477', '#0099c6', '#990099'], borderWidth: 0, borderColor: '#000', tooltipFormat: new SPFormat('<span style="color: {{color}}">●</span> {{value}} ({{percent.1}}%)') }, // Defaults for box plots box: { raw: false, boxLineColor: '#000', boxFillColor: '#cdf', whiskerColor: '#000', outlierLineColor: '#333', outlierFillColor: '#fff', medianColor: '#f00', showOutliers: true, outlierIQR: 1.5, spotRadius: 1.5, target: undefined, targetColor: '#4a2', chartRangeMax: undefined, chartRangeMin: undefined, tooltipFormat: new SPFormat('{{field:fields}}: {{value}}'), tooltipFormatFieldlistKey: 'field', tooltipValueLookups: { fields: { lq: 'Lower Quartile', med: 'Median', uq: 'Upper Quartile', lo: 'Left Outlier', ro: 'Right Outlier', lw: 'Left Whisker', rw: 'Right Whisker'} } } }; }; // You can have tooltips use a css class other than jqstooltip by specifying tooltipClassname defaultStyles = '.jqstooltip { ' + 'position: absolute;' + 'left: 0px;' + 'top: 0px;' + 'visibility: hidden;' + 'background: rgb(0, 0, 0) transparent;' + 'background-color: rgba(0,0,0,0.6);' + 'filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);' + '-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";' + 'color: white;' + 'font: 10px arial, san serif;' + 'text-align: left;' + 'white-space: nowrap;' + 'padding: 5px;' + 'border: 1px solid white;' + 'z-index: 10000;' + '}' + '.jqsfield { ' + 'color: white;' + 'font: 10px arial, san serif;' + 'text-align: left;' + '}'; /** * Utilities */ createClass = function (/* [baseclass, [mixin, ...]], definition */) { var Class, args; Class = function () { this.init.apply(this, arguments); }; if (arguments.length > 1) { if (arguments[0]) { Class.prototype = $.extend(new arguments[0](), arguments[arguments.length - 1]); Class._super = arguments[0].prototype; } else { Class.prototype = arguments[arguments.length - 1]; } if (arguments.length > 2) { args = Array.prototype.slice.call(arguments, 1, -1); args.unshift(Class.prototype); $.extend.apply($, args); } } else { Class.prototype = arguments[0]; } Class.prototype.cls = Class; return Class; }; /** * Wraps a format string for tooltips * {{x}} * {{x.2} * {{x:months}} */ $.SPFormatClass = SPFormat = createClass({ fre: /\{\{([\w.]+?)(:(.+?))?\}\}/g, precre: /(\w+)\.(\d+)/, init: function (format, fclass) { this.format = format; this.fclass = fclass; }, render: function (fieldset, lookups, options) { var self = this, fields = fieldset, match, token, lookupkey, fieldvalue, prec; return this.format.replace(this.fre, function () { var lookup; token = arguments[1]; lookupkey = arguments[3]; match = self.precre.exec(token); if (match) { prec = match[2]; token = match[1]; } else { prec = false; } fieldvalue = fields[token]; if (fieldvalue === undefined) { return ''; } if (lookupkey && lookups && lookups[lookupkey]) { lookup = lookups[lookupkey]; if (lookup.get) { // RangeMap return lookups[lookupkey].get(fieldvalue) || fieldvalue; } else { return lookups[lookupkey][fieldvalue] || fieldvalue; } } if (isNumber(fieldvalue)) { if (options.get('numberFormatter')) { fieldvalue = options.get('numberFormatter')(fieldvalue); } else { fieldvalue = formatNumber(fieldvalue, prec, options.get('numberDigitGroupCount'), options.get('numberDigitGroupSep'), options.get('numberDecimalMark')); } } return fieldvalue; }); } }); // convience method to avoid needing the new operator $.spformat = function(format, fclass) { return new SPFormat(format, fclass); }; clipval = function (val, min, max) { if (val < min) { return min; } if (val > max) { return max; } return val; }; quartile = function (values, q) { var vl; if (q === 2) { vl = Math.floor(values.length / 2); return values.length % 2 ? values[vl] : (values[vl-1] + values[vl]) / 2; } else { if (values.length % 2 ) { // odd vl = (values.length * q + q) / 4; return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1]; } else { //even vl = (values.length * q + 2) / 4; return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1]; } } }; normalizeValue = function (val) { var nf; switch (val) { case 'undefined': val = undefined; break; case 'null': val = null; break; case 'true': val = true; break; case 'false': val = false; break; default: nf = parseFloat(val); if (val == nf) { val = nf; } } return val; }; normalizeValues = function (vals) { var i, result = []; for (i = vals.length; i--;) { result[i] = normalizeValue(vals[i]); } return result; }; remove = function (vals, filter) { var i, vl, result = []; for (i = 0, vl = vals.length; i < vl; i++) { if (vals[i] !== filter) { result.push(vals[i]); } } return result; }; isNumber = function (num) { return !isNaN(parseFloat(num)) && isFinite(num); }; formatNumber = function (num, prec, groupsize, groupsep, decsep) { var p, i; num = (prec === false ? parseFloat(num).toString() : num.toFixed(prec)).split(''); p = (p = $.inArray('.', num)) < 0 ? num.length : p; if (p < num.length) { num[p] = decsep; } for (i = p - groupsize; i > 0; i -= groupsize) { num.splice(i, 0, groupsep); } return num.join(''); }; // determine if all values of an array match a value // returns true if the array is empty all = function (val, arr, ignoreNull) { var i; for (i = arr.length; i--; ) { if (ignoreNull && arr[i] === null) continue; if (arr[i] !== val) { return false; } } return true; }; // sums the numeric values in an array, ignoring other values sum = function (vals) { var total = 0, i; for (i = vals.length; i--;) { total += typeof vals[i] === 'number' ? vals[i] : 0; } return total; }; ensureArray = function (val) { return $.isArray(val) ? val : [val]; }; // http://paulirish.com/2008/bookmarklet-inject-new-css-rules/ addCSS = function(css) { var tag; //if ('\v' == 'v') /* ie only */ { if (document.createStyleSheet) { document.createStyleSheet().cssText = css; } else { tag = document.createElement('style'); tag.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(tag); tag[(typeof document.body.style.WebkitAppearance == 'string') /* webkit only */ ? 'innerText' : 'innerHTML'] = css; } }; // Provide a cross-browser interface to a few simple drawing primitives $.fn.simpledraw = function (width, height, useExisting, interact) { var target, mhandler; if (useExisting && (target = this.data('_jqs_vcanvas'))) { return target; } if ($.fn.sparkline.canvas === false) { // We've already determined that neither Canvas nor VML are available return false; } else if ($.fn.sparkline.canvas === undefined) { // No function defined yet -- need to see if we support Canvas or VML var el = document.createElement('canvas'); if (!!(el.getContext && el.getContext('2d'))) { // Canvas is available $.fn.sparkline.canvas = function(width, height, target, interact) { return new VCanvas_canvas(width, height, target, interact); }; } else if (document.namespaces && !document.namespaces.v) { // VML is available document.namespaces.add('v', 'urn:schemas-microsoft-com:vml', '#default#VML'); $.fn.sparkline.canvas = function(width, height, target, interact) { return new VCanvas_vml(width, height, target); }; } else { // Neither Canvas nor VML are available $.fn.sparkline.canvas = false; return false; } } if (width === undefined) { width = $(this).innerWidth(); } if (height === undefined) { height = $(this).innerHeight(); } target = $.fn.sparkline.canvas(width, height, this, interact); mhandler = $(this).data('_jqs_mhandler'); if (mhandler) { mhandler.registerCanvas(target); } return target; }; $.fn.cleardraw = function () { var target = this.data('_jqs_vcanvas'); if (target) { target.reset(); } }; $.RangeMapClass = RangeMap = createClass({ init: function (map) { var key, range, rangelist = []; for (key in map) { if (map.hasOwnProperty(key) && typeof key === 'string' && key.indexOf(':') > -1) { range = key.split(':'); range[0] = range[0].length === 0 ? -Infinity : parseFloat(range[0]); range[1] = range[1].length === 0 ? Infinity : parseFloat(range[1]); range[2] = map[key]; rangelist.push(range); } } this.map = map; this.rangelist = rangelist || false; }, get: function (value) { var rangelist = this.rangelist, i, range, result; if ((result = this.map[value]) !== undefined) { return result; } if (rangelist) { for (i = rangelist.length; i--;) { range = rangelist[i]; if (range[0] <= value && range[1] >= value) { return range[2]; } } } return undefined; } }); // Convenience function $.range_map = function(map) { return new RangeMap(map); }; MouseHandler = createClass({ init: function (el, options) { var $el = $(el); this.$el = $el; this.options = options; this.currentPageX = 0; this.currentPageY = 0; this.el = el; this.splist = []; this.tooltip = null; this.over = false; this.displayTooltips = !options.get('disableTooltips'); this.highlightEnabled = !options.get('disableHighlight'); }, registerSparkline: function (sp) { this.splist.push(sp); if (this.over) { this.updateDisplay(); } }, registerCanvas: function (canvas) { var $canvas = $(canvas.canvas); this.canvas = canvas; this.$canvas = $canvas; $canvas.mouseenter($.proxy(this.mouseenter, this)); $canvas.mouseleave($.proxy(this.mouseleave, this)); $canvas.click($.proxy(this.mouseclick, this)); }, reset: function (removeTooltip) { this.splist = []; if (this.tooltip && removeTooltip) { this.tooltip.remove(); this.tooltip = undefined; } }, mouseclick: function (e) { var clickEvent = $.Event('sparklineClick'); clickEvent.originalEvent = e; clickEvent.sparklines = this.splist; this.$el.trigger(clickEvent); }, mouseenter: function (e) { $(document.body).unbind('mousemove.jqs'); $(document.body).bind('mousemove.jqs', $.proxy(this.mousemove, this)); this.over = true; this.currentPageX = e.pageX; this.currentPageY = e.pageY; this.currentEl = e.target; if (!this.tooltip && this.displayTooltips) { this.tooltip = new Tooltip(this.options); this.tooltip.updatePosition(e.pageX, e.pageY); } this.updateDisplay(); }, mouseleave: function () { $(document.body).unbind('mousemove.jqs'); var splist = this.splist, spcount = splist.length, needsRefresh = false, sp, i; this.over = false; this.currentEl = null; if (this.tooltip) { this.tooltip.remove(); this.tooltip = null; } for (i = 0; i < spcount; i++) { sp = splist[i]; if (sp.clearRegionHighlight()) { needsRefresh = true; } } if (needsRefresh) { this.canvas.render(); } }, mousemove: function (e) { this.currentPageX = e.pageX; this.currentPageY = e.pageY; this.currentEl = e.target; if (this.tooltip) { this.tooltip.updatePosition(e.pageX, e.pageY); } this.updateDisplay(); }, updateDisplay: function () { var splist = this.splist, spcount = splist.length, needsRefresh = false, offset = this.$canvas.offset(), localX = this.currentPageX - offset.left, localY = this.currentPageY - offset.top, tooltiphtml, sp, i, result, changeEvent; if (!this.over) { return; } for (i = 0; i < spcount; i++) { sp = splist[i]; result = sp.setRegionHighlight(this.currentEl, localX, localY); if (result) { needsRefresh = true; } } if (needsRefresh) { changeEvent = $.Event('sparklineRegionChange'); changeEvent.sparklines = this.splist; this.$el.trigger(changeEvent); if (this.tooltip) { tooltiphtml = ''; for (i = 0; i < spcount; i++) { sp = splist[i]; tooltiphtml += sp.getCurrentRegionTooltip(); } this.tooltip.setContent(tooltiphtml); } if (!this.disableHighlight) { this.canvas.render(); } } if (result === null) { this.mouseleave(); } } }); Tooltip = createClass({ sizeStyle: 'position: static !important;' + 'display: block !important;' + 'visibility: hidden !important;' + 'float: left !important;', init: function (options) { var tooltipClassname = options.get('tooltipClassname', 'jqstooltip'), sizetipStyle = this.sizeStyle, offset; this.container = options.get('tooltipContainer') || document.body; this.tooltipOffsetX = options.get('tooltipOffsetX', 10); this.tooltipOffsetY = options.get('tooltipOffsetY', 12); // remove any previous lingering tooltip $('#jqssizetip').remove(); $('#jqstooltip').remove(); this.sizetip = $('<div/>', { id: 'jqssizetip', style: sizetipStyle, 'class': tooltipClassname }); this.tooltip = $('<div/>', { id: 'jqstooltip', 'class': tooltipClassname }).appendTo(this.container); // account for the container's location offset = this.tooltip.offset(); this.offsetLeft = offset.left; this.offsetTop = offset.top; this.hidden = true; $(window).unbind('resize.jqs scroll.jqs'); $(window).bind('resize.jqs scroll.jqs', $.proxy(this.updateWindowDims, this)); this.updateWindowDims(); }, updateWindowDims: function () { this.scrollTop = $(window).scrollTop(); this.scrollLeft = $(window).scrollLeft(); this.scrollRight = this.scrollLeft + $(window).width(); this.updatePosition(); }, getSize: function (content) { this.sizetip.html(content).appendTo(this.container); this.width = this.sizetip.width() + 1; this.height = this.sizetip.height(); this.sizetip.remove(); }, setContent: function (content) { if (!content) { this.tooltip.css('visibility', 'hidden'); this.hidden = true; return; } this.getSize(content); this.tooltip.html(content) .css({ 'width': this.width, 'height': this.height, 'visibility': 'visible' }); if (this.hidden) { this.hidden = false; this.updatePosition(); } }, updatePosition: function (x, y) { if (x === undefined) { if (this.mousex === undefined) { return; } x = this.mousex - this.offsetLeft; y = this.mousey - this.offsetTop; } else { this.mousex = x = x - this.offsetLeft; this.mousey = y = y - this.offsetTop; } if (!this.height || !this.width || this.hidden) { return; } y -= this.height + this.tooltipOffsetY; x += this.tooltipOffsetX; if (y < this.scrollTop) { y = this.scrollTop; } if (x < this.scrollLeft) { x = this.scrollLeft; } else if (x + this.width > this.scrollRight) { x = this.scrollRight - this.width; } this.tooltip.css({ 'left': x, 'top': y }); }, remove: function () { this.tooltip.remove(); this.sizetip.remove(); this.sizetip = this.tooltip = undefined; $(window).unbind('resize.jqs scroll.jqs'); } }); initStyles = function() { addCSS(defaultStyles); }; $(initStyles); pending = []; $.fn.sparkline = function (userValues, userOptions) { return this.each(function () { var options = new $.fn.sparkline.options(this, userOptions), $this = $(this), render, i; render = function () { var values, width, height, tmp, mhandler, sp, vals; if (userValues === 'html' || userValues === undefined) { vals = this.getAttribute(options.get('tagValuesAttribute')); if (vals === undefined || vals === null) { vals = $this.html(); } values = vals.replace(/(^\s*<!--)|(-->\s*$)|\s+/g, '').split(','); } else { values = userValues; } width = options.get('width') === 'auto' ? values.length * options.get('defaultPixelsPerValue') : options.get('width'); if (options.get('height') === 'auto') { if (!options.get('composite') || !$.data(this, '_jqs_vcanvas')) { // must be a better way to get the line height tmp = document.createElement('span'); tmp.innerHTML = 'a'; $this.html(tmp); height = $(tmp).innerHeight() || $(tmp).height(); $(tmp).remove(); tmp = null; } } else { height = options.get('height'); } if (!options.get('disableInteraction')) { mhandler = $.data(this, '_jqs_mhandler'); if (!mhandler) { mhandler = new MouseHandler(this, options); $.data(this, '_jqs_mhandler', mhandler); } else if (!options.get('composite')) { mhandler.reset(); } } else { mhandler = false; } if (options.get('composite') && !$.data(this, '_jqs_vcanvas')) { if (!$.data(this, '_jqs_errnotify')) { alert('Attempted to attach a composite sparkline to an element with no existing sparkline'); $.data(this, '_jqs_errnotify', true); } return; } sp = new $.fn.sparkline[options.get('type')](this, values, options, width, height); sp.render(); if (mhandler) { mhandler.registerSparkline(sp); } }; if (($(this).html() && !options.get('disableHiddenCheck') && $(this).is(':hidden')) || !$(this).parents('body').length) { if (!options.get('composite') && $.data(this, '_jqs_pending')) { // remove any existing references to the element for (i = pending.length; i; i--) { if (pending[i - 1][0] == this) { pending.splice(i - 1, 1); } } } pending.push([this, render]); $.data(this, '_jqs_pending', true); } else { render.call(this); } }); }; $.fn.sparkline.defaults = getDefaults(); $.sparkline_display_visible = function () { var el, i, pl; var done = []; for (i = 0, pl = pending.length; i < pl; i++) { el = pending[i][0]; if ($(el).is(':visible') && !$(el).parents().is(':hidden')) { pending[i][1].call(el); $.data(pending[i][0], '_jqs_pending', false); done.push(i); } else if (!$(el).closest('html').length && !$.data(el, '_jqs_pending')) { // element has been inserted and removed from the DOM // If it was not yet inserted into the dom then the .data request // will return true. // removing from the dom causes the data to be removed. $.data(pending[i][0], '_jqs_pending', false); done.push(i); } } for (i = done.length; i; i--) { pending.splice(done[i - 1], 1); } }; /** * User option handler */ $.fn.sparkline.options = createClass({ init: function (tag, userOptions) { var extendedOptions, defaults, base, tagOptionType; this.userOptions = userOptions = userOptions || {}; this.tag = tag; this.tagValCache = {}; defaults = $.fn.sparkline.defaults; base = defaults.common; this.tagOptionsPrefix = userOptions.enableTagOptions && (userOptions.tagOptionsPrefix || base.tagOptionsPrefix); tagOptionType = this.getTagSetting('type'); if (tagOptionType === UNSET_OPTION) { extendedOptions = defaults[userOptions.type || base.type]; } else { extendedOptions = defaults[tagOptionType]; } this.mergedOptions = $.extend({}, base, extendedOptions, userOptions); }, getTagSetting: function (key) { var prefix = this.tagOptionsPrefix, val, i, pairs, keyval; if (prefix === false || prefix === undefined) { return UNSET_OPTION; } if (this.tagValCache.hasOwnProperty(key)) { val = this.tagValCache.key; } else { val = this.tag.getAttribute(prefix + key); if (val === undefined || val === null) { val = UNSET_OPTION; } else if (val.substr(0, 1) === '[') { val = val.substr(1, val.length - 2).split(','); for (i = val.length; i--;) { val[i] = normalizeValue(val[i].replace(/(^\s*)|(\s*$)/g, '')); } } else if (val.substr(0, 1) === '{') { pairs = val.substr(1, val.length - 2).split(','); val = {}; for (i = pairs.length; i--;) { keyval = pairs[i].split(':', 2); val[keyval[0].replace(/(^\s*)|(\s*$)/g, '')] = normalizeValue(keyval[1].replace(/(^\s*)|(\s*$)/g, '')); } } else { val = normalizeValue(val); } this.tagValCache.key = val; } return val; }, get: function (key, defaultval) { var tagOption = this.getTagSetting(key), result; if (tagOption !== UNSET_OPTION) { return tagOption; } return (result = this.mergedOptions[key]) === undefined ? defaultval : result; } }); $.fn.sparkline._base = createClass({ disabled: false, init: function (el, values, options, width, height) { this.el = el; this.$el = $(el); this.values = values; this.options = options; this.width = width; this.height = height; this.currentRegion = undefined; }, /** * Setup the canvas */ initTarget: function () { var interactive = !this.options.get('disableInteraction'); if (!(this.target = this.$el.simpledraw(this.width, this.height, this.options.get('composite'), interactive))) { this.disabled = true; } else { this.canvasWidth = this.target.pixelWidth; this.canvasHeight = this.target.pixelHeight; } }, /** * Actually render the chart to the canvas */ render: function () { if (this.disabled) { this.el.innerHTML = ''; return false; } return true; }, /** * Return a region id for a given x/y co-ordinate */ getRegion: function (x, y) { }, /** * Highlight an item based on the moused-over x,y co-ordinate */ setRegionHighlight: function (el, x, y) { var currentRegion = this.currentRegion, highlightEnabled = !this.options.get('disableHighlight'), newRegion; if (x > this.canvasWidth || y > this.canvasHeight || x < 0 || y < 0) { return null; } newRegion = this.getRegion(el, x, y); if (currentRegion !== newRegion) { if (currentRegion !== undefined && highlightEnabled) { this.removeHighlight(); } this.currentRegion = newRegion; if (newRegion !== undefined && highlightEnabled) { this.renderHighlight(); } return true; } return false; }, /** * Reset any currently highlighted item */ clearRegionHighlight: function () { if (this.currentRegion !== undefined) { this.removeHighlight(); this.currentRegion = undefined; return true; } return false; }, renderHighlight: function () { this.changeHighlight(true); }, removeHighlight: function () { this.changeHighlight(false); }, changeHighlight: function (highlight) {}, /** * Fetch the HTML to display as a tooltip */ getCurrentRegionTooltip: function () { var options = this.options, header = '', entries = [], fields, formats, formatlen, fclass, text, i, showFields, showFieldsKey, newFields, fv, formatter, format, fieldlen, j; if (this.currentRegion === undefined) { return ''; } fields = this.getCurrentRegionFields(); formatter = options.get('tooltipFormatter'); if (formatter) { return formatter(this, options, fields); } if (options.get('tooltipChartTitle')) { header += '<div class="jqs jqstitle">' + options.get('tooltipChartTitle') + '</div>\n'; } formats = this.options.get('tooltipFormat'); if (!formats) { return ''; } if (!$.isArray(formats)) { formats = [formats]; } if (!$.isArray(fields)) { fields = [fields]; } showFields = this.options.get('tooltipFormatFieldlist'); showFieldsKey = this.options.get('tooltipFormatFieldlistKey'); if (showFields && showFieldsKey) { // user-selected ordering of fields newFields = []; for (i = fields.length; i--;) { fv = fields[i][showFieldsKey]; if ((j = $.inArray(fv, showFields)) != -1) { newFields[j] = fields[i]; } } fields = newFields; } formatlen = formats.length; fieldlen = fields.length; for (i = 0; i < formatlen; i++) { format = formats[i]; if (typeof format === 'string') { format = new SPFormat(format); } fclass = format.fclass || 'jqsfield'; for (j = 0; j < fieldlen; j++) { if (!fields[j].isNull || !options.get('tooltipSkipNull')) { $.extend(fields[j], { prefix: options.get('tooltipPrefix'), suffix: options.get('tooltipSuffix') }); text = format.render(fields[j], options.get('tooltipValueLookups'), options); entries.push('<div class="' + fclass + '">' + text + '</div>'); } } } if (entries.length) { return header + entries.join('\n'); } return ''; }, getCurrentRegionFields: function () {}, calcHighlightColor: function (color, options) { var highlightColor = options.get('highlightColor'), lighten = options.get('highlightLighten'), parse, mult, rgbnew, i; if (highlightColor) { return highlightColor; } if (lighten) { // extract RGB values parse = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(color) || /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color); if (parse) { rgbnew = []; mult = color.length === 4 ? 16 : 1; for (i = 0; i < 3; i++) { rgbnew[i] = clipval(Math.round(parseInt(parse[i + 1], 16) * mult * lighten), 0, 255); } return 'rgb(' + rgbnew.join(',') + ')'; } } return color; } }); barHighlightMixin = { changeHighlight: function (highlight) { var currentRegion = this.currentRegion, target = this.target, shapeids = this.regionShapes[currentRegion], newShapes; // will be null if the region value was null if (shapeids) { newShapes = this.renderRegion(currentRegion, highlight); if ($.isArray(newShapes) || $.isArray(shapeids)) { target.replaceWithShapes(shapeids, newShapes); this.regionShapes[currentRegion] = $.map(newShapes, function (newShape) { return newShape.id; }); } else { target.replaceWithShape(shapeids, newShapes); this.regionShapes[currentRegion] = newShapes.id; } } }, render: function () { var values = this.values, target = this.target, regionShapes = this.regionShapes, shapes, ids, i, j; if (!this.cls._super.render.call(this)) { return; } for (i = values.length; i--;) { shapes = this.renderRegion(i); if (shapes) { if ($.isArray(shapes)) { ids = []; for (j = shapes.length; j--;) { shapes[j].append(); ids.push(shapes[j].id); } regionShapes[i] = ids; } else { shapes.append(); regionShapes[i] = shapes.id; // store just the shapeid } } else { // null value regionShapes[i] = null; } } target.render(); } }; /** * Line charts */ $.fn.sparkline.line = line = createClass($.fn.sparkline._base, { type: 'line', init: function (el, values, options, width, height) { line._super.init.call(this, el, values, options, width, height); this.vertices = []; this.regionMap = []; this.xvalues = []; this.yvalues = []; this.yminmax = []; this.hightlightSpotId = null; this.lastShapeId = null; this.initTarget(); }, getRegion: function (el, x, y) { var i, regionMap = this.regionMap; // maps regions to value positions for (i = regionMap.length; i--;) { if (regionMap[i] !== null && x >= regionMap[i][0] && x <= regionMap[i][1]) { return regionMap[i][2]; } } return undefined; }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.yvalues[currentRegion] === null, x: this.xvalues[currentRegion], y: this.yvalues[currentRegion], color: this.options.get('lineColor'), fillColor: this.options.get('fillColor'), offset: currentRegion }; }, renderHighlight: function () { var currentRegion = this.currentRegion, target = this.target, vertex = this.vertices[currentRegion], options = this.options, spotRadius = options.get('spotRadius'), highlightSpotColor = options.get('highlightSpotColor'), highlightLineColor = options.get('highlightLineColor'), highlightSpot, highlightLine; if (!vertex) { return; } if (spotRadius && highlightSpotColor) { highlightSpot = target.drawCircle(vertex[0], vertex[1], spotRadius, undefined, highlightSpotColor); this.highlightSpotId = highlightSpot.id; target.insertAfterShape(this.lastShapeId, highlightSpot); } if (highlightLineColor) { highlightLine = target.drawLine(vertex[0], this.canvasTop, vertex[0], this.canvasTop + this.canvasHeight, highlightLineColor); this.highlightLineId = highlightLine.id; target.insertAfterShape(this.lastShapeId, highlightLine); } }, removeHighlight: function () { var target = this.target; if (this.highlightSpotId) { target.removeShapeId(this.highlightSpotId); this.highlightSpotId = null; } if (this.highlightLineId) { target.removeShapeId(this.highlightLineId); this.highlightLineId = null; } }, scanValues: function () { var values = this.values, valcount = values.length, xvalues = this.xvalues, yvalues = this.yvalues, yminmax = this.yminmax, i, val, isStr, isArray, sp; for (i = 0; i < valcount; i++) { val = values[i]; isStr = typeof(values[i]) === 'string'; isArray = typeof(values[i]) === 'object' && values[i] instanceof Array; sp = isStr && values[i].split(':'); if (isStr && sp.length === 2) { // x:y xvalues.push(Number(sp[0])); yvalues.push(Number(sp[1])); yminmax.push(Number(sp[1])); } else if (isArray) { xvalues.push(val[0]); yvalues.push(val[1]); yminmax.push(val[1]); } else { xvalues.push(i); if (values[i] === null || values[i] === 'null') { yvalues.push(null); } else { yvalues.push(Number(val)); yminmax.push(Number(val)); } } } if (this.options.get('xvalues')) { xvalues = this.options.get('xvalues'); } this.maxy = this.maxyorg = Math.max.apply(Math, yminmax); this.miny = this.minyorg = Math.min.apply(Math, yminmax); this.maxx = Math.max.apply(Math, xvalues); this.minx = Math.min.apply(Math, xvalues); this.xvalues = xvalues; this.yvalues = yvalues; this.yminmax = yminmax; }, processRangeOptions: function () { var options = this.options, normalRangeMin = options.get('normalRangeMin'), normalRangeMax = options.get('normalRangeMax'); if (normalRangeMin !== undefined) { if (normalRangeMin < this.miny) { this.miny = normalRangeMin; } if (normalRangeMax > this.maxy) { this.maxy = normalRangeMax; } } if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.miny)) { this.miny = options.get('chartRangeMin'); } if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.maxy)) { this.maxy = options.get('chartRangeMax'); } if (options.get('chartRangeMinX') !== undefined && (options.get('chartRangeClipX') || options.get('chartRangeMinX') < this.minx)) { this.minx = options.get('chartRangeMinX'); } if (options.get('chartRangeMaxX') !== undefined && (options.get('chartRangeClipX') || options.get('chartRangeMaxX') > this.maxx)) { this.maxx = options.get('chartRangeMaxX'); } }, drawNormalRange: function (canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey) { var normalRangeMin = this.options.get('normalRangeMin'), normalRangeMax = this.options.get('normalRangeMax'), ytop = canvasTop + Math.round(canvasHeight - (canvasHeight * ((normalRangeMax - this.miny) / rangey))), height = Math.round((canvasHeight * (normalRangeMax - normalRangeMin)) / rangey); this.target.drawRect(canvasLeft, ytop, canvasWidth, height, undefined, this.options.get('normalRangeColor')).append(); }, render: function () { var options = this.options, target = this.target, canvasWidth = this.canvasWidth, canvasHeight = this.canvasHeight, vertices = this.vertices, spotRadius = options.get('spotRadius'), regionMap = this.regionMap, rangex, rangey, yvallast, canvasTop, canvasLeft, vertex, path, paths, x, y, xnext, xpos, xposnext, last, next, yvalcount, lineShapes, fillShapes, plen, valueSpots, hlSpotsEnabled, color, xvalues, yvalues, i; if (!line._super.render.call(this)) { return; } this.scanValues(); this.processRangeOptions(); xvalues = this.xvalues; yvalues = this.yvalues; if (!this.yminmax.length || this.yvalues.length < 2) { // empty or all null valuess return; } canvasTop = canvasLeft = 0; rangex = this.maxx - this.minx === 0 ? 1 : this.maxx - this.minx; rangey = this.maxy - this.miny === 0 ? 1 : this.maxy - this.miny; yvallast = this.yvalues.length - 1; if (spotRadius && (canvasWidth < (spotRadius * 4) || canvasHeight < (spotRadius * 4))) { spotRadius = 0; } if (spotRadius) { // adjust the canvas size as required so that spots will fit hlSpotsEnabled = options.get('highlightSpotColor') && !options.get('disableInteraction'); if (hlSpotsEnabled || options.get('minSpotColor') || (options.get('spotColor') && yvalues[yvallast] === this.miny)) { canvasHeight -= Math.ceil(spotRadius); } if (hlSpotsEnabled || options.get('maxSpotColor') || (options.get('spotColor') && yvalues[yvallast] === this.maxy)) { canvasHeight -= Math.ceil(spotRadius); canvasTop += Math.ceil(spotRadius); } if (hlSpotsEnabled || ((options.get('minSpotColor') || options.get('maxSpotColor')) && (yvalues[0] === this.miny || yvalues[0] === this.maxy))) { canvasLeft += Math.ceil(spotRadius); canvasWidth -= Math.ceil(spotRadius); } if (hlSpotsEnabled || options.get('spotColor') || (options.get('minSpotColor') || options.get('maxSpotColor') && (yvalues[yvallast] === this.miny || yvalues[yvallast] === this.maxy))) { canvasWidth -= Math.ceil(spotRadius); } } canvasHeight--; if (options.get('normalRangeMin') !== undefined && !options.get('drawNormalOnTop')) { this.drawNormalRange(canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey); } path = []; paths = [path]; last = next = null; yvalcount = yvalues.length; for (i = 0; i < yvalcount; i++) { x = xvalues[i]; xnext = xvalues[i + 1]; y = yvalues[i]; xpos = canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)); xposnext = i < yvalcount - 1 ? canvasLeft + Math.round((xnext - this.minx) * (canvasWidth / rangex)) : canvasWidth; next = xpos + ((xposnext - xpos) / 2); regionMap[i] = [last || 0, next, i]; last = next; if (y === null) { if (i) { if (yvalues[i - 1] !== null) { path = []; paths.push(path); } vertices.push(null); } } else { if (y < this.miny) { y = this.miny; } if (y > this.maxy) { y = this.maxy; } if (!path.length) { // previous value was null path.push([xpos, canvasTop + canvasHeight]); } vertex = [xpos, canvasTop + Math.round(canvasHeight - (canvasHeight * ((y - this.miny) / rangey)))]; path.push(vertex); vertices.push(vertex); } } lineShapes = []; fillShapes = []; plen = paths.length; for (i = 0; i < plen; i++) { path = paths[i]; if (path.length) { if (options.get('fillColor')) { path.push([path[path.length - 1][0], (canvasTop + canvasHeight)]); fillShapes.push(path.slice(0)); path.pop(); } // if there's only a single point in this path, then we want to display it // as a vertical line which means we keep path[0] as is if (path.length > 2) { // else we want the first value path[0] = [path[0][0], path[1][1]]; } lineShapes.push(path); } } // draw the fill first, then optionally the normal range, then the line on top of that plen = fillShapes.length; for (i = 0; i < plen; i++) { target.drawShape(fillShapes[i], options.get('fillColor'), options.get('fillColor')).append(); } if (options.get('normalRangeMin') !== undefined && options.get('drawNormalOnTop')) { this.drawNormalRange(canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey); } plen = lineShapes.length; for (i = 0; i < plen; i++) { target.drawShape(lineShapes[i], options.get('lineColor'), undefined, options.get('lineWidth')).append(); } if (spotRadius && options.get('valueSpots')) { valueSpots = options.get('valueSpots'); if (valueSpots.get === undefined) { valueSpots = new RangeMap(valueSpots); } for (i = 0; i < yvalcount; i++) { color = valueSpots.get(yvalues[i]); if (color) { target.drawCircle(canvasLeft + Math.round((xvalues[i] - this.minx) * (canvasWidth / rangex)), canvasTop + Math.round(canvasHeight - (canvasHeight * ((yvalues[i] - this.miny) / rangey))), spotRadius, undefined, color).append(); } } } if (spotRadius && options.get('spotColor') && yvalues[yvallast] !== null) { target.drawCircle(canvasLeft + Math.round((xvalues[xvalues.length - 1] - this.minx) * (canvasWidth / rangex)), canvasTop + Math.round(canvasHeight - (canvasHeight * ((yvalues[yvallast] - this.miny) / rangey))), spotRadius, undefined, options.get('spotColor')).append(); } if (this.maxy !== this.minyorg) { if (spotRadius && options.get('minSpotColor')) { x = xvalues[$.inArray(this.minyorg, yvalues)]; target.drawCircle(canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)), canvasTop + Math.round(canvasHeight - (canvasHeight * ((this.minyorg - this.miny) / rangey))), spotRadius, undefined, options.get('minSpotColor')).append(); } if (spotRadius && options.get('maxSpotColor')) { x = xvalues[$.inArray(this.maxyorg, yvalues)]; target.drawCircle(canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)), canvasTop + Math.round(canvasHeight - (canvasHeight * ((this.maxyorg - this.miny) / rangey))), spotRadius, undefined, options.get('maxSpotColor')).append(); } } this.lastShapeId = target.getLastShapeId(); this.canvasTop = canvasTop; target.render(); } }); /** * Bar charts */ $.fn.sparkline.bar = bar = createClass($.fn.sparkline._base, barHighlightMixin, { type: 'bar', init: function (el, values, options, width, height) { var barWidth = parseInt(options.get('barWidth'), 10), barSpacing = parseInt(options.get('barSpacing'), 10), chartRangeMin = options.get('chartRangeMin'), chartRangeMax = options.get('chartRangeMax'), chartRangeClip = options.get('chartRangeClip'), stackMin = Infinity, stackMax = -Infinity, isStackString, groupMin, groupMax, stackRanges, numValues, i, vlen, range, zeroAxis, xaxisOffset, min, max, clipMin, clipMax, stacked, vlist, j, slen, svals, val, yoffset, yMaxCalc, canvasHeightEf; bar._super.init.call(this, el, values, options, width, height); // scan values to determine whether to stack bars for (i = 0, vlen = values.length; i < vlen; i++) { val = values[i]; isStackString = typeof(val) === 'string' && val.indexOf(':') > -1; if (isStackString || $.isArray(val)) { stacked = true; if (isStackString) { val = values[i] = normalizeValues(val.split(':')); } val = remove(val, null); // min/max will treat null as zero groupMin = Math.min.apply(Math, val); groupMax = Math.max.apply(Math, val); if (groupMin < stackMin) { stackMin = groupMin; } if (groupMax > stackMax) { stackMax = groupMax; } } } this.stacked = stacked; this.regionShapes = {}; this.barWidth = barWidth; this.barSpacing = barSpacing; this.totalBarWidth = barWidth + barSpacing; this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing); this.initTarget(); if (chartRangeClip) { clipMin = chartRangeMin === undefined ? -Infinity : chartRangeMin; clipMax = chartRangeMax === undefined ? Infinity : chartRangeMax; } numValues = []; stackRanges = stacked ? [] : numValues; var stackTotals = []; var stackRangesNeg = []; for (i = 0, vlen = values.length; i < vlen; i++) { if (stacked) { vlist = values[i]; values[i] = svals = []; stackTotals[i] = 0; stackRanges[i] = stackRangesNeg[i] = 0; for (j = 0, slen = vlist.length; j < slen; j++) { val = svals[j] = chartRangeClip ? clipval(vlist[j], clipMin, clipMax) : vlist[j]; if (val !== null) { if (val > 0) { stackTotals[i] += val; } if (stackMin < 0 && stackMax > 0) { if (val < 0) { stackRangesNeg[i] += Math.abs(val); } else { stackRanges[i] += val; } } else { stackRanges[i] += Math.abs(val - (val < 0 ? stackMax : stackMin)); } numValues.push(val); } } } else { val = chartRangeClip ? clipval(values[i], clipMin, clipMax) : values[i]; val = values[i] = normalizeValue(val); if (val !== null) { numValues.push(val); } } } this.max = max = Math.max.apply(Math, numValues); this.min = min = Math.min.apply(Math, numValues); this.stackMax = stackMax = stacked ? Math.max.apply(Math, stackTotals) : max; this.stackMin = stackMin = stacked ? Math.min.apply(Math, numValues) : min; if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < min)) { min = options.get('chartRangeMin'); } if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > max)) { max = options.get('chartRangeMax'); } this.zeroAxis = zeroAxis = options.get('zeroAxis', true); if (min <= 0 && max >= 0 && zeroAxis) { xaxisOffset = 0; } else if (zeroAxis == false) { xaxisOffset = min; } else if (min > 0) { xaxisOffset = min; } else { xaxisOffset = max; } this.xaxisOffset = xaxisOffset; range = stacked ? (Math.max.apply(Math, stackRanges) + Math.max.apply(Math, stackRangesNeg)) : max - min; // as we plot zero/min values a single pixel line, we add a pixel to all other // values - Reduce the effective canvas size to suit this.canvasHeightEf = (zeroAxis && min < 0) ? this.canvasHeight - 2 : this.canvasHeight - 1; if (min < xaxisOffset) { yMaxCalc = (stacked && max >= 0) ? stackMax : max; yoffset = (yMaxCalc - xaxisOffset) / range * this.canvasHeight; if (yoffset !== Math.ceil(yoffset)) { this.canvasHeightEf -= 2; yoffset = Math.ceil(yoffset); } } else { yoffset = this.canvasHeight; } this.yoffset = yoffset; if ($.isArray(options.get('colorMap'))) { this.colorMapByIndex = options.get('colorMap'); this.colorMapByValue = null; } else { this.colorMapByIndex = null; this.colorMapByValue = options.get('colorMap'); if (this.colorMapByValue && this.colorMapByValue.get === undefined) { this.colorMapByValue = new RangeMap(this.colorMapByValue); } } this.range = range; }, getRegion: function (el, x, y) { var result = Math.floor(x / this.totalBarWidth); return (result < 0 || result >= this.values.length) ? undefined : result; }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion, values = ensureArray(this.values[currentRegion]), result = [], value, i; for (i = values.length; i--;) { value = values[i]; result.push({ isNull: value === null, value: value, color: this.calcColor(i, value, currentRegion), offset: currentRegion }); } return result; }, calcColor: function (stacknum, value, valuenum) { var colorMapByIndex = this.colorMapByIndex, colorMapByValue = this.colorMapByValue, options = this.options, color, newColor; if (this.stacked) { color = options.get('stackedBarColor'); } else { color = (value < 0) ? options.get('negBarColor') : options.get('barColor'); } if (value === 0 && options.get('zeroColor') !== undefined) { color = options.get('zeroColor'); } if (colorMapByValue && (newColor = colorMapByValue.get(value))) { color = newColor; } else if (colorMapByIndex && colorMapByIndex.length > valuenum) { color = colorMapByIndex[valuenum]; } return $.isArray(color) ? color[stacknum % color.length] : color; }, /** * Render bar(s) for a region */ renderRegion: function (valuenum, highlight) { var vals = this.values[valuenum], options = this.options, xaxisOffset = this.xaxisOffset, result = [], range = this.range, stacked = this.stacked, target = this.target, x = valuenum * this.totalBarWidth, canvasHeightEf = this.canvasHeightEf, yoffset = this.yoffset, y, height, color, isNull, yoffsetNeg, i, valcount, val, minPlotted, allMin; vals = $.isArray(vals) ? vals : [vals]; valcount = vals.length; val = vals[0]; isNull = all(null, vals); allMin = all(xaxisOffset, vals, true); if (isNull) { if (options.get('nullColor')) { color = highlight ? options.get('nullColor') : this.calcHighlightColor(options.get('nullColor'), options); y = (yoffset > 0) ? yoffset - 1 : yoffset; return target.drawRect(x, y, this.barWidth - 1, 0, color, color); } else { return undefined; } } yoffsetNeg = yoffset; for (i = 0; i < valcount; i++) { val = vals[i]; if (stacked && val === xaxisOffset) { if (!allMin || minPlotted) { continue; } minPlotted = true; } if (range > 0) { height = Math.floor(canvasHeightEf * ((Math.abs(val - xaxisOffset) / range))) + 1; } else { height = 1; } if (val < xaxisOffset || (val === xaxisOffset && yoffset === 0)) { y = yoffsetNeg; yoffsetNeg += height; } else { y = yoffset - height; yoffset -= height; } color = this.calcColor(i, val, valuenum); if (highlight) { color = this.calcHighlightColor(color, options); } result.push(target.drawRect(x, y, this.barWidth - 1, height - 1, color, color)); } if (result.length === 1) { return result[0]; } return result; } }); /** * Tristate charts */ $.fn.sparkline.tristate = tristate = createClass($.fn.sparkline._base, barHighlightMixin, { type: 'tristate', init: function (el, values, options, width, height) { var barWidth = parseInt(options.get('barWidth'), 10), barSpacing = parseInt(options.get('barSpacing'), 10); tristate._super.init.call(this, el, values, options, width, height); this.regionShapes = {}; this.barWidth = barWidth; this.barSpacing = barSpacing; this.totalBarWidth = barWidth + barSpacing; this.values = $.map(values, Number); this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing); if ($.isArray(options.get('colorMap'))) { this.colorMapByIndex = options.get('colorMap'); this.colorMapByValue = null; } else { this.colorMapByIndex = null; this.colorMapByValue = options.get('colorMap'); if (this.colorMapByValue && this.colorMapByValue.get === undefined) { this.colorMapByValue = new RangeMap(this.colorMapByValue); } } this.initTarget(); }, getRegion: function (el, x, y) { return Math.floor(x / this.totalBarWidth); }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.values[currentRegion] === undefined, value: this.values[currentRegion], color: this.calcColor(this.values[currentRegion], currentRegion), offset: currentRegion }; }, calcColor: function (value, valuenum) { var values = this.values, options = this.options, colorMapByIndex = this.colorMapByIndex, colorMapByValue = this.colorMapByValue, color, newColor; if (colorMapByValue && (newColor = colorMapByValue.get(value))) { color = newColor; } else if (colorMapByIndex && colorMapByIndex.length > valuenum) { color = colorMapByIndex[valuenum]; } else if (values[valuenum] < 0) { color = options.get('negBarColor'); } else if (values[valuenum] > 0) { color = options.get('posBarColor'); } else { color = options.get('zeroBarColor'); } return color; }, renderRegion: function (valuenum, highlight) { var values = this.values, options = this.options, target = this.target, canvasHeight, height, halfHeight, x, y, color; canvasHeight = target.pixelHeight; halfHeight = Math.round(canvasHeight / 2); x = valuenum * this.totalBarWidth; if (values[valuenum] < 0) { y = halfHeight; height = halfHeight - 1; } else if (values[valuenum] > 0) { y = 0; height = halfHeight - 1; } else { y = halfHeight - 1; height = 2; } color = this.calcColor(values[valuenum], valuenum); if (color === null) { return; } if (highlight) { color = this.calcHighlightColor(color, options); } return target.drawRect(x, y, this.barWidth - 1, height - 1, color, color); } }); /** * Discrete charts */ $.fn.sparkline.discrete = discrete = createClass($.fn.sparkline._base, barHighlightMixin, { type: 'discrete', init: function (el, values, options, width, height) { discrete._super.init.call(this, el, values, options, width, height); this.regionShapes = {}; this.values = values = $.map(values, Number); this.min = Math.min.apply(Math, values); this.max = Math.max.apply(Math, values); this.range = this.max - this.min; this.width = width = options.get('width') === 'auto' ? values.length * 2 : this.width; this.interval = Math.floor(width / values.length); this.itemWidth = width / values.length; if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.min)) { this.min = options.get('chartRangeMin'); } if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.max)) { this.max = options.get('chartRangeMax'); } this.initTarget(); if (this.target) { this.lineHeight = options.get('lineHeight') === 'auto' ? Math.round(this.canvasHeight * 0.3) : options.get('lineHeight'); } }, getRegion: function (el, x, y) { return Math.floor(x / this.itemWidth); }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.values[currentRegion] === undefined, value: this.values[currentRegion], offset: currentRegion }; }, renderRegion: function (valuenum, highlight) { var values = this.values, options = this.options, min = this.min, max = this.max, range = this.range, interval = this.interval, target = this.target, canvasHeight = this.canvasHeight, lineHeight = this.lineHeight, pheight = canvasHeight - lineHeight, ytop, val, color, x; val = clipval(values[valuenum], min, max); x = valuenum * interval; ytop = Math.round(pheight - pheight * ((val - min) / range)); color = (options.get('thresholdColor') && val < options.get('thresholdValue')) ? options.get('thresholdColor') : options.get('lineColor'); if (highlight) { color = this.calcHighlightColor(color, options); } return target.drawLine(x, ytop, x, ytop + lineHeight, color); } }); /** * Bullet charts */ $.fn.sparkline.bullet = bullet = createClass($.fn.sparkline._base, { type: 'bullet', init: function (el, values, options, width, height) { var min, max, vals; bullet._super.init.call(this, el, values, options, width, height); // values: target, performance, range1, range2, range3 this.values = values = normalizeValues(values); // target or performance could be null vals = values.slice(); vals[0] = vals[0] === null ? vals[2] : vals[0]; vals[1] = values[1] === null ? vals[2] : vals[1]; min = Math.min.apply(Math, values); max = Math.max.apply(Math, values); if (options.get('base') === undefined) { min = min < 0 ? min : 0; } else { min = options.get('base'); } this.min = min; this.max = max; this.range = max - min; this.shapes = {}; this.valueShapes = {}; this.regiondata = {}; this.width = width = options.get('width') === 'auto' ? '4.0em' : width; this.target = this.$el.simpledraw(width, height, options.get('composite')); if (!values.length) { this.disabled = true; } this.initTarget(); }, getRegion: function (el, x, y) { var shapeid = this.target.getShapeAt(el, x, y); return (shapeid !== undefined && this.shapes[shapeid] !== undefined) ? this.shapes[shapeid] : undefined; }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { fieldkey: currentRegion.substr(0, 1), value: this.values[currentRegion.substr(1)], region: currentRegion }; }, changeHighlight: function (highlight) { var currentRegion = this.currentRegion, shapeid = this.valueShapes[currentRegion], shape; delete this.shapes[shapeid]; switch (currentRegion.substr(0, 1)) { case 'r': shape = this.renderRange(currentRegion.substr(1), highlight); break; case 'p': shape = this.renderPerformance(highlight); break; case 't': shape = this.renderTarget(highlight); break; } this.valueShapes[currentRegion] = shape.id; this.shapes[shape.id] = currentRegion; this.target.replaceWithShape(shapeid, shape); }, renderRange: function (rn, highlight) { var rangeval = this.values[rn], rangewidth = Math.round(this.canvasWidth * ((rangeval - this.min) / this.range)), color = this.options.get('rangeColors')[rn - 2]; if (highlight) { color = this.calcHighlightColor(color, this.options); } return this.target.drawRect(0, 0, rangewidth - 1, this.canvasHeight - 1, color, color); }, renderPerformance: function (highlight) { var perfval = this.values[1], perfwidth = Math.round(this.canvasWidth * ((perfval - this.min) / this.range)), color = this.options.get('performanceColor'); if (highlight) { color = this.calcHighlightColor(color, this.options); } return this.target.drawRect(0, Math.round(this.canvasHeight * 0.3), perfwidth - 1, Math.round(this.canvasHeight * 0.4) - 1, color, color); }, renderTarget: function (highlight) { var targetval = this.values[0], x = Math.round(this.canvasWidth * ((targetval - this.min) / this.range) - (this.options.get('targetWidth') / 2)), targettop = Math.round(this.canvasHeight * 0.10), targetheight = this.canvasHeight - (targettop * 2), color = this.options.get('targetColor'); if (highlight) { color = this.calcHighlightColor(color, this.options); } return this.target.drawRect(x, targettop, this.options.get('targetWidth') - 1, targetheight - 1, color, color); }, render: function () { var vlen = this.values.length, target = this.target, i, shape; if (!bullet._super.render.call(this)) { return; } for (i = 2; i < vlen; i++) { shape = this.renderRange(i).append(); this.shapes[shape.id] = 'r' + i; this.valueShapes['r' + i] = shape.id; } if (this.values[1] !== null) { shape = this.renderPerformance().append(); this.shapes[shape.id] = 'p1'; this.valueShapes.p1 = shape.id; } if (this.values[0] !== null) { shape = this.renderTarget().append(); this.shapes[shape.id] = 't0'; this.valueShapes.t0 = shape.id; } target.render(); } }); /** * Pie charts */ $.fn.sparkline.pie = pie = createClass($.fn.sparkline._base, { type: 'pie', init: function (el, values, options, width, height) { var total = 0, i; pie._super.init.call(this, el, values, options, width, height); this.shapes = {}; // map shape ids to value offsets this.valueShapes = {}; // maps value offsets to shape ids this.values = values = $.map(values, Number); if (options.get('width') === 'auto') { this.width = this.height; } if (values.length > 0) { for (i = values.length; i--;) { total += values[i]; } } this.total = total; this.initTarget(); this.radius = Math.floor(Math.min(this.canvasWidth, this.canvasHeight) / 2); }, getRegion: function (el, x, y) { var shapeid = this.target.getShapeAt(el, x, y); return (shapeid !== undefined && this.shapes[shapeid] !== undefined) ? this.shapes[shapeid] : undefined; }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.values[currentRegion] === undefined, value: this.values[currentRegion], percent: this.values[currentRegion] / this.total * 100, color: this.options.get('sliceColors')[currentRegion % this.options.get('sliceColors').length], offset: currentRegion }; }, changeHighlight: function (highlight) { var currentRegion = this.currentRegion, newslice = this.renderSlice(currentRegion, highlight), shapeid = this.valueShapes[currentRegion]; delete this.shapes[shapeid]; this.target.replaceWithShape(shapeid, newslice); this.valueShapes[currentRegion] = newslice.id; this.shapes[newslice.id] = currentRegion; }, renderSlice: function (valuenum, highlight) { var target = this.target, options = this.options, radius = this.radius, borderWidth = options.get('borderWidth'), offset = options.get('offset'), circle = 2 * Math.PI, values = this.values, total = this.total, next = offset ? (2*Math.PI)*(offset/360) : 0, start, end, i, vlen, color; vlen = values.length; for (i = 0; i < vlen; i++) { start = next; end = next; if (total > 0) { // avoid divide by zero end = next + (circle * (values[i] / total)); } if (valuenum === i) { color = options.get('sliceColors')[i % options.get('sliceColors').length]; if (highlight) { color = this.calcHighlightColor(color, options); } return target.drawPieSlice(radius, radius, radius - borderWidth, start, end, undefined, color); } next = end; } }, render: function () { var target = this.target, values = this.values, options = this.options, radius = this.radius, borderWidth = options.get('borderWidth'), shape, i; if (!pie._super.render.call(this)) { return; } if (borderWidth) { target.drawCircle(radius, radius, Math.floor(radius - (borderWidth / 2)), options.get('borderColor'), undefined, borderWidth).append(); } for (i = values.length; i--;) { if (values[i]) { // don't render zero values shape = this.renderSlice(i).append(); this.valueShapes[i] = shape.id; // store just the shapeid this.shapes[shape.id] = i; } } target.render(); } }); /** * Box plots */ $.fn.sparkline.box = box = createClass($.fn.sparkline._base, { type: 'box', init: function (el, values, options, width, height) { box._super.init.call(this, el, values, options, width, height); this.values = $.map(values, Number); this.width = options.get('width') === 'auto' ? '4.0em' : width; this.initTarget(); if (!this.values.length) { this.disabled = 1; } }, /** * Simulate a single region */ getRegion: function () { return 1; }, getCurrentRegionFields: function () { var result = [ { field: 'lq', value: this.quartiles[0] }, { field: 'med', value: this.quartiles[1] }, { field: 'uq', value: this.quartiles[2] } ]; if (this.loutlier !== undefined) { result.push({ field: 'lo', value: this.loutlier}); } if (this.routlier !== undefined) { result.push({ field: 'ro', value: this.routlier}); } if (this.lwhisker !== undefined) { result.push({ field: 'lw', value: this.lwhisker}); } if (this.rwhisker !== undefined) { result.push({ field: 'rw', value: this.rwhisker}); } return result; }, render: function () { var target = this.target, values = this.values, vlen = values.length, options = this.options, canvasWidth = this.canvasWidth, canvasHeight = this.canvasHeight, minValue = options.get('chartRangeMin') === undefined ? Math.min.apply(Math, values) : options.get('chartRangeMin'), maxValue = options.get('chartRangeMax') === undefined ? Math.max.apply(Math, values) : options.get('chartRangeMax'), canvasLeft = 0, lwhisker, loutlier, iqr, q1, q2, q3, rwhisker, routlier, i, size, unitSize; if (!box._super.render.call(this)) { return; } if (options.get('raw')) { if (options.get('showOutliers') && values.length > 5) { loutlier = values[0]; lwhisker = values[1]; q1 = values[2]; q2 = values[3]; q3 = values[4]; rwhisker = values[5]; routlier = values[6]; } else { lwhisker = values[0]; q1 = values[1]; q2 = values[2]; q3 = values[3]; rwhisker = values[4]; } } else { values.sort(function (a, b) { return a - b; }); q1 = quartile(values, 1); q2 = quartile(values, 2); q3 = quartile(values, 3); iqr = q3 - q1; if (options.get('showOutliers')) { lwhisker = rwhisker = undefined; for (i = 0; i < vlen; i++) { if (lwhisker === undefined && values[i] > q1 - (iqr * options.get('outlierIQR'))) { lwhisker = values[i]; } if (values[i] < q3 + (iqr * options.get('outlierIQR'))) { rwhisker = values[i]; } } loutlier = values[0]; routlier = values[vlen - 1]; } else { lwhisker = values[0]; rwhisker = values[vlen - 1]; } } this.quartiles = [q1, q2, q3]; this.lwhisker = lwhisker; this.rwhisker = rwhisker; this.loutlier = loutlier; this.routlier = routlier; unitSize = canvasWidth / (maxValue - minValue + 1); if (options.get('showOutliers')) { canvasLeft = Math.ceil(options.get('spotRadius')); canvasWidth -= 2 * Math.ceil(options.get('spotRadius')); unitSize = canvasWidth / (maxValue - minValue + 1); if (loutlier < lwhisker) { target.drawCircle((loutlier - minValue) * unitSize + canvasLeft, canvasHeight / 2, options.get('spotRadius'), options.get('outlierLineColor'), options.get('outlierFillColor')).append(); } if (routlier > rwhisker) { target.drawCircle((routlier - minValue) * unitSize + canvasLeft, canvasHeight / 2, options.get('spotRadius'), options.get('outlierLineColor'), options.get('outlierFillColor')).append(); } } // box target.drawRect( Math.round((q1 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight * 0.1), Math.round((q3 - q1) * unitSize), Math.round(canvasHeight * 0.8), options.get('boxLineColor'), options.get('boxFillColor')).append(); // left whisker target.drawLine( Math.round((lwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 2), Math.round((q1 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 2), options.get('lineColor')).append(); target.drawLine( Math.round((lwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 4), Math.round((lwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight - canvasHeight / 4), options.get('whiskerColor')).append(); // right whisker target.drawLine(Math.round((rwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 2), Math.round((q3 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 2), options.get('lineColor')).append(); target.drawLine( Math.round((rwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 4), Math.round((rwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight - canvasHeight / 4), options.get('whiskerColor')).append(); // median line target.drawLine( Math.round((q2 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight * 0.1), Math.round((q2 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight * 0.9), options.get('medianColor')).append(); if (options.get('target')) { size = Math.ceil(options.get('spotRadius')); target.drawLine( Math.round((options.get('target') - minValue) * unitSize + canvasLeft), Math.round((canvasHeight / 2) - size), Math.round((options.get('target') - minValue) * unitSize + canvasLeft), Math.round((canvasHeight / 2) + size), options.get('targetColor')).append(); target.drawLine( Math.round((options.get('target') - minValue) * unitSize + canvasLeft - size), Math.round(canvasHeight / 2), Math.round((options.get('target') - minValue) * unitSize + canvasLeft + size), Math.round(canvasHeight / 2), options.get('targetColor')).append(); } target.render(); } }); // Setup a very simple "virtual canvas" to make drawing the few shapes we need easier // This is accessible as $(foo).simpledraw() VShape = createClass({ init: function (target, id, type, args) { this.target = target; this.id = id; this.type = type; this.args = args; }, append: function () { this.target.appendShape(this); return this; } }); VCanvas_base = createClass({ _pxregex: /(\d+)(px)?\s*$/i, init: function (width, height, target) { if (!width) { return; } this.width = width; this.height = height; this.target = target; this.lastShapeId = null; if (target[0]) { target = target[0]; } $.data(target, '_jqs_vcanvas', this); }, drawLine: function (x1, y1, x2, y2, lineColor, lineWidth) { return this.drawShape([[x1, y1], [x2, y2]], lineColor, lineWidth); }, drawShape: function (path, lineColor, fillColor, lineWidth) { return this._genShape('Shape', [path, lineColor, fillColor, lineWidth]); }, drawCircle: function (x, y, radius, lineColor, fillColor, lineWidth) { return this._genShape('Circle', [x, y, radius, lineColor, fillColor, lineWidth]); }, drawPieSlice: function (x, y, radius, startAngle, endAngle, lineColor, fillColor) { return this._genShape('PieSlice', [x, y, radius, startAngle, endAngle, lineColor, fillColor]); }, drawRect: function (x, y, width, height, lineColor, fillColor) { return this._genShape('Rect', [x, y, width, height, lineColor, fillColor]); }, getElement: function () { return this.canvas; }, /** * Return the most recently inserted shape id */ getLastShapeId: function () { return this.lastShapeId; }, /** * Clear and reset the canvas */ reset: function () { alert('reset not implemented'); }, _insert: function (el, target) { $(target).html(el); }, /** * Calculate the pixel dimensions of the canvas */ _calculatePixelDims: function (width, height, canvas) { // XXX This should probably be a configurable option var match; match = this._pxregex.exec(height); if (match) { this.pixelHeight = match[1]; } else { this.pixelHeight = $(canvas).height(); } match = this._pxregex.exec(width); if (match) { this.pixelWidth = match[1]; } else { this.pixelWidth = $(canvas).width(); } }, /** * Generate a shape object and id for later rendering */ _genShape: function (shapetype, shapeargs) { var id = shapeCount++; shapeargs.unshift(id); return new VShape(this, id, shapetype, shapeargs); }, /** * Add a shape to the end of the render queue */ appendShape: function (shape) { alert('appendShape not implemented'); }, /** * Replace one shape with another */ replaceWithShape: function (shapeid, shape) { alert('replaceWithShape not implemented'); }, /** * Insert one shape after another in the render queue */ insertAfterShape: function (shapeid, shape) { alert('insertAfterShape not implemented'); }, /** * Remove a shape from the queue */ removeShapeId: function (shapeid) { alert('removeShapeId not implemented'); }, /** * Find a shape at the specified x/y co-ordinates */ getShapeAt: function (el, x, y) { alert('getShapeAt not implemented'); }, /** * Render all queued shapes onto the canvas */ render: function () { alert('render not implemented'); } }); VCanvas_canvas = createClass(VCanvas_base, { init: function (width, height, target, interact) { VCanvas_canvas._super.init.call(this, width, height, target); this.canvas = document.createElement('canvas'); if (target[0]) { target = target[0]; } $.data(target, '_jqs_vcanvas', this); $(this.canvas).css({ display: 'inline-block', width: width, height: height, verticalAlign: 'top' }); this._insert(this.canvas, target); this._calculatePixelDims(width, height, this.canvas); this.canvas.width = this.pixelWidth; this.canvas.height = this.pixelHeight; this.interact = interact; this.shapes = {}; this.shapeseq = []; this.currentTargetShapeId = undefined; $(this.canvas).css({width: this.pixelWidth, height: this.pixelHeight}); }, _getContext: function (lineColor, fillColor, lineWidth) { var context = this.canvas.getContext('2d'); if (lineColor !== undefined) { context.strokeStyle = lineColor; } context.lineWidth = lineWidth === undefined ? 1 : lineWidth; if (fillColor !== undefined) { context.fillStyle = fillColor; } return context; }, reset: function () { var context = this._getContext(); context.clearRect(0, 0, this.pixelWidth, this.pixelHeight); this.shapes = {}; this.shapeseq = []; this.currentTargetShapeId = undefined; }, _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) { var context = this._getContext(lineColor, fillColor, lineWidth), i, plen; context.beginPath(); context.moveTo(path[0][0] + 0.5, path[0][1] + 0.5); for (i = 1, plen = path.length; i < plen; i++) { context.lineTo(path[i][0] + 0.5, path[i][1] + 0.5); // the 0.5 offset gives us crisp pixel-width lines } if (lineColor !== undefined) { context.stroke(); } if (fillColor !== undefined) { context.fill(); } if (this.targetX !== undefined && this.targetY !== undefined && context.isPointInPath(this.targetX, this.targetY)) { this.currentTargetShapeId = shapeid; } }, _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) { var context = this._getContext(lineColor, fillColor, lineWidth); context.beginPath(); context.arc(x, y, radius, 0, 2 * Math.PI, false); if (this.targetX !== undefined && this.targetY !== undefined && context.isPointInPath(this.targetX, this.targetY)) { this.currentTargetShapeId = shapeid; } if (lineColor !== undefined) { context.stroke(); } if (fillColor !== undefined) { context.fill(); } }, _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) { var context = this._getContext(lineColor, fillColor); context.beginPath(); context.moveTo(x, y); context.arc(x, y, radius, startAngle, endAngle, false); context.lineTo(x, y); context.closePath(); if (lineColor !== undefined) { context.stroke(); } if (fillColor) { context.fill(); } if (this.targetX !== undefined && this.targetY !== undefined && context.isPointInPath(this.targetX, this.targetY)) { this.currentTargetShapeId = shapeid; } }, _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) { return this._drawShape(shapeid, [[x, y], [x + width, y], [x + width, y + height], [x, y + height], [x, y]], lineColor, fillColor); }, appendShape: function (shape) { this.shapes[shape.id] = shape; this.shapeseq.push(shape.id); this.lastShapeId = shape.id; return shape.id; }, replaceWithShape: function (shapeid, shape) { var shapeseq = this.shapeseq, i; this.shapes[shape.id] = shape; for (i = shapeseq.length; i--;) { if (shapeseq[i] == shapeid) { shapeseq[i] = shape.id; } } delete this.shapes[shapeid]; }, replaceWithShapes: function (shapeids, shapes) { var shapeseq = this.shapeseq, shapemap = {}, sid, i, first; for (i = shapeids.length; i--;) { shapemap[shapeids[i]] = true; } for (i = shapeseq.length; i--;) { sid = shapeseq[i]; if (shapemap[sid]) { shapeseq.splice(i, 1); delete this.shapes[sid]; first = i; } } for (i = shapes.length; i--;) { shapeseq.splice(first, 0, shapes[i].id); this.shapes[shapes[i].id] = shapes[i]; } }, insertAfterShape: function (shapeid, shape) { var shapeseq = this.shapeseq, i; for (i = shapeseq.length; i--;) { if (shapeseq[i] === shapeid) { shapeseq.splice(i + 1, 0, shape.id); this.shapes[shape.id] = shape; return; } } }, removeShapeId: function (shapeid) { var shapeseq = this.shapeseq, i; for (i = shapeseq.length; i--;) { if (shapeseq[i] === shapeid) { shapeseq.splice(i, 1); break; } } delete this.shapes[shapeid]; }, getShapeAt: function (el, x, y) { this.targetX = x; this.targetY = y; this.render(); return this.currentTargetShapeId; }, render: function () { var shapeseq = this.shapeseq, shapes = this.shapes, shapeCount = shapeseq.length, context = this._getContext(), shapeid, shape, i; context.clearRect(0, 0, this.pixelWidth, this.pixelHeight); for (i = 0; i < shapeCount; i++) { shapeid = shapeseq[i]; shape = shapes[shapeid]; this['_draw' + shape.type].apply(this, shape.args); } if (!this.interact) { // not interactive so no need to keep the shapes array this.shapes = {}; this.shapeseq = []; } } }); VCanvas_vml = createClass(VCanvas_base, { init: function (width, height, target) { var groupel; VCanvas_vml._super.init.call(this, width, height, target); if (target[0]) { target = target[0]; } $.data(target, '_jqs_vcanvas', this); this.canvas = document.createElement('span'); $(this.canvas).css({ display: 'inline-block', position: 'relative', overflow: 'hidden', width: width, height: height, margin: '0px', padding: '0px', verticalAlign: 'top'}); this._insert(this.canvas, target); this._calculatePixelDims(width, height, this.canvas); this.canvas.width = this.pixelWidth; this.canvas.height = this.pixelHeight; groupel = '<v:group coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '"' + ' style="position:absolute;top:0;left:0;width:' + this.pixelWidth + 'px;height=' + this.pixelHeight + 'px;"></v:group>'; this.canvas.insertAdjacentHTML('beforeEnd', groupel); this.group = $(this.canvas).children()[0]; this.rendered = false; this.prerender = ''; }, _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) { var vpath = [], initial, stroke, fill, closed, vel, plen, i; for (i = 0, plen = path.length; i < plen; i++) { vpath[i] = '' + (path[i][0]) + ',' + (path[i][1]); } initial = vpath.splice(0, 1); lineWidth = lineWidth === undefined ? 1 : lineWidth; stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" '; fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" '; closed = vpath[0] === vpath[vpath.length - 1] ? 'x ' : ''; vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' + ' id="jqsshape' + shapeid + '" ' + stroke + fill + ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' + ' path="m ' + initial + ' l ' + vpath.join(', ') + ' ' + closed + 'e">' + ' </v:shape>'; return vel; }, _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) { var stroke, fill, vel; x -= radius; y -= radius; stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" '; fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" '; vel = '<v:oval ' + ' id="jqsshape' + shapeid + '" ' + stroke + fill + ' style="position:absolute;top:' + y + 'px; left:' + x + 'px; width:' + (radius * 2) + 'px; height:' + (radius * 2) + 'px"></v:oval>'; return vel; }, _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) { var vpath, startx, starty, endx, endy, stroke, fill, vel; if (startAngle === endAngle) { return ''; // VML seems to have problem when start angle equals end angle. } if ((endAngle - startAngle) === (2 * Math.PI)) { startAngle = 0.0; // VML seems to have a problem when drawing a full circle that doesn't start 0 endAngle = (2 * Math.PI); } startx = x + Math.round(Math.cos(startAngle) * radius); starty = y + Math.round(Math.sin(startAngle) * radius); endx = x + Math.round(Math.cos(endAngle) * radius); endy = y + Math.round(Math.sin(endAngle) * radius); if (startx === endx && starty === endy) { if ((endAngle - startAngle) < Math.PI) { // Prevent very small slices from being mistaken as a whole pie return ''; } // essentially going to be the entire circle, so ignore startAngle startx = endx = x + radius; starty = endy = y; } if (startx === endx && starty === endy && (endAngle - startAngle) < Math.PI) { return ''; } vpath = [x - radius, y - radius, x + radius, y + radius, startx, starty, endx, endy]; stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="1px" strokeColor="' + lineColor + '" '; fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" '; vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' + ' id="jqsshape' + shapeid + '" ' + stroke + fill + ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' + ' path="m ' + x + ',' + y + ' wa ' + vpath.join(', ') + ' x e">' + ' </v:shape>'; return vel; }, _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) { return this._drawShape(shapeid, [[x, y], [x, y + height], [x + width, y + height], [x + width, y], [x, y]], lineColor, fillColor); }, reset: function () { this.group.innerHTML = ''; }, appendShape: function (shape) { var vel = this['_draw' + shape.type].apply(this, shape.args); if (this.rendered) { this.group.insertAdjacentHTML('beforeEnd', vel); } else { this.prerender += vel; } this.lastShapeId = shape.id; return shape.id; }, replaceWithShape: function (shapeid, shape) { var existing = $('#jqsshape' + shapeid), vel = this['_draw' + shape.type].apply(this, shape.args); existing[0].outerHTML = vel; }, replaceWithShapes: function (shapeids, shapes) { // replace the first shapeid with all the new shapes then toast the remaining old shapes var existing = $('#jqsshape' + shapeids[0]), replace = '', slen = shapes.length, i; for (i = 0; i < slen; i++) { replace += this['_draw' + shapes[i].type].apply(this, shapes[i].args); } existing[0].outerHTML = replace; for (i = 1; i < shapeids.length; i++) { $('#jqsshape' + shapeids[i]).remove(); } }, insertAfterShape: function (shapeid, shape) { var existing = $('#jqsshape' + shapeid), vel = this['_draw' + shape.type].apply(this, shape.args); existing[0].insertAdjacentHTML('afterEnd', vel); }, removeShapeId: function (shapeid) { var existing = $('#jqsshape' + shapeid); this.group.removeChild(existing[0]); }, getShapeAt: function (el, x, y) { var shapeid = el.id.substr(8); return shapeid; }, render: function () { if (!this.rendered) { // batch the intial render into a single repaint this.group.innerHTML = this.prerender; this.rendered = true; } } }); }))}(document, Math));PK ɫ�ZE��ݷ � piegage/piegage-demo.jsnu �[��� /* Pie gauges */ var initPieChart = function() { $('.chart').easyPieChart({ barColor: function(percent) { percent /= 100; return "rgb(" + Math.round(254 * (1 - percent)) + ", " + Math.round(255 * percent) + ", 0)"; }, animate: 1000, scaleColor: '#ccc', lineWidth: 3, size: 100, lineCap: 'cap', onStep: function(value) { this.$el.find('span').text(~~value); } }); $('.chart-home').easyPieChart({ barColor: 'rgba(255,255,255,0.5)', trackColor: 'rgba(255,255,255,0.1)', animate: 1000, scaleColor: 'rgba(255,255,255,0.3)', lineWidth: 3, size: 100, lineCap: 'cap', onStep: function(value) { this.$el.find('span').text(~~value); } }); $('.chart-alt').easyPieChart({ barColor: function(percent) { percent /= 100; return "rgb(" + Math.round(255 * (1 - percent)) + ", " + Math.round(255 * percent) + ", 0)"; }, trackColor: '#333', scaleColor: false, lineCap: 'butt', rotate: -90, lineWidth: 20, animate: 1500, onStep: function(value) { this.$el.find('span').text(~~value); } }); $('.chart-alt-1').easyPieChart({ barColor: function(percent) { percent /= 100; return "rgb(" + Math.round(255 * (1 - percent)) + ", " + Math.round(255 * percent) + ", 0)"; }, trackColor: '#e1ecf1', scaleColor: '#c4d7e0', lineCap: 'cap', rotate: -90, lineWidth: 10, size: 80, animate: 2500, onStep: function(value) { this.$el.find('span').text(~~value); } }); $('.chart-alt-2').easyPieChart({ barColor: function(percent) { percent /= 100; return "rgb(" + Math.round(255 * (1 - percent)) + ", " + Math.round(255 * percent) + ", 0)"; }, trackColor: '#fff', scaleColor: false, lineCap: 'butt', rotate: -90, lineWidth: 4, size: 50, animate: 1500, onStep: function(value) { this.$el.find('span').text(~~value); } }); $('.chart-alt-3').easyPieChart({ barColor: function(percent) { percent /= 100; return "rgb(" + Math.round(255 * (1 - percent)) + ", " + Math.round(255 * percent) + ", 0)"; }, trackColor: '#333', scaleColor: true, lineCap: 'butt', rotate: -90, lineWidth: 4, size: 50, animate: 1500, onStep: function(value) { this.$el.find('span').text(~~value); } }); $('.chart-alt-10').easyPieChart({ barColor: 'rgba(255,255,255,255.4)', trackColor: 'rgba(255,255,255,0.1)', scaleColor: 'transparent', lineCap: 'round', rotate: -90, lineWidth: 4, size: 100, animate: 2500, onStep: function(value) { this.$el.find('span').text(~~value); } }); $('.updateEasyPieChart').on('click', function(e) { e.preventDefault(); $('.chart-home, .chart, .chart-alt, .chart-alt-1, .chart-alt-2, .chart-alt-3, .chart-alt-10').each(function() { $(this).data('easyPieChart').update(Math.round(100 * Math.random())); }); }); }; $(document).ready(function() { initPieChart(); }); PK ɫ�ZT*�l l piegage/piegage.jsnu �[��� // Generated by CoffeeScript 1.6.2 /* Easy pie chart is a jquery plugin to display simple animated pie charts for only one value Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. Built on top of the jQuery library (http://jquery.com) @source: http://github.com/rendro/easy-pie-chart/ @autor: Robert Fleischmann @version: 1.2.1 Inspired by: http://dribbble.com/shots/631074-Simple-Pie-Charts-II?list=popular&offset=210 Thanks to Philip Thrasher for the jquery plugin boilerplate for coffee script */ (function($) { $.easyPieChart = function(el, options) { var addScaleLine, animateLine, drawLine, easeInOutQuad, rAF, renderBackground, renderScale, renderTrack, _this = this; this.el = el; this.$el = $(el); this.$el.data("easyPieChart", this); this.init = function() { var percent, scaleBy; _this.options = $.extend({}, $.easyPieChart.defaultOptions, options); percent = parseInt(_this.$el.data('percent'), 10); _this.percentage = 0; _this.canvas = $("<canvas width='" + _this.options.size + "' height='" + _this.options.size + "'></canvas>").get(0); _this.$el.append(_this.canvas); if (typeof G_vmlCanvasManager !== "undefined" && G_vmlCanvasManager !== null) { G_vmlCanvasManager.initElement(_this.canvas); } _this.ctx = _this.canvas.getContext('2d'); if (window.devicePixelRatio > 1) { scaleBy = window.devicePixelRatio; $(_this.canvas).css({ width: _this.options.size, height: _this.options.size }); _this.canvas.width *= scaleBy; _this.canvas.height *= scaleBy; _this.ctx.scale(scaleBy, scaleBy); } _this.ctx.translate(_this.options.size / 2, _this.options.size / 2); _this.ctx.rotate(_this.options.rotate * Math.PI / 180); _this.$el.addClass('easyPieChart'); _this.$el.css({ width: _this.options.size, height: _this.options.size, lineHeight: "" + _this.options.size + "px" }); _this.update(percent); return _this; }; this.update = function(percent) { percent = parseFloat(percent) || 0; if (_this.options.animate === false) { drawLine(percent); } else { animateLine(_this.percentage, percent); } return _this; }; renderScale = function() { var i, _i, _results; _this.ctx.fillStyle = _this.options.scaleColor; _this.ctx.lineWidth = 1; _results = []; for (i = _i = 0; _i <= 24; i = ++_i) { _results.push(addScaleLine(i)); } return _results; }; addScaleLine = function(i) { var offset; offset = i % 6 === 0 ? 0 : _this.options.size * 0.017; _this.ctx.save(); _this.ctx.rotate(i * Math.PI / 12); _this.ctx.fillRect(_this.options.size / 2 - offset, 0, -_this.options.size * 0.05 + offset, 1); _this.ctx.restore(); }; renderTrack = function() { var offset; offset = _this.options.size / 2 - _this.options.lineWidth / 2; if (_this.options.scaleColor !== false) { offset -= _this.options.size * 0.08; } _this.ctx.beginPath(); _this.ctx.arc(0, 0, offset, 0, Math.PI * 2, true); _this.ctx.closePath(); _this.ctx.strokeStyle = _this.options.trackColor; _this.ctx.lineWidth = _this.options.lineWidth; _this.ctx.stroke(); }; renderBackground = function() { if (_this.options.scaleColor !== false) { renderScale(); } if (_this.options.trackColor !== false) { renderTrack(); } }; drawLine = function(percent) { var offset; renderBackground(); _this.ctx.strokeStyle = $.isFunction(_this.options.barColor) ? _this.options.barColor(percent) : _this.options.barColor; _this.ctx.lineCap = _this.options.lineCap; _this.ctx.lineWidth = _this.options.lineWidth; offset = _this.options.size / 2 - _this.options.lineWidth / 2; if (_this.options.scaleColor !== false) { offset -= _this.options.size * 0.08; } _this.ctx.save(); _this.ctx.rotate(-Math.PI / 2); _this.ctx.beginPath(); _this.ctx.arc(0, 0, offset, 0, Math.PI * 2 * percent / 100, false); _this.ctx.stroke(); _this.ctx.restore(); }; rAF = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { return window.setTimeout(callback, 1000 / 60); }; })(); animateLine = function(from, to) { var anim, startTime; _this.options.onStart.call(_this); _this.percentage = to; startTime = Date.now(); anim = function() { var currentValue, process; process = Date.now() - startTime; if (process < _this.options.animate) { rAF(anim); } _this.ctx.clearRect(-_this.options.size / 2, -_this.options.size / 2, _this.options.size, _this.options.size); renderBackground.call(_this); currentValue = [easeInOutQuad(process, from, to - from, _this.options.animate)]; _this.options.onStep.call(_this, currentValue); drawLine.call(_this, currentValue); if (process >= _this.options.animate) { return _this.options.onStop.call(_this); } }; rAF(anim); }; easeInOutQuad = function(t, b, c, d) { var easeIn, easing; easeIn = function(t) { return Math.pow(t, 2); }; easing = function(t) { if (t < 1) { return easeIn(t); } else { return 2 - easeIn((t / 2) * -2 + 2); } }; t /= d / 2; return c / 2 * easing(t) + b; }; return this.init(); }; $.easyPieChart.defaultOptions = { barColor: '#ef1e25', trackColor: '#f2f2f2', scaleColor: '#dfe0e0', lineCap: 'round', rotate: 0, size: 110, lineWidth: 3, animate: false, onStart: $.noop, onStop: $.noop, onStep: $.noop }; $.fn.easyPieChart = function(options) { return $.each(this, function(i, el) { var $el, instanceOptions; $el = $(el); if (!$el.data('easyPieChart')) { instanceOptions = $.extend({}, options, $el.data()); return $el.data('easyPieChart', new $.easyPieChart(el, instanceOptions)); } }); }; return void 0; })(jQuery);PK ɫ�Zb�� piegage/piegage.cssnu �[��� /* Pie gauge */ .easyPieChart { position: relative; text-align: center; margin-left: auto; margin-right: auto; } .easyPieChart canvas { position: absolute; top: 0; left: 0; } .chart-home, .chart, .chart-alt, .chart-alt-1, .chart-alt-2, .chart-alt-3 { text-align: center; font-weight: bold; margin: 0 auto; } /* Flot charts */ .chart-wrapper { width: 100%; height: 350px; } .chart-container { width: 100%; height: 100%; font-size: 14px; line-height: 1.2em; }PK ɫ�ZJB�՚$ �$ chart-js/chart-bar.jsnu �[��� (function(){ "use strict"; var root = this, Chart = root.Chart, helpers = Chart.helpers; var defaultConfig = { //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value scaleBeginAtZero : true, //Boolean - Whether grid lines are shown across the chart scaleShowGridLines : true, //String - Colour of the grid lines scaleGridLineColor : "rgba(0,0,0,.05)", //Number - Width of the grid lines scaleGridLineWidth : 1, //Boolean - If there is a stroke on each bar barShowStroke : true, //Number - Pixel width of the bar stroke barStrokeWidth : 2, //Number - Spacing between each of the X value sets barValueSpacing : 5, //Number - Spacing between data sets within X values barDatasetSpacing : 1, //String - A legend template legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>" }; Chart.Type.extend({ name: "Bar", defaults : defaultConfig, initialize: function(data){ //Expose options as a scope variable here so we can access it in the ScaleClass var options = this.options; this.ScaleClass = Chart.Scale.extend({ offsetGridLines : true, calculateBarX : function(datasetCount, datasetIndex, barIndex){ //Reusable method for calculating the xPosition of a given bar based on datasetIndex & width of the bar var xWidth = this.calculateBaseWidth(), xAbsolute = this.calculateX(barIndex) - (xWidth/2), barWidth = this.calculateBarWidth(datasetCount); return xAbsolute + (barWidth * datasetIndex) + (datasetIndex * options.barDatasetSpacing) + barWidth/2; }, calculateBaseWidth : function(){ return (this.calculateX(1) - this.calculateX(0)) - (2*options.barValueSpacing); }, calculateBarWidth : function(datasetCount){ //The padding between datasets is to the right of each bar, providing that there are more than 1 dataset var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing); return (baseWidth / datasetCount); } }); this.datasets = []; //Set up tooltip events on the chart if (this.options.showTooltips){ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){ var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : []; this.eachBars(function(bar){ bar.restore(['fillColor', 'strokeColor']); }); helpers.each(activeBars, function(activeBar){ activeBar.fillColor = activeBar.highlightFill; activeBar.strokeColor = activeBar.highlightStroke; }); this.showTooltip(activeBars); }); } //Declare the extension of the default point, to cater for the options passed in to the constructor this.BarClass = Chart.Rectangle.extend({ strokeWidth : this.options.barStrokeWidth, showStroke : this.options.barShowStroke, ctx : this.chart.ctx }); //Iterate through each of the datasets, and build this into a property of the chart helpers.each(data.datasets,function(dataset,datasetIndex){ var datasetObject = { label : dataset.label || null, fillColor : dataset.fillColor, strokeColor : dataset.strokeColor, bars : [] }; this.datasets.push(datasetObject); helpers.each(dataset.data,function(dataPoint,index){ //Add a new point for each piece of data, passing any required data to draw. datasetObject.bars.push(new this.BarClass({ value : dataPoint, label : data.labels[index], datasetLabel: dataset.label, strokeColor : dataset.strokeColor, fillColor : dataset.fillColor, highlightFill : dataset.highlightFill || dataset.fillColor, highlightStroke : dataset.highlightStroke || dataset.strokeColor })); },this); },this); this.buildScale(data.labels); this.BarClass.prototype.base = this.scale.endPoint; this.eachBars(function(bar, index, datasetIndex){ helpers.extend(bar, { width : this.scale.calculateBarWidth(this.datasets.length), x: this.scale.calculateBarX(this.datasets.length, datasetIndex, index), y: this.scale.endPoint }); bar.save(); }, this); this.render(); }, update : function(){ this.scale.update(); // Reset any highlight colours before updating. helpers.each(this.activeElements, function(activeElement){ activeElement.restore(['fillColor', 'strokeColor']); }); this.eachBars(function(bar){ bar.save(); }); this.render(); }, eachBars : function(callback){ helpers.each(this.datasets,function(dataset, datasetIndex){ helpers.each(dataset.bars, callback, this, datasetIndex); },this); }, getBarsAtEvent : function(e){ var barsArray = [], eventPosition = helpers.getRelativePosition(e), datasetIterator = function(dataset){ barsArray.push(dataset.bars[barIndex]); }, barIndex; for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) { for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) { if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){ helpers.each(this.datasets, datasetIterator); return barsArray; } } } return barsArray; }, buildScale : function(labels){ var self = this; var dataTotal = function(){ var values = []; self.eachBars(function(bar){ values.push(bar.value); }); return values; }; var scaleOptions = { templateString : this.options.scaleLabel, height : this.chart.height, width : this.chart.width, ctx : this.chart.ctx, textColor : this.options.scaleFontColor, fontSize : this.options.scaleFontSize, fontStyle : this.options.scaleFontStyle, fontFamily : this.options.scaleFontFamily, valuesCount : labels.length, beginAtZero : this.options.scaleBeginAtZero, integersOnly : this.options.scaleIntegersOnly, calculateYRange: function(currentHeight){ var updatedRanges = helpers.calculateScaleRange( dataTotal(), currentHeight, this.fontSize, this.beginAtZero, this.integersOnly ); helpers.extend(this, updatedRanges); }, xLabels : labels, font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily), lineWidth : this.options.scaleLineWidth, lineColor : this.options.scaleLineColor, gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0, gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)", padding : (this.options.showScale) ? 0 : (this.options.barShowStroke) ? this.options.barStrokeWidth : 0, showLabels : this.options.scaleShowLabels, display : this.options.showScale }; if (this.options.scaleOverride){ helpers.extend(scaleOptions, { calculateYRange: helpers.noop, steps: this.options.scaleSteps, stepValue: this.options.scaleStepWidth, min: this.options.scaleStartValue, max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth) }); } this.scale = new this.ScaleClass(scaleOptions); }, addData : function(valuesArray,label){ //Map the values array for each of the datasets helpers.each(valuesArray,function(value,datasetIndex){ //Add a new point for each piece of data, passing any required data to draw. this.datasets[datasetIndex].bars.push(new this.BarClass({ value : value, label : label, x: this.scale.calculateBarX(this.datasets.length, datasetIndex, this.scale.valuesCount+1), y: this.scale.endPoint, width : this.scale.calculateBarWidth(this.datasets.length), base : this.scale.endPoint, strokeColor : this.datasets[datasetIndex].strokeColor, fillColor : this.datasets[datasetIndex].fillColor })); },this); this.scale.addXLabel(label); //Then re-render the chart. this.update(); }, removeData : function(){ this.scale.removeXLabel(); //Then re-render the chart. helpers.each(this.datasets,function(dataset){ dataset.bars.shift(); },this); this.update(); }, reflow : function(){ helpers.extend(this.BarClass.prototype,{ y: this.scale.endPoint, base : this.scale.endPoint }); var newScaleProps = helpers.extend({ height : this.chart.height, width : this.chart.width }); this.scale.update(newScaleProps); }, draw : function(ease){ var easingDecimal = ease || 1; this.clear(); var ctx = this.chart.ctx; this.scale.draw(easingDecimal); //Draw all the bars for each dataset helpers.each(this.datasets,function(dataset,datasetIndex){ helpers.each(dataset.bars,function(bar,index){ if (bar.hasValue()){ bar.base = this.scale.endPoint; //Transition then draw bar.transition({ x : this.scale.calculateBarX(this.datasets.length, datasetIndex, index), y : this.scale.calculateY(bar.value), width : this.scale.calculateBarWidth(this.datasets.length) }, easingDecimal).draw(); } },this); },this); } }); }).call(this);PK ɫ�Zn��i'