UNPKG

c3

Version:

D3-based reusable chart library

1,786 lines (1,683 loc) 388 kB
/* @license C3.js v0.7.18 | (c) C3 Team and other contributors | http://c3js.org/ */ import * as d3 from 'd3'; function ChartInternal(api) { var $$ = this; // Note: This part will be replaced by rollup-plugin-modify // When bundling esm output. Beware of changing this line. // TODO: Maybe we should check that the modification by rollup-plugin-modify // is valid during unit tests. $$.d3 = window.d3 ? window.d3 : typeof require !== 'undefined' ? require('d3') : undefined; $$.api = api; $$.config = $$.getDefaultConfig(); $$.data = {}; $$.cache = {}; $$.axes = {}; } /** * The Chart class * * The methods of this class is the public APIs of the chart object. */ function Chart(config) { this.internal = new ChartInternal(this); this.internal.loadConfig(config); this.internal.beforeInit(config); this.internal.init(); this.internal.afterInit(config) // bind "this" to nested API ;(function bindThis(fn, target, argThis) { Object.keys(fn).forEach(function(key) { target[key] = fn[key].bind(argThis); if (Object.keys(fn[key]).length > 0) { bindThis(fn[key], target[key], argThis); } }); })(Chart.prototype, this, this); } var asHalfPixel = function(n) { return Math.ceil(n) + 0.5 }; var ceil10 = function(v) { return Math.ceil(v / 10) * 10 }; var diffDomain = function(d) { return d[1] - d[0] }; var getOption = function(options, key, defaultValue) { return isDefined(options[key]) ? options[key] : defaultValue }; var getPathBox = function(path) { var box = getBBox(path), items = [path.pathSegList.getItem(0), path.pathSegList.getItem(1)], minX = items[0].x, minY = Math.min(items[0].y, items[1].y); return { x: minX, y: minY, width: box.width, height: box.height } }; var getBBox = function(element) { try { return element.getBBox() } catch (ignore) { // Firefox will throw an exception if getBBox() is called whereas the // element is rendered with display:none // See https://github.com/c3js/c3/issues/2692 // The previous code was using `getBoundingClientRect` which was returning // everything at 0 in this case so let's reproduce this behavior here. return { x: 0, y: 0, width: 0, height: 0 } } }; var hasValue = function(dict, value) { var found = false; Object.keys(dict).forEach(function(key) { if (dict[key] === value) { found = true; } }); return found }; var isArray = function(o) { return Array.isArray(o) }; var isDefined = function(v) { return typeof v !== 'undefined' }; var isEmpty = function(o) { return ( typeof o === 'undefined' || o === null || (isString(o) && o.length === 0) || (typeof o === 'object' && Object.keys(o).length === 0) ) }; var isFunction = function(o) { return typeof o === 'function' }; var isNumber = function(o) { return typeof o === 'number' }; var isString = function(o) { return typeof o === 'string' }; var isUndefined = function(v) { return typeof v === 'undefined' }; var isValue = function(v) { return v || v === 0 }; var notEmpty = function(o) { return !isEmpty(o) }; var sanitise = function(str) { return typeof str === 'string' ? str.replace(/</g, '&lt;').replace(/>/g, '&gt;') : str }; var flattenArray = function(arr) { return Array.isArray(arr) ? [].concat(...arr) : [] }; /** * Returns whether the point is within the given box. * * @param {Array} point An [x,y] coordinate * @param {Object} box An object with {x, y, width, height} keys * @param {Number} sensitivity An offset to ease check on very small boxes */ var isWithinBox = function(point, box, sensitivity = 0) { const xStart = box.x - sensitivity; const xEnd = box.x + box.width + sensitivity; const yStart = box.y + box.height + sensitivity; const yEnd = box.y - sensitivity; return ( xStart < point[0] && point[0] < xEnd && yEnd < point[1] && point[1] < yStart ) }; /** * Returns Internet Explorer version number (or false if no Internet Explorer used). * * @param string agent Optional parameter to specify user agent */ var getIEVersion = function(agent) { // https://stackoverflow.com/questions/19999388/check-if-user-is-using-ie if (typeof agent === 'undefined') { agent = window.navigator.userAgent; } let pos = agent.indexOf('MSIE '); // up to IE10 if (pos > 0) { return parseInt(agent.substring(pos + 5, agent.indexOf('.', pos)), 10) } pos = agent.indexOf('Trident/'); // IE11 if (pos > 0) { pos = agent.indexOf('rv:'); return parseInt(agent.substring(pos + 3, agent.indexOf('.', pos)), 10) } return false }; /** * Returns whether the used browser is Internet Explorer. * * @param {Number} version Optional parameter to specify IE version */ var isIE = function(version) { const ver = getIEVersion(); if (typeof version === 'undefined') { return !!ver } return version === ver }; function AxisInternal(component, params) { var internal = this; internal.component = component; internal.params = params || {}; internal.d3 = component.d3; internal.scale = internal.d3.scaleLinear(); internal.range; internal.orient = 'bottom'; internal.innerTickSize = 6; internal.outerTickSize = this.params.withOuterTick ? 6 : 0; internal.tickPadding = 3; internal.tickValues = null; internal.tickFormat; internal.tickArguments; internal.tickOffset = 0; internal.tickCulling = true; internal.tickCentered; internal.tickTextCharSize; internal.tickTextRotate = internal.params.tickTextRotate; internal.tickLength; internal.axis = internal.generateAxis(); } AxisInternal.prototype.axisX = function(selection, x, tickOffset) { selection.attr('transform', function(d) { return 'translate(' + Math.ceil(x(d) + tickOffset) + ', 0)' }); }; AxisInternal.prototype.axisY = function(selection, y) { selection.attr('transform', function(d) { return 'translate(0,' + Math.ceil(y(d)) + ')' }); }; AxisInternal.prototype.scaleExtent = function(domain) { var start = domain[0], stop = domain[domain.length - 1]; return start < stop ? [start, stop] : [stop, start] }; AxisInternal.prototype.generateTicks = function(scale) { var internal = this; var i, domain, ticks = []; if (scale.ticks) { return scale.ticks.apply(scale, internal.tickArguments) } domain = scale.domain(); for (i = Math.ceil(domain[0]); i < domain[1]; i++) { ticks.push(i); } if (ticks.length > 0 && ticks[0] > 0) { ticks.unshift(ticks[0] - (ticks[1] - ticks[0])); } return ticks }; AxisInternal.prototype.copyScale = function() { var internal = this; var newScale = internal.scale.copy(), domain; if (internal.params.isCategory) { domain = internal.scale.domain(); newScale.domain([domain[0], domain[1] - 1]); } return newScale }; AxisInternal.prototype.textFormatted = function(v) { var internal = this, formatted = internal.tickFormat ? internal.tickFormat(v) : v; return typeof formatted !== 'undefined' ? formatted : '' }; AxisInternal.prototype.updateRange = function() { var internal = this; internal.range = internal.scale.rangeExtent ? internal.scale.rangeExtent() : internal.scaleExtent(internal.scale.range()); return internal.range }; AxisInternal.prototype.updateTickTextCharSize = function(tick) { var internal = this; if (internal.tickTextCharSize) { return internal.tickTextCharSize } var size = { h: 11.5, w: 5.5 }; tick .select('text') .text(function(d) { return internal.textFormatted(d) }) .each(function(d) { var box = getBBox(this), text = internal.textFormatted(d), h = box.height, w = text ? box.width / text.length : undefined; if (h && w) { size.h = h; size.w = w; } }) .text(''); internal.tickTextCharSize = size; return size }; AxisInternal.prototype.isVertical = function() { return this.orient === 'left' || this.orient === 'right' }; AxisInternal.prototype.tspanData = function(d, i, scale) { var internal = this; var splitted = internal.params.tickMultiline ? internal.splitTickText(d, scale) : [].concat(internal.textFormatted(d)); if (internal.params.tickMultiline && internal.params.tickMultilineMax > 0) { splitted = internal.ellipsify(splitted, internal.params.tickMultilineMax); } return splitted.map(function(s) { return { index: i, splitted: s, length: splitted.length } }) }; AxisInternal.prototype.splitTickText = function(d, scale) { var internal = this, tickText = internal.textFormatted(d), maxWidth = internal.params.tickWidth, subtext, spaceIndex, textWidth, splitted = []; if (Object.prototype.toString.call(tickText) === '[object Array]') { return tickText } if (!maxWidth || maxWidth <= 0) { maxWidth = internal.isVertical() ? 95 : internal.params.isCategory ? Math.ceil(scale(1) - scale(0)) - 12 : 110; } function split(splitted, text) { spaceIndex = undefined; for (var i = 1; i < text.length; i++) { if (text.charAt(i) === ' ') { spaceIndex = i; } subtext = text.substr(0, i + 1); textWidth = internal.tickTextCharSize.w * subtext.length; // if text width gets over tick width, split by space index or crrent index if (maxWidth < textWidth) { return split( splitted.concat(text.substr(0, spaceIndex ? spaceIndex : i)), text.slice(spaceIndex ? spaceIndex + 1 : i) ) } } return splitted.concat(text) } return split(splitted, tickText + '') }; AxisInternal.prototype.ellipsify = function(splitted, max) { if (splitted.length <= max) { return splitted } var ellipsified = splitted.slice(0, max); var remaining = 3; for (var i = max - 1; i >= 0; i--) { var available = ellipsified[i].length; ellipsified[i] = ellipsified[i] .substr(0, available - remaining) .padEnd(available, '.'); remaining -= available; if (remaining <= 0) { break } } return ellipsified }; AxisInternal.prototype.updateTickLength = function() { var internal = this; internal.tickLength = Math.max(internal.innerTickSize, 0) + internal.tickPadding; }; AxisInternal.prototype.lineY2 = function(d) { var internal = this, tickPosition = internal.scale(d) + (internal.tickCentered ? 0 : internal.tickOffset); return internal.range[0] < tickPosition && tickPosition < internal.range[1] ? internal.innerTickSize : 0 }; AxisInternal.prototype.textY = function() { var internal = this, rotate = internal.tickTextRotate; return rotate ? 11.5 - 2.5 * (rotate / 15) * (rotate > 0 ? 1 : -1) : internal.tickLength }; AxisInternal.prototype.textTransform = function() { var internal = this, rotate = internal.tickTextRotate; return rotate ? 'rotate(' + rotate + ')' : '' }; AxisInternal.prototype.textTextAnchor = function() { var internal = this, rotate = internal.tickTextRotate; return rotate ? (rotate > 0 ? 'start' : 'end') : 'middle' }; AxisInternal.prototype.tspanDx = function() { var internal = this, rotate = internal.tickTextRotate; return rotate ? 8 * Math.sin(Math.PI * (rotate / 180)) : 0 }; AxisInternal.prototype.tspanDy = function(d, i) { var internal = this, dy = internal.tickTextCharSize.h; if (i === 0) { if (internal.isVertical()) { dy = -((d.length - 1) * (internal.tickTextCharSize.h / 2) - 3); } else { dy = '.71em'; } } return dy }; AxisInternal.prototype.generateAxis = function() { var internal = this, d3 = internal.d3, params = internal.params; function axis(g, transition) { var self; g.each(function() { var g = (axis.g = d3.select(this)); var scale0 = this.__chart__ || internal.scale, scale1 = (this.__chart__ = internal.copyScale()); var ticksValues = internal.tickValues ? internal.tickValues : internal.generateTicks(scale1), ticks = g.selectAll('.tick').data(ticksValues, scale1), tickEnter = ticks .enter() .insert('g', '.domain') .attr('class', 'tick') .style('opacity', 1e-6), // MEMO: No exit transition. The reason is this transition affects max tick width calculation because old tick will be included in the ticks. tickExit = ticks.exit().remove(), tickUpdate = ticks.merge(tickEnter), tickTransform, tickX, tickY; if (params.isCategory) { internal.tickOffset = Math.ceil((scale1(1) - scale1(0)) / 2); tickX = internal.tickCentered ? 0 : internal.tickOffset; tickY = internal.tickCentered ? internal.tickOffset : 0; } else { internal.tickOffset = tickX = 0; } internal.updateRange(); internal.updateTickLength(); internal.updateTickTextCharSize(g.select('.tick')); var lineUpdate = tickUpdate .select('line') .merge(tickEnter.append('line')), textUpdate = tickUpdate.select('text').merge(tickEnter.append('text')); var tspans = tickUpdate .selectAll('text') .selectAll('tspan') .data(function(d, i) { return internal.tspanData(d, i, scale1) }), tspanEnter = tspans.enter().append('tspan'), tspanUpdate = tspanEnter.merge(tspans).text(function(d) { return d.splitted }); tspans.exit().remove(); var path = g.selectAll('.domain').data([0]), pathUpdate = path .enter() .append('path') .merge(path) .attr('class', 'domain'); // TODO: each attr should be one function and change its behavior by internal.orient, probably switch (internal.orient) { case 'bottom': { tickTransform = internal.axisX; lineUpdate .attr('x1', tickX) .attr('x2', tickX) .attr('y2', function(d, i) { return internal.lineY2(d, i) }); textUpdate .attr('x', 0) .attr('y', function(d, i) { return internal.textY(d, i) }) .attr('transform', function(d, i) { return internal.textTransform(d, i) }) .style('text-anchor', function(d, i) { return internal.textTextAnchor(d, i) }); tspanUpdate .attr('x', 0) .attr('dy', function(d, i) { return internal.tspanDy(d, i) }) .attr('dx', function(d, i) { return internal.tspanDx(d, i) }); pathUpdate.attr( 'd', 'M' + internal.range[0] + ',' + internal.outerTickSize + 'V0H' + internal.range[1] + 'V' + internal.outerTickSize ); break } case 'top': { // TODO: rotated tick text tickTransform = internal.axisX; lineUpdate .attr('x1', tickX) .attr('x2', tickX) .attr('y2', function(d, i) { return -1 * internal.lineY2(d, i) }); textUpdate .attr('x', 0) .attr('y', function(d, i) { return ( -1 * internal.textY(d, i) - (params.isCategory ? 2 : internal.tickLength - 2) ) }) .attr('transform', function(d, i) { return internal.textTransform(d, i) }) .style('text-anchor', function(d, i) { return internal.textTextAnchor(d, i) }); tspanUpdate .attr('x', 0) .attr('dy', function(d, i) { return internal.tspanDy(d, i) }) .attr('dx', function(d, i) { return internal.tspanDx(d, i) }); pathUpdate.attr( 'd', 'M' + internal.range[0] + ',' + -internal.outerTickSize + 'V0H' + internal.range[1] + 'V' + -internal.outerTickSize ); break } case 'left': { tickTransform = internal.axisY; lineUpdate .attr('x2', -internal.innerTickSize) .attr('y1', tickY) .attr('y2', tickY); textUpdate .attr('x', -internal.tickLength) .attr('y', internal.tickOffset) .style('text-anchor', 'end'); tspanUpdate .attr('x', -internal.tickLength) .attr('dy', function(d, i) { return internal.tspanDy(d, i) }); pathUpdate.attr( 'd', 'M' + -internal.outerTickSize + ',' + internal.range[0] + 'H0V' + internal.range[1] + 'H' + -internal.outerTickSize ); break } case 'right': { tickTransform = internal.axisY; lineUpdate .attr('x2', internal.innerTickSize) .attr('y1', tickY) .attr('y2', tickY); textUpdate .attr('x', internal.tickLength) .attr('y', internal.tickOffset) .style('text-anchor', 'start'); tspanUpdate.attr('x', internal.tickLength).attr('dy', function(d, i) { return internal.tspanDy(d, i) }); pathUpdate.attr( 'd', 'M' + internal.outerTickSize + ',' + internal.range[0] + 'H0V' + internal.range[1] + 'H' + internal.outerTickSize ); break } } if (scale1.rangeBand) { var x = scale1, dx = x.rangeBand() / 2; scale0 = scale1 = function(d) { return x(d) + dx }; } else if (scale0.rangeBand) { scale0 = scale1; } else { tickExit.call(tickTransform, scale1, internal.tickOffset); } tickEnter.call(tickTransform, scale0, internal.tickOffset); self = (transition ? tickUpdate.transition(transition) : tickUpdate) .style('opacity', 1) .call(tickTransform, scale1, internal.tickOffset); }); return self } axis.scale = function(x) { if (!arguments.length) { return internal.scale } internal.scale = x; return axis }; axis.orient = function(x) { if (!arguments.length) { return internal.orient } internal.orient = x in { top: 1, right: 1, bottom: 1, left: 1 } ? x + '' : 'bottom'; return axis }; axis.tickFormat = function(format) { if (!arguments.length) { return internal.tickFormat } internal.tickFormat = format; return axis }; axis.tickCentered = function(isCentered) { if (!arguments.length) { return internal.tickCentered } internal.tickCentered = isCentered; return axis }; axis.tickOffset = function() { return internal.tickOffset }; axis.tickInterval = function() { var interval, length; if (params.isCategory) { interval = internal.tickOffset * 2; } else { length = axis.g .select('path.domain') .node() .getTotalLength() - internal.outerTickSize * 2; interval = length / axis.g.selectAll('line').size(); } return interval === Infinity ? 0 : interval }; axis.ticks = function() { if (!arguments.length) { return internal.tickArguments } internal.tickArguments = arguments; return axis }; axis.tickCulling = function(culling) { if (!arguments.length) { return internal.tickCulling } internal.tickCulling = culling; return axis }; axis.tickValues = function(x) { if (typeof x === 'function') { internal.tickValues = function() { return x(internal.scale.domain()) }; } else { if (!arguments.length) { return internal.tickValues } internal.tickValues = x; } return axis }; return axis }; var CLASS = { target: 'c3-target', chart: 'c3-chart', chartLine: 'c3-chart-line', chartLines: 'c3-chart-lines', chartBar: 'c3-chart-bar', chartBars: 'c3-chart-bars', chartText: 'c3-chart-text', chartTexts: 'c3-chart-texts', chartArc: 'c3-chart-arc', chartArcs: 'c3-chart-arcs', chartArcsTitle: 'c3-chart-arcs-title', chartArcsBackground: 'c3-chart-arcs-background', chartArcsGaugeUnit: 'c3-chart-arcs-gauge-unit', chartArcsGaugeMax: 'c3-chart-arcs-gauge-max', chartArcsGaugeMin: 'c3-chart-arcs-gauge-min', selectedCircle: 'c3-selected-circle', selectedCircles: 'c3-selected-circles', eventRect: 'c3-event-rect', eventRects: 'c3-event-rects', eventRectsSingle: 'c3-event-rects-single', eventRectsMultiple: 'c3-event-rects-multiple', zoomRect: 'c3-zoom-rect', brush: 'c3-brush', dragZoom: 'c3-drag-zoom', focused: 'c3-focused', defocused: 'c3-defocused', region: 'c3-region', regions: 'c3-regions', title: 'c3-title', tooltipContainer: 'c3-tooltip-container', tooltip: 'c3-tooltip', tooltipName: 'c3-tooltip-name', shape: 'c3-shape', shapes: 'c3-shapes', line: 'c3-line', lines: 'c3-lines', bar: 'c3-bar', bars: 'c3-bars', circle: 'c3-circle', circles: 'c3-circles', arc: 'c3-arc', arcLabelLine: 'c3-arc-label-line', arcs: 'c3-arcs', area: 'c3-area', areas: 'c3-areas', empty: 'c3-empty', text: 'c3-text', texts: 'c3-texts', gaugeValue: 'c3-gauge-value', grid: 'c3-grid', gridLines: 'c3-grid-lines', xgrid: 'c3-xgrid', xgrids: 'c3-xgrids', xgridLine: 'c3-xgrid-line', xgridLines: 'c3-xgrid-lines', xgridFocus: 'c3-xgrid-focus', ygrid: 'c3-ygrid', ygrids: 'c3-ygrids', ygridLine: 'c3-ygrid-line', ygridLines: 'c3-ygrid-lines', colorScale: 'c3-colorscale', stanfordElements: 'c3-stanford-elements', stanfordLine: 'c3-stanford-line', stanfordLines: 'c3-stanford-lines', stanfordRegion: 'c3-stanford-region', stanfordRegions: 'c3-stanford-regions', stanfordText: 'c3-stanford-text', stanfordTexts: 'c3-stanford-texts', axis: 'c3-axis', axisX: 'c3-axis-x', axisXLabel: 'c3-axis-x-label', axisY: 'c3-axis-y', axisYLabel: 'c3-axis-y-label', axisY2: 'c3-axis-y2', axisY2Label: 'c3-axis-y2-label', legendBackground: 'c3-legend-background', legendItem: 'c3-legend-item', legendItemEvent: 'c3-legend-item-event', legendItemTile: 'c3-legend-item-tile', legendItemHidden: 'c3-legend-item-hidden', legendItemFocused: 'c3-legend-item-focused', dragarea: 'c3-dragarea', EXPANDED: '_expanded_', SELECTED: '_selected_', INCLUDED: '_included_' }; class Axis { constructor(owner) { this.owner = owner; this.d3 = owner.d3; this.internal = AxisInternal; } } Axis.prototype.init = function init() { var $$ = this.owner, config = $$.config, main = $$.main; $$.axes.x = main .append('g') .attr('class', CLASS.axis + ' ' + CLASS.axisX) .attr('clip-path', config.axis_x_inner ? '' : $$.clipPathForXAxis) .attr('transform', $$.getTranslate('x')) .style('visibility', config.axis_x_show ? 'visible' : 'hidden'); $$.axes.x .append('text') .attr('class', CLASS.axisXLabel) .attr('transform', config.axis_rotated ? 'rotate(-90)' : '') .style('text-anchor', this.textAnchorForXAxisLabel.bind(this)); $$.axes.y = main .append('g') .attr('class', CLASS.axis + ' ' + CLASS.axisY) .attr('clip-path', config.axis_y_inner ? '' : $$.clipPathForYAxis) .attr('transform', $$.getTranslate('y')) .style('visibility', config.axis_y_show ? 'visible' : 'hidden'); $$.axes.y .append('text') .attr('class', CLASS.axisYLabel) .attr('transform', config.axis_rotated ? '' : 'rotate(-90)') .style('text-anchor', this.textAnchorForYAxisLabel.bind(this)); $$.axes.y2 = main .append('g') .attr('class', CLASS.axis + ' ' + CLASS.axisY2) // clip-path? .attr('transform', $$.getTranslate('y2')) .style('visibility', config.axis_y2_show ? 'visible' : 'hidden'); $$.axes.y2 .append('text') .attr('class', CLASS.axisY2Label) .attr('transform', config.axis_rotated ? '' : 'rotate(-90)') .style('text-anchor', this.textAnchorForY2AxisLabel.bind(this)); }; Axis.prototype.getXAxis = function getXAxis( scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText ) { var $$ = this.owner, config = $$.config, axisParams = { isCategory: $$.isCategorized(), withOuterTick: withOuterTick, tickMultiline: config.axis_x_tick_multiline, tickMultilineMax: config.axis_x_tick_multiline ? Number(config.axis_x_tick_multilineMax) : 0, tickWidth: config.axis_x_tick_width, tickTextRotate: withoutRotateTickText ? 0 : config.axis_x_tick_rotate, withoutTransition: withoutTransition }, axis = new this.internal(this, axisParams).axis.scale(scale).orient(orient); if ($$.isTimeSeries() && tickValues && typeof tickValues !== 'function') { tickValues = tickValues.map(function(v) { return $$.parseDate(v) }); } // Set tick axis.tickFormat(tickFormat).tickValues(tickValues); if ($$.isCategorized()) { axis.tickCentered(config.axis_x_tick_centered); if (isEmpty(config.axis_x_tick_culling)) { config.axis_x_tick_culling = false; } } return axis }; Axis.prototype.updateXAxisTickValues = function updateXAxisTickValues( targets, axis ) { var $$ = this.owner, config = $$.config, tickValues; if (config.axis_x_tick_fit || config.axis_x_tick_count) { tickValues = this.generateTickValues( $$.mapTargetsToUniqueXs(targets), config.axis_x_tick_count, $$.isTimeSeries() ); } if (axis) { axis.tickValues(tickValues); } else { $$.xAxis.tickValues(tickValues); $$.subXAxis.tickValues(tickValues); } return tickValues }; Axis.prototype.getYAxis = function getYAxis( axisId, scale, orient, tickValues, withOuterTick, withoutTransition, withoutRotateTickText ) { const $$ = this.owner; const config = $$.config; let tickFormat = config[`axis_${axisId}_tick_format`]; if (!tickFormat && $$.isAxisNormalized(axisId)) { tickFormat = x => `${x}%`; } const axis = new this.internal(this, { withOuterTick: withOuterTick, withoutTransition: withoutTransition, tickTextRotate: withoutRotateTickText ? 0 : config.axis_y_tick_rotate }).axis .scale(scale) .orient(orient); if (tickFormat) { axis.tickFormat(tickFormat); } if ($$.isTimeSeriesY()) { axis.ticks(config.axis_y_tick_time_type, config.axis_y_tick_time_interval); } else { axis.tickValues(tickValues); } return axis }; Axis.prototype.getId = function getId(id) { var config = this.owner.config; return id in config.data_axes ? config.data_axes[id] : 'y' }; Axis.prototype.getXAxisTickFormat = function getXAxisTickFormat() { // #2251 previously set any negative values to a whole number, // however both should be truncated according to the users format specification var $$ = this.owner, config = $$.config; let format = $$.isTimeSeries() ? $$.defaultAxisTimeFormat : $$.isCategorized() ? $$.categoryName : function(v) { return v }; if (config.axis_x_tick_format) { if (isFunction(config.axis_x_tick_format)) { format = config.axis_x_tick_format; } else if ($$.isTimeSeries()) { format = function(date) { return date ? $$.axisTimeFormat(config.axis_x_tick_format)(date) : '' }; } } return isFunction(format) ? function(v) { return format.call($$, v) } : format }; Axis.prototype.getTickValues = function getTickValues(tickValues, axis) { return tickValues ? tickValues : axis ? axis.tickValues() : undefined }; Axis.prototype.getXAxisTickValues = function getXAxisTickValues() { return this.getTickValues( this.owner.config.axis_x_tick_values, this.owner.xAxis ) }; Axis.prototype.getYAxisTickValues = function getYAxisTickValues() { return this.getTickValues( this.owner.config.axis_y_tick_values, this.owner.yAxis ) }; Axis.prototype.getY2AxisTickValues = function getY2AxisTickValues() { return this.getTickValues( this.owner.config.axis_y2_tick_values, this.owner.y2Axis ) }; Axis.prototype.getLabelOptionByAxisId = function getLabelOptionByAxisId( axisId ) { var $$ = this.owner, config = $$.config, option; if (axisId === 'y') { option = config.axis_y_label; } else if (axisId === 'y2') { option = config.axis_y2_label; } else if (axisId === 'x') { option = config.axis_x_label; } return option }; Axis.prototype.getLabelText = function getLabelText(axisId) { var option = this.getLabelOptionByAxisId(axisId); return isString(option) ? option : option ? option.text : null }; Axis.prototype.setLabelText = function setLabelText(axisId, text) { var $$ = this.owner, config = $$.config, option = this.getLabelOptionByAxisId(axisId); if (isString(option)) { if (axisId === 'y') { config.axis_y_label = text; } else if (axisId === 'y2') { config.axis_y2_label = text; } else if (axisId === 'x') { config.axis_x_label = text; } } else if (option) { option.text = text; } }; Axis.prototype.getLabelPosition = function getLabelPosition( axisId, defaultPosition ) { var option = this.getLabelOptionByAxisId(axisId), position = option && typeof option === 'object' && option.position ? option.position : defaultPosition; return { isInner: position.indexOf('inner') >= 0, isOuter: position.indexOf('outer') >= 0, isLeft: position.indexOf('left') >= 0, isCenter: position.indexOf('center') >= 0, isRight: position.indexOf('right') >= 0, isTop: position.indexOf('top') >= 0, isMiddle: position.indexOf('middle') >= 0, isBottom: position.indexOf('bottom') >= 0 } }; Axis.prototype.getXAxisLabelPosition = function getXAxisLabelPosition() { return this.getLabelPosition( 'x', this.owner.config.axis_rotated ? 'inner-top' : 'inner-right' ) }; Axis.prototype.getYAxisLabelPosition = function getYAxisLabelPosition() { return this.getLabelPosition( 'y', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top' ) }; Axis.prototype.getY2AxisLabelPosition = function getY2AxisLabelPosition() { return this.getLabelPosition( 'y2', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top' ) }; Axis.prototype.getLabelPositionById = function getLabelPositionById(id) { return id === 'y2' ? this.getY2AxisLabelPosition() : id === 'y' ? this.getYAxisLabelPosition() : this.getXAxisLabelPosition() }; Axis.prototype.textForXAxisLabel = function textForXAxisLabel() { return this.getLabelText('x') }; Axis.prototype.textForYAxisLabel = function textForYAxisLabel() { return this.getLabelText('y') }; Axis.prototype.textForY2AxisLabel = function textForY2AxisLabel() { return this.getLabelText('y2') }; Axis.prototype.xForAxisLabel = function xForAxisLabel(forHorizontal, position) { var $$ = this.owner; if (forHorizontal) { return position.isLeft ? 0 : position.isCenter ? $$.width / 2 : $$.width } else { return position.isBottom ? -$$.height : position.isMiddle ? -$$.height / 2 : 0 } }; Axis.prototype.dxForAxisLabel = function dxForAxisLabel( forHorizontal, position ) { if (forHorizontal) { return position.isLeft ? '0.5em' : position.isRight ? '-0.5em' : '0' } else { return position.isTop ? '-0.5em' : position.isBottom ? '0.5em' : '0' } }; Axis.prototype.textAnchorForAxisLabel = function textAnchorForAxisLabel( forHorizontal, position ) { if (forHorizontal) { return position.isLeft ? 'start' : position.isCenter ? 'middle' : 'end' } else { return position.isBottom ? 'start' : position.isMiddle ? 'middle' : 'end' } }; Axis.prototype.xForXAxisLabel = function xForXAxisLabel() { return this.xForAxisLabel( !this.owner.config.axis_rotated, this.getXAxisLabelPosition() ) }; Axis.prototype.xForYAxisLabel = function xForYAxisLabel() { return this.xForAxisLabel( this.owner.config.axis_rotated, this.getYAxisLabelPosition() ) }; Axis.prototype.xForY2AxisLabel = function xForY2AxisLabel() { return this.xForAxisLabel( this.owner.config.axis_rotated, this.getY2AxisLabelPosition() ) }; Axis.prototype.dxForXAxisLabel = function dxForXAxisLabel() { return this.dxForAxisLabel( !this.owner.config.axis_rotated, this.getXAxisLabelPosition() ) }; Axis.prototype.dxForYAxisLabel = function dxForYAxisLabel() { return this.dxForAxisLabel( this.owner.config.axis_rotated, this.getYAxisLabelPosition() ) }; Axis.prototype.dxForY2AxisLabel = function dxForY2AxisLabel() { return this.dxForAxisLabel( this.owner.config.axis_rotated, this.getY2AxisLabelPosition() ) }; Axis.prototype.dyForXAxisLabel = function dyForXAxisLabel() { var $$ = this.owner, config = $$.config, position = this.getXAxisLabelPosition(); if (config.axis_rotated) { return position.isInner ? '1.2em' : -25 - ($$.config.axis_x_inner ? 0 : this.getMaxTickWidth('x')) } else { return position.isInner ? '-0.5em' : $$.getHorizontalAxisHeight('x') - 10 } }; Axis.prototype.dyForYAxisLabel = function dyForYAxisLabel() { var $$ = this.owner, position = this.getYAxisLabelPosition(); if ($$.config.axis_rotated) { return position.isInner ? '-0.5em' : '3em' } else { return position.isInner ? '1.2em' : -10 - ($$.config.axis_y_inner ? 0 : this.getMaxTickWidth('y') + 10) } }; Axis.prototype.dyForY2AxisLabel = function dyForY2AxisLabel() { var $$ = this.owner, position = this.getY2AxisLabelPosition(); if ($$.config.axis_rotated) { return position.isInner ? '1.2em' : '-2.2em' } else { return position.isInner ? '-0.5em' : 15 + ($$.config.axis_y2_inner ? 0 : this.getMaxTickWidth('y2') + 15) } }; Axis.prototype.textAnchorForXAxisLabel = function textAnchorForXAxisLabel() { var $$ = this.owner; return this.textAnchorForAxisLabel( !$$.config.axis_rotated, this.getXAxisLabelPosition() ) }; Axis.prototype.textAnchorForYAxisLabel = function textAnchorForYAxisLabel() { var $$ = this.owner; return this.textAnchorForAxisLabel( $$.config.axis_rotated, this.getYAxisLabelPosition() ) }; Axis.prototype.textAnchorForY2AxisLabel = function textAnchorForY2AxisLabel() { var $$ = this.owner; return this.textAnchorForAxisLabel( $$.config.axis_rotated, this.getY2AxisLabelPosition() ) }; Axis.prototype.getMaxTickWidth = function getMaxTickWidth( id, withoutRecompute ) { var $$ = this.owner, maxWidth = 0, targetsToShow, scale, axis, dummy, svg; if (withoutRecompute && $$.currentMaxTickWidths[id]) { return $$.currentMaxTickWidths[id] } if ($$.svg) { targetsToShow = $$.filterTargetsToShow($$.data.targets); if (id === 'y') { scale = $$.y.copy().domain($$.getYDomain(targetsToShow, 'y')); axis = this.getYAxis( id, scale, $$.yOrient, $$.yAxisTickValues, false, true, true ); } else if (id === 'y2') { scale = $$.y2.copy().domain($$.getYDomain(targetsToShow, 'y2')); axis = this.getYAxis( id, scale, $$.y2Orient, $$.y2AxisTickValues, false, true, true ); } else { scale = $$.x.copy().domain($$.getXDomain(targetsToShow)); axis = this.getXAxis( scale, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, false, true, true ); this.updateXAxisTickValues(targetsToShow, axis); } dummy = $$.d3 .select('body') .append('div') .classed('c3', true) ;(svg = dummy .append('svg') .style('visibility', 'hidden') .style('position', 'fixed') .style('top', 0) .style('left', 0)), svg .append('g') .call(axis) .each(function() { $$.d3 .select(this) .selectAll('text') .each(function() { var box = getBBox(this); if (maxWidth < box.width) { maxWidth = box.width; } }); dummy.remove(); }); } $$.currentMaxTickWidths[id] = maxWidth <= 0 ? $$.currentMaxTickWidths[id] : maxWidth; return $$.currentMaxTickWidths[id] }; Axis.prototype.updateLabels = function updateLabels(withTransition) { var $$ = this.owner; var axisXLabel = $$.main.select('.' + CLASS.axisX + ' .' + CLASS.axisXLabel), axisYLabel = $$.main.select('.' + CLASS.axisY + ' .' + CLASS.axisYLabel), axisY2Label = $$.main.select('.' + CLASS.axisY2 + ' .' + CLASS.axisY2Label) ;(withTransition ? axisXLabel.transition() : axisXLabel) .attr('x', this.xForXAxisLabel.bind(this)) .attr('dx', this.dxForXAxisLabel.bind(this)) .attr('dy', this.dyForXAxisLabel.bind(this)) .text(this.textForXAxisLabel.bind(this)) ;(withTransition ? axisYLabel.transition() : axisYLabel) .attr('x', this.xForYAxisLabel.bind(this)) .attr('dx', this.dxForYAxisLabel.bind(this)) .attr('dy', this.dyForYAxisLabel.bind(this)) .text(this.textForYAxisLabel.bind(this)) ;(withTransition ? axisY2Label.transition() : axisY2Label) .attr('x', this.xForY2AxisLabel.bind(this)) .attr('dx', this.dxForY2AxisLabel.bind(this)) .attr('dy', this.dyForY2AxisLabel.bind(this)) .text(this.textForY2AxisLabel.bind(this)); }; Axis.prototype.getPadding = function getPadding( padding, key, defaultValue, domainLength ) { var p = typeof padding === 'number' ? padding : padding[key]; if (!isValue(p)) { return defaultValue } if (padding.unit === 'ratio') { return padding[key] * domainLength } // assume padding is pixels if unit is not specified return this.convertPixelsToAxisPadding(p, domainLength) }; Axis.prototype.convertPixelsToAxisPadding = function convertPixelsToAxisPadding( pixels, domainLength ) { var $$ = this.owner, length = $$.config.axis_rotated ? $$.width : $$.height; return domainLength * (pixels / length) }; Axis.prototype.generateTickValues = function generateTickValues( values, tickCount, forTimeSeries ) { var tickValues = values, targetCount, start, end, count, interval, i, tickValue; if (tickCount) { targetCount = isFunction(tickCount) ? tickCount() : tickCount; // compute ticks according to tickCount if (targetCount === 1) { tickValues = [values[0]]; } else if (targetCount === 2) { tickValues = [values[0], values[values.length - 1]]; } else if (targetCount > 2) { count = targetCount - 2; start = values[0]; end = values[values.length - 1]; interval = (end - start) / (count + 1); // re-construct unique values tickValues = [start]; for (i = 0; i < count; i++) { tickValue = +start + interval * (i + 1); tickValues.push(forTimeSeries ? new Date(tickValue) : tickValue); } tickValues.push(end); } } if (!forTimeSeries) { tickValues = tickValues.sort(function(a, b) { return a - b }); } return tickValues }; Axis.prototype.generateTransitions = function generateTransitions(duration) { var $$ = this.owner, axes = $$.axes; return { axisX: duration ? axes.x.transition().duration(duration) : axes.x, axisY: duration ? axes.y.transition().duration(duration) : axes.y, axisY2: duration ? axes.y2.transition().duration(duration) : axes.y2, axisSubX: duration ? axes.subx.transition().duration(duration) : axes.subx } }; Axis.prototype.redraw = function redraw(duration, isHidden) { var $$ = this.owner, transition = duration ? $$.d3.transition().duration(duration) : null; $$.axes.x.style('opacity', isHidden ? 0 : 1).call($$.xAxis, transition); $$.axes.y.style('opacity', isHidden ? 0 : 1).call($$.yAxis, transition); $$.axes.y2.style('opacity', isHidden ? 0 : 1).call($$.y2Axis, transition); $$.axes.subx.style('opacity', isHidden ? 0 : 1).call($$.subXAxis, transition); }; var c3 = { version: '0.7.18', chart: { fn: Chart.prototype, internal: { fn: ChartInternal.prototype, axis: { fn: Axis.prototype, internal: { fn: AxisInternal.prototype } } } }, generate: function(config) { return new Chart(config) } }; ChartInternal.prototype.beforeInit = function() { // can do something }; ChartInternal.prototype.afterInit = function() { // can do something }; ChartInternal.prototype.init = function() { var $$ = this, config = $$.config; $$.initParams(); if (config.data_url) { $$.convertUrlToData( config.data_url, config.data_mimeType, config.data_headers, config.data_keys, $$.initWithData ); } else if (config.data_json) { $$.initWithData($$.convertJsonToData(config.data_json, config.data_keys)); } else if (config.data_rows) { $$.initWithData($$.convertRowsToData(config.data_rows)); } else if (config.data_columns) { $$.initWithData($$.convertColumnsToData(config.data_columns)); } else { throw Error('url or json or rows or columns is required.') } }; ChartInternal.prototype.initParams = function() { var $$ = this, d3 = $$.d3, config = $$.config; // MEMO: clipId needs to be unique because it conflicts when multiple charts exist $$.clipId = 'c3-' + new Date().valueOf() + '-clip'; $$.clipIdForXAxis = $$.clipId + '-xaxis'; $$.clipIdForYAxis = $$.clipId + '-yaxis'; $$.clipIdForGrid = $$.clipId + '-grid'; $$.clipIdForSubchart = $$.clipId + '-subchart'; $$.clipPath = $$.getClipPath($$.clipId); $$.clipPathForXAxis = $$.getClipPath($$.clipIdForXAxis); $$.clipPathForYAxis = $$.getClipPath($$.clipIdForYAxis); $$.clipPathForGrid = $$.getClipPath($$.clipIdForGrid); $$.clipPathForSubchart = $$.getClipPath($$.clipIdForSubchart); $$.dragStart = null; $$.dragging = false; $$.flowing = false; $$.cancelClick = false; $$.mouseover = undefined; $$.transiting = false; $$.color = $$.generateColor(); $$.levelColor = $$.generateLevelColor(); $$.dataTimeParse = (config.data_xLocaltime ? d3.timeParse : d3.utcParse)( $$.config.data_xFormat ); $$.axisTimeFormat = config.axis_x_localtime ? d3.timeFormat : d3.utcFormat; $$.defaultAxisTimeFormat = function(date) { if (date.getMilliseconds()) { return d3.timeFormat('.%L')(date) } if (date.getSeconds()) { return d3.timeFormat(':%S')(date) } if (date.getMinutes()) { return d3.timeFormat('%I:%M')(date) } if (date.getHours()) { return d3.timeFormat('%I %p')(date) } if (date.getDay() && date.getDate() !== 1) { return d3.timeFormat('%-m/%-d')(date) } if (date.getDate() !== 1) { return d3.timeFormat('%-m/%-d')(date) } if (date.getMonth()) { return d3.timeFormat('%-m/%-d')(date) } return d3.timeFormat('%Y/%-m/%-d')(date) }; $$.hiddenTargetIds = []; $$.hiddenLegendIds = []; $$.focusedTargetIds = []; $$.defocusedTargetIds = []; $$.xOrient = config.axis_rotated ? config.axis_x_inner ? 'right' : 'left' : config.axis_x_inner ? 'top' : 'bottom'; $$.yOrient = config.axis_rotated ? config.axis_y_inner ? 'top' : 'bottom' : config.axis_y_inner ? 'right' : 'left'; $$.y2Orient = config.axis_rotated ? config.axis_y2_inner ? 'bottom' : 'top' : config.axis_y2_inner ? 'left' : 'right'; $$.subXOrient = config.axis_rotated ? 'left' : 'bottom'; $$.isLegendRight = config.legend_position === 'right'; $$.isLegendInset = config.legend_position === 'inset'; $$.isLegendTop = config.legend_inset_anchor === 'top-left' || config.legend_inset_anchor === 'top-right'; $$.isLegendLeft = config.legend_inset_anchor === 'top-left' || config.legend_inset_anchor === 'bottom-left'; $$.legendStep = 0; $$.legendItemWidth = 0; $$.legendItemHeight = 0; $$.currentMaxTickWidths = { x: 0, y: 0, y2: 0 }; $$.rotated_padding_left = 30; $$.rotated_padding_right = config.axis_rotated && !config.axis_x_show ? 0 : 30; $$.rotated_padding_top = 5; $$.withoutFadeIn = {}; $$.intervalForObserveInserted = undefined; $$.axes.subx = d3.selectAll([]); // needs when excluding subchart.js }; ChartInternal.prototype.initChartElements = function() { if (this.initBar) { this.initBar(); } if (this.initLine) { this.initLine(); } if (this.initArc) { this.initArc(); } if (this.initGauge) { this.initGauge(); } if (this.initText) { this.initText(); } }; ChartInternal.prototype.initWithData = function(data) { var $$ = this, d3 = $$.d3, config = $$.config; var defs, main, binding = true; $$.axis = new Axis($$); if (!config.bindto) { $$.selectChart = d3.selectAll([]); } else if (typeof config.bindto.node === 'function') { $$.selectChart = config.bindto; } else { $$.selectChart = d3.select(config.bindto); } if ($$.selectChart.empty()) { $$.selectChart = d3 .select(document.createElement('div')) .style('opacity', 0); $$.observeInserted($$.selectChart); binding = false; } $$.selectChart.html('').classed('c3', true); // Init data as targets $$.data.xs = {}; $$.data.targets = $$.convertDataToTargets(data); if (config.data_filter) { $$.data.targets = $$.data.targets.filter(config.data_filter); } // Set targets to hide if needed if (config.data_hide) { $$.addHiddenTargetIds( config.data_hide === true ? $$.mapToIds($$.data.targets) : config.data_hide ); } if (config.legend_hide) { $$.addHiddenLegendIds( config.legend_hide === true ? $$.mapToIds($$.data.targets) : config.legend_hide ); } if ($$.isStanfordGraphType()) { $$.initStanfordData(); } // Init sizes and scales $$.updateSizes(); $$.updateScales(); // Set domains for each scale $$.x.domain(d3.extent($$.getXDomain($$.data.targets))); $$.y.domain($$.getYDomain($$.data.targets, 'y')); $$.y2.domain($$.getYDomain($$.data.targets, 'y2')); $$.subX.domain($$.x.domain()); $$.subY.domain($$.y.domain()); $$.subY2.domain($$.y2.domain()); // Save original x domain for zoom update $$.orgXDomain = $$.x.domain(); /*-- Basic Elements --*/ // Define svgs $$.svg = $$.selectChart .append('svg') .style('overflow', 'hidden') .on('mouseenter', function() { return config.onmouseover.call($$) }) .on('mouseleave', function() { return config.onmouseout.call($$) }); if ($$.config.svg_classname) { $$.svg.attr('class', $$.config.svg_classname); } // Define defs defs = $$.svg.append('defs'); $$.clipChart = $$.appendClip(defs, $$.clipId); $$.clipXAxis = $$.appendClip(defs, $$.clipIdForXAxis); $$.clipYAxis = $$.appendClip(defs, $$.clipIdForYAxis); $$.clipGrid = $$.appendClip(defs, $$.clipIdForGrid); $$.clipSubchart = $$.appendClip(defs, $$.clipIdForSubchart); $$.updateSvgSize(); // Define regions main = $$.main = $$.svg.append('g').attr('transform', $$.getTranslate('main')); if ($$.initPie) { $$.initPie(); } if ($$.initDragZoom) { $$.initDragZoom(); } if (config.subchart_show && $$.initSubchart) { $$.initSubchart(); } if ($$.initTooltip) { $$.initTooltip(); } if ($$.initLegend) { $$.initLegend(); } if ($$.initTitle) { $$.initTitle(); } if ($$.initZoom) { $$.initZoom(); } if ($$.isStanfordGraphType()) { $$.drawColorScale(); } // Update selection based on size and scale // TODO: currently this must be called after initLegend because of update of sizes, but it should be done in initSubchart. if (config.subchart_show && $$.initSubchartBrush) { $$.initSubchartBrush(); } /*-- Main Region --*/ // text when empty main .append('text') .attr('class', CLASS.text + ' ' + CLASS.empty) .attr('text-anchor', 'middle') // horizontal centering of text at x position in all browsers. .attr('dominant-baseline', 'middle'); // vertical centering of text at y position in all browsers, except IE. // Regions $$.initRegion(); // Grids $$.initGrid(); // Define g for chart area main .append('g') .attr('clip-path', $$.clipPath) .attr('class', CLASS.chart); // Grid lines if (config.grid_lines_front) { $$.initGridLines(); } $$.initStanfordElements(); // Cover whole with rects for events $$.initEventRect(); // Define g for chart $$.initChartElements(); // Add Axis $$.axis.init(); // Set targets $$.updateTargets($$.data.targets); // Set default extent if defined if (config.axis_x_selection) { $$.brush.selectionAsValue($$.getDefaultSelection()); } // Draw with targets if (binding) { $$.updateDimension(); $$.config.oninit.call($$); $$.redraw({ withTransition: false, withTransform: true, withUpdateXDomain: true, withUpdateOrgXDomain: true, withTransitionForAxis: false }); } // Bind to resize event $$.bindResize(); // Bind to window focus event $$.bindWindowFocus(); // export element of the chart $$.api.element = $$.selectChart.node(); }; ChartInt