Your IP : 216.73.216.86


Current Path : /home/emeraadmin/www/4d695/
Upload File :
Current File : /home/emeraadmin/www/4d695/c3.tar

src/axis-internal.js000064400000037352151701472650010471 0ustar00function 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 = this.getBoundingClientRect(),
            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;
};

export {AxisInternal};src/text.js000064400000012277151701472650006676 0ustar00import CLASS from './class';
import { ChartInternal } from './core';

ChartInternal.prototype.initText = function () {
    var $$ = this;
    $$.main.select('.' + CLASS.chart).append("g")
        .attr("class", CLASS.chartTexts);
    $$.mainText = $$.d3.selectAll([]);
};
ChartInternal.prototype.updateTargetsForText = function (targets) {
    var $$ = this,
        classChartText = $$.classChartText.bind($$),
        classTexts = $$.classTexts.bind($$),
        classFocus = $$.classFocus.bind($$);
    var mainText = $$.main.select('.' + CLASS.chartTexts).selectAll('.' + CLASS.chartText)
        .data(targets);
    var mainTextEnter = mainText.enter().append('g')
        .attr('class', classChartText)
        .style('opacity', 0)
        .style("pointer-events", "none");
    mainTextEnter.append('g')
        .attr('class', classTexts);
    mainTextEnter.merge(mainText)
        .attr('class', function (d) { return classChartText(d) + classFocus(d); });
};
ChartInternal.prototype.updateText = function (xForText, yForText, durationForExit) {
    var $$ = this, config = $$.config,
        barOrLineData = $$.barOrLineData.bind($$),
        classText = $$.classText.bind($$);
    var mainText = $$.main.selectAll('.' + CLASS.texts).selectAll('.' + CLASS.text)
        .data(barOrLineData);
    var mainTextEnter = mainText.enter().append('text')
        .attr("class", classText)
        .attr('text-anchor', function (d) { return config.axis_rotated ? (d.value < 0 ? 'end' : 'start') : 'middle'; })
        .style("stroke", 'none')
        .attr('x', xForText)
        .attr('y', yForText)
        .style("fill", function (d) { return $$.color(d); })
        .style("fill-opacity", 0);
    $$.mainText = mainTextEnter.merge(mainText)
        .text(function (d, i, j) { return $$.dataLabelFormat(d.id)(d.value, d.id, i, j); });
    mainText.exit()
        .transition().duration(durationForExit)
        .style('fill-opacity', 0)
        .remove();
};
ChartInternal.prototype.redrawText = function (xForText, yForText, forFlow, withTransition, transition) {
    return [
        (withTransition ? this.mainText.transition(transition) : this.mainText)
            .attr('x', xForText)
            .attr('y', yForText)
            .style("fill", this.color)
            .style("fill-opacity", forFlow ? 0 : this.opacityForText.bind(this))
    ];
};
ChartInternal.prototype.getTextRect = function (text, cls, element) {
    var dummy = this.d3.select('body').append('div').classed('c3', true),
        svg = dummy.append("svg").style('visibility', 'hidden').style('position', 'fixed').style('top', 0).style('left', 0),
        font = this.d3.select(element).style('font'),
        rect;
    svg.selectAll('.dummy')
        .data([text])
      .enter().append('text')
        .classed(cls ? cls : "", true)
        .style('font', font)
        .text(text)
      .each(function () { rect = this.getBoundingClientRect(); });
    dummy.remove();
    return rect;
};
ChartInternal.prototype.generateXYForText = function (areaIndices, barIndices, lineIndices, forX) {
    var $$ = this,
        getAreaPoints = $$.generateGetAreaPoints(areaIndices, false),
        getBarPoints = $$.generateGetBarPoints(barIndices, false),
        getLinePoints = $$.generateGetLinePoints(lineIndices, false),
        getter = forX ? $$.getXForText : $$.getYForText;
    return function (d, i) {
        var getPoints = $$.isAreaType(d) ? getAreaPoints : $$.isBarType(d) ? getBarPoints : getLinePoints;
        return getter.call($$, getPoints(d, i), d, this);
    };
};
ChartInternal.prototype.getXForText = function (points, d, textElement) {
    var $$ = this,
        box = textElement.getBoundingClientRect(), xPos, padding;
    if ($$.config.axis_rotated) {
        padding = $$.isBarType(d) ? 4 : 6;
        xPos = points[2][1] + padding * (d.value < 0 ? -1 : 1);
    } else {
        xPos = $$.hasType('bar') ? (points[2][0] + points[0][0]) / 2 : points[0][0];
    }
    // show labels regardless of the domain if value is null
    if (d.value === null) {
        if (xPos > $$.width) {
            xPos = $$.width - box.width;
        } else if (xPos < 0) {
            xPos = 4;
        }
    }
    return xPos;
};
ChartInternal.prototype.getYForText = function (points, d, textElement) {
    var $$ = this,
        box = textElement.getBoundingClientRect(),
        yPos;
    if ($$.config.axis_rotated) {
        yPos = (points[0][0] + points[2][0] + box.height * 0.6) / 2;
    } else {
        yPos = points[2][1];
        if (d.value < 0  || (d.value === 0 && !$$.hasPositiveValue)) {
            yPos += box.height;
            if ($$.isBarType(d) && $$.isSafari()) {
                yPos -= 3;
            }
            else if (!$$.isBarType(d) && $$.isChrome()) {
                yPos += 3;
            }
        } else {
            yPos += $$.isBarType(d) ? -3 : -6;
        }
    }
    // show labels regardless of the domain if value is null
    if (d.value === null && !$$.config.axis_rotated) {
        if (yPos < box.height) {
            yPos = box.height;
        } else if (yPos > this.height) {
            yPos = this.height - 4;
        }
    }
    return yPos;
};
src/size.js000064400000012241151701472650006653 0ustar00import CLASS from './class';
import { ChartInternal } from './core';
import { isValue, ceil10 } from './util';

ChartInternal.prototype.getCurrentWidth = function () {
    var $$ = this, config = $$.config;
    return config.size_width ? config.size_width : $$.getParentWidth();
};
ChartInternal.prototype.getCurrentHeight = function () {
    var $$ = this, config = $$.config,
        h = config.size_height ? config.size_height : $$.getParentHeight();
    return h > 0 ? h : 320 / ($$.hasType('gauge') && !config.gauge_fullCircle ? 2 : 1);
};
ChartInternal.prototype.getCurrentPaddingTop = function () {
    var $$ = this,
        config = $$.config,
        padding = isValue(config.padding_top) ? config.padding_top : 0;
    if ($$.title && $$.title.node()) {
        padding += $$.getTitlePadding();
    }
    return padding;
};
ChartInternal.prototype.getCurrentPaddingBottom = function () {
    var config = this.config;
    return isValue(config.padding_bottom) ? config.padding_bottom : 0;
};
ChartInternal.prototype.getCurrentPaddingLeft = function (withoutRecompute) {
    var $$ = this, config = $$.config;
    if (isValue(config.padding_left)) {
        return config.padding_left;
    } else if (config.axis_rotated) {
        return (!config.axis_x_show || config.axis_x_inner) ? 1 : Math.max(ceil10($$.getAxisWidthByAxisId('x', withoutRecompute)), 40);
    } else if (!config.axis_y_show || config.axis_y_inner) { // && !config.axis_rotated
        return $$.axis.getYAxisLabelPosition().isOuter ? 30 : 1;
    } else {
        return ceil10($$.getAxisWidthByAxisId('y', withoutRecompute));
    }
};
ChartInternal.prototype.getCurrentPaddingRight = function () {
    var $$ = this, config = $$.config,
        defaultPadding = 10, legendWidthOnRight = $$.isLegendRight ? $$.getLegendWidth() + 20 : 0;
    if (isValue(config.padding_right)) {
        return config.padding_right + 1; // 1 is needed not to hide tick line
    } else if (config.axis_rotated) {
        return defaultPadding + legendWidthOnRight;
    } else if (!config.axis_y2_show || config.axis_y2_inner) { // && !config.axis_rotated
        return 2 + legendWidthOnRight + ($$.axis.getY2AxisLabelPosition().isOuter ? 20 : 0);
    } else {
        return ceil10($$.getAxisWidthByAxisId('y2')) + legendWidthOnRight;
    }
};

ChartInternal.prototype.getParentRectValue = function (key) {
    var parent = this.selectChart.node(), v;
    while (parent && parent.tagName !== 'BODY') {
        try {
            v = parent.getBoundingClientRect()[key];
        } catch(e) {
            if (key === 'width') {
                // In IE in certain cases getBoundingClientRect
                // will cause an "unspecified error"
                v = parent.offsetWidth;
            }
        }
        if (v) {
            break;
        }
        parent = parent.parentNode;
    }
    return v;
};
ChartInternal.prototype.getParentWidth = function () {
    return this.getParentRectValue('width');
};
ChartInternal.prototype.getParentHeight = function () {
    var h = this.selectChart.style('height');
    return h.indexOf('px') > 0 ? +h.replace('px', '') : 0;
};


ChartInternal.prototype.getSvgLeft = function (withoutRecompute) {
    var $$ = this, config = $$.config,
        hasLeftAxisRect = config.axis_rotated || (!config.axis_rotated && !config.axis_y_inner),
        leftAxisClass = config.axis_rotated ? CLASS.axisX : CLASS.axisY,
        leftAxis = $$.main.select('.' + leftAxisClass).node(),
        svgRect = leftAxis && hasLeftAxisRect ? leftAxis.getBoundingClientRect() : {right: 0},
        chartRect = $$.selectChart.node().getBoundingClientRect(),
        hasArc = $$.hasArcType(),
        svgLeft = svgRect.right - chartRect.left - (hasArc ? 0 : $$.getCurrentPaddingLeft(withoutRecompute));
    return svgLeft > 0 ? svgLeft : 0;
};


ChartInternal.prototype.getAxisWidthByAxisId = function (id, withoutRecompute) {
    var $$ = this, position = $$.axis.getLabelPositionById(id);
    return $$.axis.getMaxTickWidth(id, withoutRecompute) + (position.isInner ? 20 : 40);
};
ChartInternal.prototype.getHorizontalAxisHeight = function (axisId) {
    var $$ = this, config = $$.config, h = 30;
    if (axisId === 'x' && !config.axis_x_show) { return 8; }
    if (axisId === 'x' && config.axis_x_height) { return config.axis_x_height; }
    if (axisId === 'y' && !config.axis_y_show) {
        return config.legend_show && !$$.isLegendRight && !$$.isLegendInset ? 10 : 1;
    }
    if (axisId === 'y2' && !config.axis_y2_show) { return $$.rotated_padding_top; }
    // Calculate x axis height when tick rotated
    if (axisId === 'x' && !config.axis_rotated && config.axis_x_tick_rotate) {
        h = 30 + $$.axis.getMaxTickWidth(axisId) * Math.cos(Math.PI * (90 - Math.abs(config.axis_x_tick_rotate)) / 180);
    }
    // Calculate y axis height when tick rotated
    if (axisId === 'y' && config.axis_rotated && config.axis_y_tick_rotate) {
        h = 30 + $$.axis.getMaxTickWidth(axisId) * Math.cos(Math.PI * (90 - Math.abs(config.axis_y_tick_rotate)) / 180);
    }
    return h + ($$.axis.getLabelPositionById(axisId).isInner ? 0 : 10) + (axisId === 'y2' ? -10 : 0);
};

src/interaction.js000064400000014360151701472650010224 0ustar00import CLASS from './class';
import { ChartInternal } from './core';

ChartInternal.prototype.initEventRect = function () {
    var $$ = this, config = $$.config;

    $$.main.select('.' + CLASS.chart).append("g")
        .attr("class", CLASS.eventRects)
        .style('fill-opacity', 0);
    $$.eventRect = $$.main.select('.' + CLASS.eventRects).append('rect')
        .attr('class', CLASS.eventRect);

    // event rect handle zoom event as well
    if (config.zoom_enabled && $$.zoom) {
        $$.eventRect.call($$.zoom).on("dblclick.zoom", null);
        if (config.zoom_initialRange) {
            // WORKAROUND: Add transition to apply transform immediately when no subchart
            $$.eventRect.transition().duration(0).call(
                $$.zoom.transform, $$.zoomTransform(config.zoom_initialRange)
            );
        }
    }
};
ChartInternal.prototype.redrawEventRect = function () {
    var $$ = this, d3 = $$.d3, config = $$.config,
        x, y, w, h;

    // TODO: rotated not supported yet
    x = 0;
    y = 0;
    w = $$.width;
    h = $$.height;

    function mouseout() {
        $$.svg.select('.' + CLASS.eventRect).style('cursor', null);
        $$.hideXGridFocus();
        $$.hideTooltip();
        $$.unexpandCircles();
        $$.unexpandBars();
    }

    // rects for mouseover
    $$.main.select('.' + CLASS.eventRects)
        .style('cursor', config.zoom_enabled ? config.axis_rotated ? 'ns-resize' : 'ew-resize' : null);

    $$.eventRect
        .attr('x', x)
        .attr('y', y)
        .attr('width', w)
        .attr('height', h)
        .on('mouseout',  config.interaction_enabled ? function () {
            if (!config) { return; } // chart is destroyed
            if ($$.hasArcType()) { return; }
            mouseout();
        } : null)
        .on('mousemove', config.interaction_enabled ? function () {
            var targetsToShow, mouse, closest, sameXData, selectedData;

            if ($$.dragging) { return; } // do nothing when dragging
            if ($$.hasArcType(targetsToShow)) { return; }

            targetsToShow = $$.filterTargetsToShow($$.data.targets);
            mouse = d3.mouse(this);
            closest = $$.findClosestFromTargets(targetsToShow, mouse);

            if ($$.mouseover && (!closest || closest.id !== $$.mouseover.id)) {
                config.data_onmouseout.call($$.api, $$.mouseover);
                $$.mouseover = undefined;
            }

            if (!closest) {
                mouseout();
                return;
            }

            if ($$.isScatterType(closest) || !config.tooltip_grouped) {
                sameXData = [closest];
            } else {
                sameXData = $$.filterByX(targetsToShow, closest.x);
            }

            // show tooltip when cursor is close to some point
            selectedData = sameXData.map(function (d) {
                return $$.addName(d);
            });
            $$.showTooltip(selectedData, this);

            // expand points
            if (config.point_focus_expand_enabled) {
                $$.unexpandCircles();
                selectedData.forEach(function (d) {
                    $$.expandCircles(d.index, d.id, false);
                });
            }
            $$.expandBars(closest.index, closest.id, true);

            // Show xgrid focus line
            $$.showXGridFocus(selectedData);

            // Show cursor as pointer if point is close to mouse position
            if ($$.isBarType(closest.id) || $$.dist(closest, mouse) < config.point_sensitivity) {
                $$.svg.select('.' + CLASS.eventRect).style('cursor', 'pointer');
                if (!$$.mouseover) {
                    config.data_onmouseover.call($$.api, closest);
                    $$.mouseover = closest;
                }
            }
        } : null)
        .on('click', config.interaction_enabled ? function () {
            var targetsToShow, mouse, closest, sameXData;
            if ($$.hasArcType(targetsToShow)) { return; }

            targetsToShow = $$.filterTargetsToShow($$.data.targets);
            mouse = d3.mouse(this);
            closest = $$.findClosestFromTargets(targetsToShow, mouse);
            if (! closest) { return; }
            // select if selection enabled
            if ($$.isBarType(closest.id) || $$.dist(closest, mouse) < config.point_sensitivity) {
                if ($$.isScatterType(closest) || !config.data_selection_grouped) {
                    sameXData = [closest];
                } else {
                    sameXData = $$.filterByX(targetsToShow, closest.x);
                }
                sameXData.forEach(function (d) {
                    $$.main.selectAll('.' + CLASS.shapes + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.shape + '-' + d.index).each(function () {
                        if (config.data_selection_grouped || $$.isWithinShape(this, d)) {
                            $$.toggleShape(this, d, d.index);
                            config.data_onclick.call($$.api, d, this);
                        }
                    });
                });
            }
        } : null)
        .call(
            config.interaction_enabled && config.data_selection_draggable && $$.drag ? (
                d3.drag()
                    .on('drag', function () { $$.drag(d3.mouse(this)); })
                    .on('start', function () { $$.dragstart(d3.mouse(this)); })
                    .on('end', function () { $$.dragend(); })
            ) : function () {}
        );
};
ChartInternal.prototype.getMousePosition = function (data) {
    var $$ = this;
    return [$$.x(data.x), $$.getYScale(data.id)(data.value)];
};
ChartInternal.prototype.dispatchEvent = function (type, mouse) {
    var $$ = this,
        selector = '.' + CLASS.eventRect,
        eventRect = $$.main.select(selector).node(),
        box = eventRect.getBoundingClientRect(),
        x = box.left + (mouse ? mouse[0] : 0),
        y = box.top + (mouse ? mouse[1] : 0),
        event = document.createEvent("MouseEvents");

    event.initMouseEvent(type, true, true, window, 0, x, y, x, y,
                         false, false, false, false, 0, null);
    eventRect.dispatchEvent(event);
};
src/title.js000064400000002536151701472650007030 0ustar00import {
    ChartInternal
} from './core';

ChartInternal.prototype.initTitle = function () {
    var $$ = this;
    $$.title = $$.svg.append("text")
        .text($$.config.title_text)
        .attr("class", $$.CLASS.title);
};
ChartInternal.prototype.redrawTitle = function () {
    var $$ = this;
    $$.title
        .attr("x", $$.xForTitle.bind($$))
        .attr("y", $$.yForTitle.bind($$));
};
ChartInternal.prototype.xForTitle = function () {
    var $$ = this,
        config = $$.config,
        position = config.title_position || 'left',
        x;
    if (position.indexOf('right') >= 0) {
        x = $$.currentWidth - $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).width - config.title_padding.right;
    } else if (position.indexOf('center') >= 0) {
        x = ($$.currentWidth - $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).width) / 2;
    } else { // left
        x = config.title_padding.left;
    }
    return x;
};
ChartInternal.prototype.yForTitle = function () {
    var $$ = this;
    return $$.config.title_padding.top + $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).height;
};
ChartInternal.prototype.getTitlePadding = function () {
    var $$ = this;
    return $$.yForTitle() + $$.config.title_padding.bottom;
};
src/api.show.js000064400000003233151701472650007432 0ustar00import { Chart } from './core';

Chart.prototype.show = function (targetIds, options) {
    var $$ = this.internal, targets;

    targetIds = $$.mapToTargetIds(targetIds);
    options = options || {};

    $$.removeHiddenTargetIds(targetIds);
    targets = $$.svg.selectAll($$.selectorTargets(targetIds));

    targets.transition()
        .style('display', 'initial', 'important')
        .style('opacity', 1, 'important')
        .call($$.endall, function () {
            targets.style('opacity', null).style('opacity', 1);
        });

    if (options.withLegend) {
        $$.showLegend(targetIds);
    }

    $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
};

Chart.prototype.hide = function (targetIds, options) {
    var $$ = this.internal, targets;

    targetIds = $$.mapToTargetIds(targetIds);
    options = options || {};

    $$.addHiddenTargetIds(targetIds);
    targets = $$.svg.selectAll($$.selectorTargets(targetIds));

    targets.transition()
        .style('opacity', 0, 'important')
        .call($$.endall, function () {
            targets.style('opacity', null).style('opacity', 0);
            targets.style('display', 'none');
        });

    if (options.withLegend) {
        $$.hideLegend(targetIds);
    }

    $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
};

Chart.prototype.toggle = function (targetIds, options) {
    var that = this, $$ = this.internal;
    $$.mapToTargetIds(targetIds).forEach(function (targetId) {
        $$.isTargetToShow(targetId) ? that.hide(targetId, options) : that.show(targetId, options);
    });
};
src/drag.js000064400000006476151701472650006633 0ustar00import CLASS from './class';
import { ChartInternal } from './core';
import { getPathBox } from './util';

ChartInternal.prototype.drag = function (mouse) {
    var $$ = this, config = $$.config, main = $$.main, d3 = $$.d3;
    var sx, sy, mx, my, minX, maxX, minY, maxY;

    if ($$.hasArcType()) { return; }
    if (!config.data_selection_enabled) { return; } // do nothing if not selectable
    if (!config.data_selection_multiple) { return; } // skip when single selection because drag is used for multiple selection

    sx = $$.dragStart[0];
    sy = $$.dragStart[1];
    mx = mouse[0];
    my = mouse[1];
    minX = Math.min(sx, mx);
    maxX = Math.max(sx, mx);
    minY = (config.data_selection_grouped) ? $$.margin.top : Math.min(sy, my);
    maxY = (config.data_selection_grouped) ? $$.height : Math.max(sy, my);

    main.select('.' + CLASS.dragarea)
        .attr('x', minX)
        .attr('y', minY)
        .attr('width', maxX - minX)
        .attr('height', maxY - minY);
    // TODO: binary search when multiple xs
    main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape)
        .filter(function (d) { return config.data_selection_isselectable(d); })
        .each(function (d, i) {
            var shape = d3.select(this),
                isSelected = shape.classed(CLASS.SELECTED),
                isIncluded = shape.classed(CLASS.INCLUDED),
                _x, _y, _w, _h, toggle, isWithin = false, box;
            if (shape.classed(CLASS.circle)) {
                _x = shape.attr("cx") * 1;
                _y = shape.attr("cy") * 1;
                toggle = $$.togglePoint;
                isWithin = minX < _x && _x < maxX && minY < _y && _y < maxY;
            }
            else if (shape.classed(CLASS.bar)) {
                box = getPathBox(this);
                _x = box.x;
                _y = box.y;
                _w = box.width;
                _h = box.height;
                toggle = $$.togglePath;
                isWithin = !(maxX < _x || _x + _w < minX) && !(maxY < _y || _y + _h < minY);
            } else {
                // line/area selection not supported yet
                return;
            }
            if (isWithin ^ isIncluded) {
                shape.classed(CLASS.INCLUDED, !isIncluded);
                // TODO: included/unincluded callback here
                shape.classed(CLASS.SELECTED, !isSelected);
                toggle.call($$, !isSelected, shape, d, i);
            }
        });
};

ChartInternal.prototype.dragstart = function (mouse) {
    var $$ = this, config = $$.config;
    if ($$.hasArcType()) { return; }
    if (! config.data_selection_enabled) { return; } // do nothing if not selectable
    $$.dragStart = mouse;
    $$.main.select('.' + CLASS.chart).append('rect')
        .attr('class', CLASS.dragarea)
        .style('opacity', 0.1);
    $$.dragging = true;
};

ChartInternal.prototype.dragend = function () {
    var $$ = this, config = $$.config;
    if ($$.hasArcType()) { return; }
    if (! config.data_selection_enabled) { return; } // do nothing if not selectable
    $$.main.select('.' + CLASS.dragarea)
        .transition().duration(100)
        .style('opacity', 0)
        .remove();
    $$.main.selectAll('.' + CLASS.shape)
        .classed(CLASS.INCLUDED, false);
    $$.dragging = false;
};
src/api.axis.js000064400000004125151701472650007417 0ustar00import { Chart } from './core';
import { isValue, isDefined } from './util';

Chart.prototype.axis = function () {};
Chart.prototype.axis.labels = function (labels) {
    var $$ = this.internal;
    if (arguments.length) {
        Object.keys(labels).forEach(function (axisId) {
            $$.axis.setLabelText(axisId, labels[axisId]);
        });
        $$.axis.updateLabels();
    }
    // TODO: return some values?
};
Chart.prototype.axis.max = function (max) {
    var $$ = this.internal, config = $$.config;
    if (arguments.length) {
        if (typeof max === 'object') {
            if (isValue(max.x)) { config.axis_x_max = max.x; }
            if (isValue(max.y)) { config.axis_y_max = max.y; }
            if (isValue(max.y2)) { config.axis_y2_max = max.y2; }
        } else {
            config.axis_y_max = config.axis_y2_max = max;
        }
        $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
    } else {
        return {
            x: config.axis_x_max,
            y: config.axis_y_max,
            y2: config.axis_y2_max
        };
    }
};
Chart.prototype.axis.min = function (min) {
    var $$ = this.internal, config = $$.config;
    if (arguments.length) {
        if (typeof min === 'object') {
            if (isValue(min.x)) { config.axis_x_min = min.x; }
            if (isValue(min.y)) { config.axis_y_min = min.y; }
            if (isValue(min.y2)) { config.axis_y2_min = min.y2; }
        } else {
            config.axis_y_min = config.axis_y2_min = min;
        }
        $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
    } else {
        return {
            x: config.axis_x_min,
            y: config.axis_y_min,
            y2: config.axis_y2_min
        };
    }
};
Chart.prototype.axis.range = function (range) {
    if (arguments.length) {
        if (isDefined(range.max)) { this.axis.max(range.max); }
        if (isDefined(range.min)) { this.axis.min(range.min); }
    } else {
        return {
            max: this.axis.max(),
            min: this.axis.min()
        };
    }
};
src/data.load.js000064400000006033151701472650007532 0ustar00import CLASS from './class';
import { ChartInternal } from './core';

ChartInternal.prototype.load = function (targets, args) {
    var $$ = this;
    if (targets) {
        // filter loading targets if needed
        if (args.filter) {
            targets = targets.filter(args.filter);
        }
        // set type if args.types || args.type specified
        if (args.type || args.types) {
            targets.forEach(function (t) {
                var type = args.types && args.types[t.id] ? args.types[t.id] : args.type;
                $$.setTargetType(t.id, type);
            });
        }
        // Update/Add data
        $$.data.targets.forEach(function (d) {
            for (var i = 0; i < targets.length; i++) {
                if (d.id === targets[i].id) {
                    d.values = targets[i].values;
                    targets.splice(i, 1);
                    break;
                }
            }
        });
        $$.data.targets = $$.data.targets.concat(targets); // add remained
    }

    // Set targets
    $$.updateTargets($$.data.targets);

    // Redraw with new targets
    $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});

    if (args.done) { args.done(); }
};
ChartInternal.prototype.loadFromArgs = function (args) {
    var $$ = this;
    if (args.data) {
        $$.load($$.convertDataToTargets(args.data), args);
    }
    else if (args.url) {
        $$.convertUrlToData(args.url, args.mimeType, args.headers, args.keys, function (data) {
            $$.load($$.convertDataToTargets(data), args);
        });
    }
    else if (args.json) {
        $$.load($$.convertDataToTargets($$.convertJsonToData(args.json, args.keys)), args);
    }
    else if (args.rows) {
        $$.load($$.convertDataToTargets($$.convertRowsToData(args.rows)), args);
    }
    else if (args.columns) {
        $$.load($$.convertDataToTargets($$.convertColumnsToData(args.columns)), args);
    }
    else {
        $$.load(null, args);
    }
};
ChartInternal.prototype.unload = function (targetIds, done) {
    var $$ = this;
    if (!done) {
        done = function () {};
    }
    // filter existing target
    targetIds = targetIds.filter(function (id) { return $$.hasTarget($$.data.targets, id); });
    // If no target, call done and return
    if (!targetIds || targetIds.length === 0) {
        done();
        return;
    }
    $$.svg.selectAll(targetIds.map(function (id) { return $$.selectorTarget(id); }))
        .transition()
        .style('opacity', 0)
        .remove()
        .call($$.endall, done);
    targetIds.forEach(function (id) {
        // Reset fadein for future load
        $$.withoutFadeIn[id] = false;
        // Remove target's elements
        if ($$.legend) {
            $$.legend.selectAll('.' + CLASS.legendItem + $$.getTargetSelectorSuffix(id)).remove();
        }
        // Remove target
        $$.data.targets = $$.data.targets.filter(function (t) {
            return t.id !== id;
        });
    });
};
src/api.chart.js000064400000002751151701472650007557 0ustar00import { Chart } from './core';

Chart.prototype.resize = function (size) {
    var $$ = this.internal, config = $$.config;
    config.size_width = size ? size.width : null;
    config.size_height = size ? size.height : null;
    this.flush();
};

Chart.prototype.flush = function () {
    var $$ = this.internal;
    $$.updateAndRedraw({withLegend: true, withTransition: false, withTransitionForTransform: false});
};

Chart.prototype.destroy = function () {
    var $$ = this.internal;

    window.clearInterval($$.intervalForObserveInserted);

    if ($$.resizeTimeout !== undefined) {
        window.clearTimeout($$.resizeTimeout);
    }

    if (window.detachEvent) {
        window.detachEvent('onresize', $$.resizeIfElementDisplayed);
    } else if (window.removeEventListener) {
        window.removeEventListener('resize', $$.resizeIfElementDisplayed);
    } else {
        var wrapper = window.onresize;
        // check if no one else removed our wrapper and remove our resizeFunction from it
        if (wrapper && wrapper.add && wrapper.remove) {
            wrapper.remove($$.resizeFunction);
        }
    }

    // remove the inner resize functions
    $$.resizeFunction.remove();

    $$.selectChart.classed('c3', false).html("");

    // MEMO: this is needed because the reference of some elements will not be released, then memory leak will happen.
    Object.keys($$).forEach(function (key) {
        $$[key] = null;
    });

    return null;
};
src/class.js000064400000004737151701472650007021 0ustar00export default {
    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',
    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_'
};
src/zoom.js000064400000011407151701472650006670 0ustar00import { ChartInternal } from './core';
import CLASS from './class';

ChartInternal.prototype.initZoom = function () {
    var $$ = this, d3 = $$.d3, config = $$.config, startEvent;

    $$.zoom = d3.zoom()
        .on("start", function () {
            if (config.zoom_type !== 'scroll') {
                return;
            }

            var e = d3.event.sourceEvent;
            if (e && e.type === "brush") { return; }
            startEvent = e;
            config.zoom_onzoomstart.call($$.api, e);
        })
        .on("zoom", function () {
            if (config.zoom_type !== 'scroll') {
                return;
            }

            var e = d3.event.sourceEvent;
            if (e && e.type === "brush") { return; }

            $$.redrawForZoom();

            config.zoom_onzoom.call($$.api, $$.x.orgDomain());
        })
        .on('end', function () {
            if (config.zoom_type !== 'scroll') {
                return;
            }

            var e = d3.event.sourceEvent;
            if (e && e.type === "brush") { return; }
            // if click, do nothing. otherwise, click interaction will be canceled.
            if (e && startEvent.clientX === e.clientX && startEvent.clientY === e.clientY) {
                return;
            }
            config.zoom_onzoomend.call($$.api, $$.x.orgDomain());
        });

    $$.zoom.updateDomain = function () {
        if (d3.event && d3.event.transform) {
            $$.x.domain(d3.event.transform.rescaleX($$.subX).domain());
        }
        return this;
    };
    $$.zoom.updateExtent = function () {
        this.scaleExtent([1, Infinity])
            .translateExtent([[0, 0], [$$.width, $$.height]])
            .extent([[0, 0], [$$.width, $$.height]]);
        return this;
    };
    $$.zoom.update = function () {
        return this.updateExtent().updateDomain();
    };

    return $$.zoom.updateExtent();
};
ChartInternal.prototype.zoomTransform = function (range) {
    var $$ = this, s = [$$.x(range[0]), $$.x(range[1])];
    return $$.d3.zoomIdentity.scale($$.width / (s[1] - s[0])).translate(-s[0], 0);
};

ChartInternal.prototype.initDragZoom = function () {
    const $$ = this;
    const d3 = $$.d3;
    const config = $$.config;
    const context = $$.context = $$.svg;
    const brushXPos = $$.margin.left + 20.5;
    const brushYPos = $$.margin.top + 0.5;

    if (!(config.zoom_type === 'drag' && config.zoom_enabled)) {
        return;
    }

    const getZoomedDomain = selection => selection && selection.map(x => $$.x.invert(x));

    const brush = $$.dragZoomBrush = d3.brushX()
        .on("start", () => {
            $$.api.unzoom();

            $$.svg
                .select("." + CLASS.dragZoom)
                .classed("disabled", false);

            config.zoom_onzoomstart.call($$.api, d3.event.sourceEvent);
        })
        .on("brush", () => {
            config.zoom_onzoom.call($$.api, getZoomedDomain(d3.event.selection));
        })
        .on("end", () => {
            if (d3.event.selection == null) {
                return;
            }

            const zoomedDomain = getZoomedDomain(d3.event.selection);

            if (!config.zoom_disableDefaultBehavior) {
              $$.api.zoom(zoomedDomain);
            }

            $$.svg
                .select("." + CLASS.dragZoom)
                .classed("disabled", true);

            config.zoom_onzoomend.call($$.api, zoomedDomain);
        });

    context
        .append("g")
        .classed(CLASS.dragZoom, true)
        .attr("clip-path", $$.clipPath)
        .attr("transform", "translate(" + brushXPos + "," + brushYPos + ")")
        .call(brush);
};

ChartInternal.prototype.getZoomDomain = function () {
    var $$ = this, config = $$.config, d3 = $$.d3,
        min = d3.min([$$.orgXDomain[0], config.zoom_x_min]),
        max = d3.max([$$.orgXDomain[1], config.zoom_x_max]);
    return [min, max];
};
ChartInternal.prototype.redrawForZoom = function () {
    var $$ = this, d3 = $$.d3, config = $$.config, zoom = $$.zoom, x = $$.x;
    if (!config.zoom_enabled) {
        return;
    }
    if ($$.filterTargetsToShow($$.data.targets).length === 0) {
        return;
    }

    zoom.update();

    if (config.zoom_disableDefaultBehavior) {
        return;
    }

    if ($$.isCategorized() && x.orgDomain()[0] === $$.orgXDomain[0]) {
        x.domain([$$.orgXDomain[0] - 1e-10, x.orgDomain()[1]]);
    }

    $$.redraw({
        withTransition: false,
        withY: config.zoom_rescale,
        withSubchart: false,
        withEventRect: false,
        withDimension: false
    });

    if (d3.event.sourceEvent && d3.event.sourceEvent.type === 'mousemove') {
        $$.cancelClick = true;
    }
};
src/category.js000064400000000330151701472650007512 0ustar00import { ChartInternal } from './core';

ChartInternal.prototype.categoryName = function (i) {
    var config = this.config;
    return i < config.axis_x_categories.length ? config.axis_x_categories[i] : i;
};
src/chart.js000064400000001130151701472650006775 0ustar00import {ChartInternal} from './chart-internal';

export function Chart(config) {
    var $$ = this.internal = new ChartInternal(this);
    $$.loadConfig(config);

    $$.beforeInit(config);
    $$.init();
    $$.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);
}src/color.js000064400000003373151701472650007025 0ustar00import { ChartInternal } from './core';
import { notEmpty } from './util';

ChartInternal.prototype.generateColor = function () {
    var $$ = this, config = $$.config, d3 = $$.d3,
        colors = config.data_colors,
        pattern = notEmpty(config.color_pattern) ? config.color_pattern : d3.schemeCategory10,
        callback = config.data_color,
        ids = [];

    return function (d) {
        var id = d.id || (d.data && d.data.id) || d, color;

        // if callback function is provided
        if (colors[id] instanceof Function) {
            color = colors[id](d);
        }
        // if specified, choose that color
        else if (colors[id]) {
            color = colors[id];
        }
        // if not specified, choose from pattern
        else {
            if (ids.indexOf(id) < 0) { ids.push(id); }
            color = pattern[ids.indexOf(id) % pattern.length];
            colors[id] = color;
        }
        return callback instanceof Function ? callback(color, d) : color;
    };
};
ChartInternal.prototype.generateLevelColor = function () {
    var $$ = this, config = $$.config,
        colors = config.color_pattern,
        threshold = config.color_threshold,
        asValue = threshold.unit === 'value',
        values = threshold.values && threshold.values.length ? threshold.values : [],
        max = threshold.max || 100;
    return notEmpty(config.color_threshold) ? function (value) {
        var i, v, color = colors[colors.length - 1];
        for (i = 0; i < values.length; i++) {
            v = asValue ? value : (value * 100 / max);
            if (v < values[i]) {
                color = colors[i];
                break;
            }
        }
        return color;
    } : null;
};
src/api.legend.js000064400000000672151701472650007714 0ustar00import { Chart } from './core';

Chart.prototype.legend = function () {};
Chart.prototype.legend.show = function (targetIds) {
    var $$ = this.internal;
    $$.showLegend($$.mapToTargetIds(targetIds));
    $$.updateAndRedraw({withLegend: true});
};
Chart.prototype.legend.hide = function (targetIds) {
    var $$ = this.internal;
    $$.hideLegend($$.mapToTargetIds(targetIds));
    $$.updateAndRedraw({withLegend: false});
};
src/class-utils.js000064400000010610151701472650010142 0ustar00import CLASS from './class';
import { ChartInternal } from './core';


ChartInternal.prototype.generateTargetClass = function (targetId) {
    return targetId || targetId === 0 ? ('-' + targetId).replace(/\s/g, '-') : '';
};
ChartInternal.prototype.generateClass = function (prefix, targetId) {
    return " " + prefix + " " + prefix + this.generateTargetClass(targetId);
};
ChartInternal.prototype.classText = function (d) {
    return this.generateClass(CLASS.text, d.index);
};
ChartInternal.prototype.classTexts = function (d) {
    return this.generateClass(CLASS.texts, d.id);
};
ChartInternal.prototype.classShape = function (d) {
    return this.generateClass(CLASS.shape, d.index);
};
ChartInternal.prototype.classShapes = function (d) {
    return this.generateClass(CLASS.shapes, d.id);
};
ChartInternal.prototype.classLine = function (d) {
    return this.classShape(d) + this.generateClass(CLASS.line, d.id);
};
ChartInternal.prototype.classLines = function (d) {
    return this.classShapes(d) + this.generateClass(CLASS.lines, d.id);
};
ChartInternal.prototype.classCircle = function (d) {
    return this.classShape(d) + this.generateClass(CLASS.circle, d.index);
};
ChartInternal.prototype.classCircles = function (d) {
    return this.classShapes(d) + this.generateClass(CLASS.circles, d.id);
};
ChartInternal.prototype.classBar = function (d) {
    return this.classShape(d) + this.generateClass(CLASS.bar, d.index);
};
ChartInternal.prototype.classBars = function (d) {
    return this.classShapes(d) + this.generateClass(CLASS.bars, d.id);
};
ChartInternal.prototype.classArc = function (d) {
    return this.classShape(d.data) + this.generateClass(CLASS.arc, d.data.id);
};
ChartInternal.prototype.classArcs = function (d) {
    return this.classShapes(d.data) + this.generateClass(CLASS.arcs, d.data.id);
};
ChartInternal.prototype.classArea = function (d) {
    return this.classShape(d) + this.generateClass(CLASS.area, d.id);
};
ChartInternal.prototype.classAreas = function (d) {
    return this.classShapes(d) + this.generateClass(CLASS.areas, d.id);
};
ChartInternal.prototype.classRegion = function (d, i) {
    return this.generateClass(CLASS.region, i) + ' ' + ('class' in d ? d['class'] : '');
};
ChartInternal.prototype.classEvent = function (d) {
    return this.generateClass(CLASS.eventRect, d.index);
};
ChartInternal.prototype.classTarget = function (id) {
    var $$ = this;
    var additionalClassSuffix = $$.config.data_classes[id], additionalClass = '';
    if (additionalClassSuffix) {
        additionalClass = ' ' + CLASS.target + '-' + additionalClassSuffix;
    }
    return $$.generateClass(CLASS.target, id) + additionalClass;
};
ChartInternal.prototype.classFocus = function (d) {
    return this.classFocused(d) + this.classDefocused(d);
};
ChartInternal.prototype.classFocused = function (d) {
    return ' ' + (this.focusedTargetIds.indexOf(d.id) >= 0 ? CLASS.focused : '');
};
ChartInternal.prototype.classDefocused = function (d) {
    return ' ' + (this.defocusedTargetIds.indexOf(d.id) >= 0 ? CLASS.defocused : '');
};
ChartInternal.prototype.classChartText = function (d) {
    return CLASS.chartText + this.classTarget(d.id);
};
ChartInternal.prototype.classChartLine = function (d) {
    return CLASS.chartLine + this.classTarget(d.id);
};
ChartInternal.prototype.classChartBar = function (d) {
    return CLASS.chartBar + this.classTarget(d.id);
};
ChartInternal.prototype.classChartArc = function (d) {
    return CLASS.chartArc + this.classTarget(d.data.id);
};
ChartInternal.prototype.getTargetSelectorSuffix = function (targetId) {
    return this.generateTargetClass(targetId)
        .replace(/([?!@#$%^&*()_=+,.<>'":;\[\]\/|~`{}\\])/g, '\\$1');
};
ChartInternal.prototype.selectorTarget = function (id, prefix) {
    return (prefix || '') + '.' + CLASS.target + this.getTargetSelectorSuffix(id);
};
ChartInternal.prototype.selectorTargets = function (ids, prefix) {
    var $$ = this;
    ids = ids || [];
    return ids.length ? ids.map(function (id) { return $$.selectorTarget(id, prefix); }) : null;
};
ChartInternal.prototype.selectorLegend = function (id) {
    return '.' + CLASS.legendItem + this.getTargetSelectorSuffix(id);
};
ChartInternal.prototype.selectorLegends = function (ids) {
    var $$ = this;
    return ids && ids.length ? ids.map(function (id) { return $$.selectorLegend(id); }) : null;
};
src/api.category.js000064400000001065151701472650010270 0ustar00import { Chart } from './core';

Chart.prototype.category = function (i, category) {
    var $$ = this.internal, config = $$.config;
    if (arguments.length > 1) {
        config.axis_x_categories[i] = category;
        $$.redraw();
    }
    return config.axis_x_categories[i];
};
Chart.prototype.categories = function (categories) {
    var $$ = this.internal, config = $$.config;
    if (!arguments.length) { return config.axis_x_categories; }
    config.axis_x_categories = categories;
    $$.redraw();
    return config.axis_x_categories;
};
src/subchart.js000064400000026164151701472650007525 0ustar00import CLASS from './class';
import { ChartInternal } from './core';
import { isFunction } from './util';

ChartInternal.prototype.initBrush = function (scale) {
    var $$ = this, d3 = $$.d3;
    // TODO: dynamically change brushY/brushX according to axis_rotated.
    $$.brush = ($$.config.axis_rotated ? d3.brushY() : d3.brushX()).on("brush", function () {
        var event = d3.event.sourceEvent;
        if (event && event.type === "zoom") { return; }
        $$.redrawForBrush();
    }).on("end", function () {
        var event = d3.event.sourceEvent;
        if (event && event.type === "zoom") { return; }
        if ($$.brush.empty() && event && event.type !== 'end') { $$.brush.clear(); }
    });
    $$.brush.updateExtent = function () {
        var range = this.scale.range(), extent;
        if ($$.config.axis_rotated) {
            extent = [[0, range[0]], [$$.width2, range[1]]];
        }
        else {
            extent = [[range[0], 0], [range[1], $$.height2]];
        }
        this.extent(extent);
        return this;
    };
    $$.brush.updateScale = function (scale) {
        this.scale = scale;
        return this;
    };
    $$.brush.update = function (scale) {
        this.updateScale(scale || $$.subX).updateExtent();
        $$.context.select('.' + CLASS.brush).call(this);
    };
    $$.brush.clear = function () {
        $$.context.select('.' + CLASS.brush).call($$.brush.move, null);
    };
    $$.brush.selection = function () {
        return d3.brushSelection($$.context.select('.' + CLASS.brush).node());
    };
    $$.brush.selectionAsValue = function (selectionAsValue, withTransition) {
        var selection, brush;
        if (selectionAsValue) {
            if ($$.context) {
                selection = [this.scale(selectionAsValue[0]), this.scale(selectionAsValue[1])];
                brush = $$.context.select('.' + CLASS.brush);
                if (withTransition) { brush = brush.transition(); }
                $$.brush.move(brush, selection);
            }
            return [];
        }
        selection = $$.brush.selection() || [0,0];
        return [this.scale.invert(selection[0]), this.scale.invert(selection[1])];
    };
    $$.brush.empty = function () {
        var selection = $$.brush.selection();
        return !selection || selection[0] === selection[1];
    };
    return $$.brush.updateScale(scale);
};
ChartInternal.prototype.initSubchart = function () {
    var $$ = this, config = $$.config,
        context = $$.context = $$.svg.append("g").attr("transform", $$.getTranslate('context')),
        visibility = config.subchart_show ? 'visible' : 'hidden';

    // set style
    context.style('visibility', visibility);

    // Define g for chart area
    context.append('g')
        .attr("clip-path", $$.clipPathForSubchart)
        .attr('class', CLASS.chart);

    // Define g for bar chart area
    context.select('.' + CLASS.chart).append("g")
        .attr("class", CLASS.chartBars);

    // Define g for line chart area
    context.select('.' + CLASS.chart).append("g")
        .attr("class", CLASS.chartLines);

    // Add extent rect for Brush
    context.append("g")
        .attr("clip-path", $$.clipPath)
        .attr("class", CLASS.brush);

    // ATTENTION: This must be called AFTER chart added
    // Add Axis
    $$.axes.subx = context.append("g")
        .attr("class", CLASS.axisX)
        .attr("transform", $$.getTranslate('subx'))
        .attr("clip-path", config.axis_rotated ? "" : $$.clipPathForXAxis);
};
ChartInternal.prototype.initSubchartBrush = function () {
    var $$ = this;
    // Add extent rect for Brush
    $$.initBrush($$.subX).updateExtent();
    $$.context.select('.' + CLASS.brush).call($$.brush);
};
ChartInternal.prototype.updateTargetsForSubchart = function (targets) {
    var $$ = this, context = $$.context, config = $$.config,
        contextLineEnter, contextLine, contextBarEnter, contextBar,
        classChartBar = $$.classChartBar.bind($$),
        classBars = $$.classBars.bind($$),
        classChartLine = $$.classChartLine.bind($$),
        classLines = $$.classLines.bind($$),
        classAreas = $$.classAreas.bind($$);

    if (config.subchart_show) {
        //-- Bar --//
        contextBar = context.select('.' + CLASS.chartBars).selectAll('.' + CLASS.chartBar)
            .data(targets);
        contextBarEnter = contextBar.enter().append('g')
            .style('opacity', 0);
        contextBarEnter.merge(contextBar)
            .attr('class', classChartBar);
        // Bars for each data
        contextBarEnter.append('g')
            .attr("class", classBars);

        //-- Line --//
        contextLine = context.select('.' + CLASS.chartLines).selectAll('.' + CLASS.chartLine)
            .data(targets);
        contextLineEnter = contextLine.enter().append('g')
            .style('opacity', 0);
        contextLineEnter.merge(contextLine)
            .attr('class', classChartLine);
        // Lines for each data
        contextLineEnter.append("g")
            .attr("class", classLines);
        // Area
        contextLineEnter.append("g")
            .attr("class", classAreas);

        //-- Brush --//
        context.selectAll('.' + CLASS.brush + ' rect')
            .attr(config.axis_rotated ? "width" : "height", config.axis_rotated ? $$.width2 : $$.height2);
    }
};
ChartInternal.prototype.updateBarForSubchart = function (durationForExit) {
    var $$ = this;
    var contextBar = $$.context.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar)
        .data($$.barData.bind($$));
    var contextBarEnter = contextBar.enter().append('path')
        .attr("class", $$.classBar.bind($$))
        .style("stroke", 'none')
        .style("fill", $$.color);
    contextBar.exit().transition().duration(durationForExit)
        .style('opacity', 0)
        .remove();
    $$.contextBar = contextBarEnter.merge(contextBar)
        .style("opacity", $$.initialOpacity.bind($$));
};
ChartInternal.prototype.redrawBarForSubchart = function (drawBarOnSub, withTransition, duration) {
    (withTransition ? this.contextBar.transition(Math.random().toString()).duration(duration) : this.contextBar)
        .attr('d', drawBarOnSub)
        .style('opacity', 1);
};
ChartInternal.prototype.updateLineForSubchart = function (durationForExit) {
    var $$ = this;
    var contextLine = $$.context.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line)
        .data($$.lineData.bind($$));
    var contextLineEnter = contextLine.enter().append('path')
        .attr('class', $$.classLine.bind($$))
        .style('stroke', $$.color);
    contextLine.exit().transition().duration(durationForExit)
        .style('opacity', 0)
        .remove();
    $$.contextLine = contextLineEnter.merge(contextLine)
        .style("opacity", $$.initialOpacity.bind($$));
};
ChartInternal.prototype.redrawLineForSubchart = function (drawLineOnSub, withTransition, duration) {
    (withTransition ? this.contextLine.transition(Math.random().toString()).duration(duration) : this.contextLine)
        .attr("d", drawLineOnSub)
        .style('opacity', 1);
};
ChartInternal.prototype.updateAreaForSubchart = function (durationForExit) {
    var $$ = this, d3 = $$.d3;
    var contextArea = $$.context.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area)
        .data($$.lineData.bind($$));
    var contextAreaEnter = contextArea.enter().append('path')
        .attr("class", $$.classArea.bind($$))
        .style("fill", $$.color)
        .style("opacity", function () { $$.orgAreaOpacity = +d3.select(this).style('opacity'); return 0; });
    contextArea.exit().transition().duration(durationForExit)
        .style('opacity', 0)
        .remove();
    $$.contextArea = contextAreaEnter.merge(contextArea)
        .style("opacity", 0);
};
ChartInternal.prototype.redrawAreaForSubchart = function (drawAreaOnSub, withTransition, duration) {
    (withTransition ? this.contextArea.transition(Math.random().toString()).duration(duration) : this.contextArea)
        .attr("d", drawAreaOnSub)
        .style("fill", this.color)
        .style("opacity", this.orgAreaOpacity);
};
ChartInternal.prototype.redrawSubchart = function (withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices) {
    var $$ = this, d3 = $$.d3, config = $$.config,
        drawAreaOnSub, drawBarOnSub, drawLineOnSub;

    $$.context.style('visibility', config.subchart_show ? 'visible' : 'hidden');

    // subchart
    if (config.subchart_show) {
        // reflect main chart to extent on subchart if zoomed
        if (d3.event && d3.event.type === 'zoom') {
            $$.brush.selectionAsValue($$.x.orgDomain());
        }
        // update subchart elements if needed
        if (withSubchart) {
            // extent rect
            if (!$$.brush.empty()) {
                $$.brush.selectionAsValue($$.x.orgDomain());
            }
            // setup drawer - MEMO: this must be called after axis updated
            drawAreaOnSub = $$.generateDrawArea(areaIndices, true);
            drawBarOnSub = $$.generateDrawBar(barIndices, true);
            drawLineOnSub = $$.generateDrawLine(lineIndices, true);

            $$.updateBarForSubchart(duration);
            $$.updateLineForSubchart(duration);
            $$.updateAreaForSubchart(duration);

            $$.redrawBarForSubchart(drawBarOnSub, duration, duration);
            $$.redrawLineForSubchart(drawLineOnSub, duration, duration);
            $$.redrawAreaForSubchart(drawAreaOnSub, duration, duration);
        }
    }
};
ChartInternal.prototype.redrawForBrush = function () {
    var $$ = this, x = $$.x, d3 = $$.d3, s;
    $$.redraw({
        withTransition: false,
        withY: $$.config.zoom_rescale,
        withSubchart: false,
        withUpdateXDomain: true,
        withEventRect: false,
        withDimension: false
    });
    // update zoom transation binded to event rect
    s = d3.event.selection || $$.brush.scale.range();
    $$.main.select('.' + CLASS.eventRect).call($$.zoom.transform, d3.zoomIdentity
                                               .scale($$.width / (s[1] - s[0]))
                                               .translate(-s[0], 0));
    $$.config.subchart_onbrush.call($$.api, x.orgDomain());
};
ChartInternal.prototype.transformContext = function (withTransition, transitions) {
    var $$ = this, subXAxis;
    if (transitions && transitions.axisSubX) {
        subXAxis = transitions.axisSubX;
    } else {
        subXAxis = $$.context.select('.' + CLASS.axisX);
        if (withTransition) { subXAxis = subXAxis.transition(); }
    }
    $$.context.attr("transform", $$.getTranslate('context'));
    subXAxis.attr("transform", $$.getTranslate('subx'));
};
ChartInternal.prototype.getDefaultSelection = function () {
    var $$ = this, config = $$.config,
        selection = isFunction(config.axis_x_selection) ? config.axis_x_selection($$.getXDomain($$.data.targets)) : config.axis_x_selection;
    if ($$.isTimeSeries()) {
        selection = [$$.parseDate(selection[0]), $$.parseDate(selection[1])];
    }
    return selection;
};
src/polyfill.js000064400000214266151701472650007546 0ustar00/* jshint ignore:start */

// SVGPathSeg API polyfill
// https://github.com/progers/pathseg
//
// This is a drop-in replacement for the SVGPathSeg and SVGPathSegList APIs that were removed from
// SVG2 (https://lists.w3.org/Archives/Public/www-svg/2015Jun/0044.html), including the latest spec
// changes which were implemented in Firefox 43 and Chrome 46.

(function () {
    "use strict";
    if (!("SVGPathSeg" in window)) {
        // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSeg
        window.SVGPathSeg = function (type, typeAsLetter, owningPathSegList) {
            this.pathSegType = type;
            this.pathSegTypeAsLetter = typeAsLetter;
            this._owningPathSegList = owningPathSegList;
        }

        window.SVGPathSeg.prototype.classname = "SVGPathSeg";

        window.SVGPathSeg.PATHSEG_UNKNOWN = 0;
        window.SVGPathSeg.PATHSEG_CLOSEPATH = 1;
        window.SVGPathSeg.PATHSEG_MOVETO_ABS = 2;
        window.SVGPathSeg.PATHSEG_MOVETO_REL = 3;
        window.SVGPathSeg.PATHSEG_LINETO_ABS = 4;
        window.SVGPathSeg.PATHSEG_LINETO_REL = 5;
        window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS = 6;
        window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL = 7;
        window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS = 8;
        window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL = 9;
        window.SVGPathSeg.PATHSEG_ARC_ABS = 10;
        window.SVGPathSeg.PATHSEG_ARC_REL = 11;
        window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS = 12;
        window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL = 13;
        window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS = 14;
        window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL = 15;
        window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS = 16;
        window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL = 17;
        window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS = 18;
        window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL = 19;

        // Notify owning PathSegList on any changes so they can be synchronized back to the path element.
        window.SVGPathSeg.prototype._segmentChanged = function () {
            if (this._owningPathSegList)
                this._owningPathSegList.segmentChanged(this);
        }

        window.SVGPathSegClosePath = function (owningPathSegList) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CLOSEPATH, "z", owningPathSegList);
        }
        window.SVGPathSegClosePath.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegClosePath.prototype.toString = function () {
            return "[object SVGPathSegClosePath]";
        }
        window.SVGPathSegClosePath.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter;
        }
        window.SVGPathSegClosePath.prototype.clone = function () {
            return new window.SVGPathSegClosePath(undefined);
        }

        window.SVGPathSegMovetoAbs = function (owningPathSegList, x, y) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_MOVETO_ABS, "M", owningPathSegList);
            this._x = x;
            this._y = y;
        }
        window.SVGPathSegMovetoAbs.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegMovetoAbs.prototype.toString = function () {
            return "[object SVGPathSegMovetoAbs]";
        }
        window.SVGPathSegMovetoAbs.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x + " " + this._y;
        }
        window.SVGPathSegMovetoAbs.prototype.clone = function () {
            return new window.SVGPathSegMovetoAbs(undefined, this._x, this._y);
        }
        Object.defineProperty(window.SVGPathSegMovetoAbs.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegMovetoAbs.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegMovetoRel = function (owningPathSegList, x, y) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_MOVETO_REL, "m", owningPathSegList);
            this._x = x;
            this._y = y;
        }
        window.SVGPathSegMovetoRel.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegMovetoRel.prototype.toString = function () {
            return "[object SVGPathSegMovetoRel]";
        }
        window.SVGPathSegMovetoRel.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x + " " + this._y;
        }
        window.SVGPathSegMovetoRel.prototype.clone = function () {
            return new window.SVGPathSegMovetoRel(undefined, this._x, this._y);
        }
        Object.defineProperty(window.SVGPathSegMovetoRel.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegMovetoRel.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegLinetoAbs = function (owningPathSegList, x, y) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_LINETO_ABS, "L", owningPathSegList);
            this._x = x;
            this._y = y;
        }
        window.SVGPathSegLinetoAbs.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegLinetoAbs.prototype.toString = function () {
            return "[object SVGPathSegLinetoAbs]";
        }
        window.SVGPathSegLinetoAbs.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x + " " + this._y;
        }
        window.SVGPathSegLinetoAbs.prototype.clone = function () {
            return new window.SVGPathSegLinetoAbs(undefined, this._x, this._y);
        }
        Object.defineProperty(window.SVGPathSegLinetoAbs.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegLinetoAbs.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegLinetoRel = function (owningPathSegList, x, y) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_LINETO_REL, "l", owningPathSegList);
            this._x = x;
            this._y = y;
        }
        window.SVGPathSegLinetoRel.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegLinetoRel.prototype.toString = function () {
            return "[object SVGPathSegLinetoRel]";
        }
        window.SVGPathSegLinetoRel.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x + " " + this._y;
        }
        window.SVGPathSegLinetoRel.prototype.clone = function () {
            return new window.SVGPathSegLinetoRel(undefined, this._x, this._y);
        }
        Object.defineProperty(window.SVGPathSegLinetoRel.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegLinetoRel.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegCurvetoCubicAbs = function (owningPathSegList, x, y, x1, y1, x2, y2) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS, "C", owningPathSegList);
            this._x = x;
            this._y = y;
            this._x1 = x1;
            this._y1 = y1;
            this._x2 = x2;
            this._y2 = y2;
        }
        window.SVGPathSegCurvetoCubicAbs.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegCurvetoCubicAbs.prototype.toString = function () {
            return "[object SVGPathSegCurvetoCubicAbs]";
        }
        window.SVGPathSegCurvetoCubicAbs.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y;
        }
        window.SVGPathSegCurvetoCubicAbs.prototype.clone = function () {
            return new window.SVGPathSegCurvetoCubicAbs(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2);
        }
        Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, "x1", {
            get: function () {
                return this._x1;
            },
            set: function (x1) {
                this._x1 = x1;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, "y1", {
            get: function () {
                return this._y1;
            },
            set: function (y1) {
                this._y1 = y1;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, "x2", {
            get: function () {
                return this._x2;
            },
            set: function (x2) {
                this._x2 = x2;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, "y2", {
            get: function () {
                return this._y2;
            },
            set: function (y2) {
                this._y2 = y2;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegCurvetoCubicRel = function (owningPathSegList, x, y, x1, y1, x2, y2) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL, "c", owningPathSegList);
            this._x = x;
            this._y = y;
            this._x1 = x1;
            this._y1 = y1;
            this._x2 = x2;
            this._y2 = y2;
        }
        window.SVGPathSegCurvetoCubicRel.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegCurvetoCubicRel.prototype.toString = function () {
            return "[object SVGPathSegCurvetoCubicRel]";
        }
        window.SVGPathSegCurvetoCubicRel.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y;
        }
        window.SVGPathSegCurvetoCubicRel.prototype.clone = function () {
            return new window.SVGPathSegCurvetoCubicRel(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2);
        }
        Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, "x1", {
            get: function () {
                return this._x1;
            },
            set: function (x1) {
                this._x1 = x1;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, "y1", {
            get: function () {
                return this._y1;
            },
            set: function (y1) {
                this._y1 = y1;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, "x2", {
            get: function () {
                return this._x2;
            },
            set: function (x2) {
                this._x2 = x2;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, "y2", {
            get: function () {
                return this._y2;
            },
            set: function (y2) {
                this._y2 = y2;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegCurvetoQuadraticAbs = function (owningPathSegList, x, y, x1, y1) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS, "Q", owningPathSegList);
            this._x = x;
            this._y = y;
            this._x1 = x1;
            this._y1 = y1;
        }
        window.SVGPathSegCurvetoQuadraticAbs.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegCurvetoQuadraticAbs.prototype.toString = function () {
            return "[object SVGPathSegCurvetoQuadraticAbs]";
        }
        window.SVGPathSegCurvetoQuadraticAbs.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x + " " + this._y;
        }
        window.SVGPathSegCurvetoQuadraticAbs.prototype.clone = function () {
            return new window.SVGPathSegCurvetoQuadraticAbs(undefined, this._x, this._y, this._x1, this._y1);
        }
        Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype, "x1", {
            get: function () {
                return this._x1;
            },
            set: function (x1) {
                this._x1 = x1;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype, "y1", {
            get: function () {
                return this._y1;
            },
            set: function (y1) {
                this._y1 = y1;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegCurvetoQuadraticRel = function (owningPathSegList, x, y, x1, y1) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL, "q", owningPathSegList);
            this._x = x;
            this._y = y;
            this._x1 = x1;
            this._y1 = y1;
        }
        window.SVGPathSegCurvetoQuadraticRel.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegCurvetoQuadraticRel.prototype.toString = function () {
            return "[object SVGPathSegCurvetoQuadraticRel]";
        }
        window.SVGPathSegCurvetoQuadraticRel.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x + " " + this._y;
        }
        window.SVGPathSegCurvetoQuadraticRel.prototype.clone = function () {
            return new window.SVGPathSegCurvetoQuadraticRel(undefined, this._x, this._y, this._x1, this._y1);
        }
        Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype, "x1", {
            get: function () {
                return this._x1;
            },
            set: function (x1) {
                this._x1 = x1;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype, "y1", {
            get: function () {
                return this._y1;
            },
            set: function (y1) {
                this._y1 = y1;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegArcAbs = function (owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_ARC_ABS, "A", owningPathSegList);
            this._x = x;
            this._y = y;
            this._r1 = r1;
            this._r2 = r2;
            this._angle = angle;
            this._largeArcFlag = largeArcFlag;
            this._sweepFlag = sweepFlag;
        }
        window.SVGPathSegArcAbs.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegArcAbs.prototype.toString = function () {
            return "[object SVGPathSegArcAbs]";
        }
        window.SVGPathSegArcAbs.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._r1 + " " + this._r2 + " " + this._angle + " " + (this._largeArcFlag ? "1" : "0") + " " + (this._sweepFlag ? "1" : "0") + " " +
                this._x + " " + this._y;
        }
        window.SVGPathSegArcAbs.prototype.clone = function () {
            return new window.SVGPathSegArcAbs(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag);
        }
        Object.defineProperty(window.SVGPathSegArcAbs.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegArcAbs.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegArcAbs.prototype, "r1", {
            get: function () {
                return this._r1;
            },
            set: function (r1) {
                this._r1 = r1;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegArcAbs.prototype, "r2", {
            get: function () {
                return this._r2;
            },
            set: function (r2) {
                this._r2 = r2;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegArcAbs.prototype, "angle", {
            get: function () {
                return this._angle;
            },
            set: function (angle) {
                this._angle = angle;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegArcAbs.prototype, "largeArcFlag", {
            get: function () {
                return this._largeArcFlag;
            },
            set: function (largeArcFlag) {
                this._largeArcFlag = largeArcFlag;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegArcAbs.prototype, "sweepFlag", {
            get: function () {
                return this._sweepFlag;
            },
            set: function (sweepFlag) {
                this._sweepFlag = sweepFlag;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegArcRel = function (owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_ARC_REL, "a", owningPathSegList);
            this._x = x;
            this._y = y;
            this._r1 = r1;
            this._r2 = r2;
            this._angle = angle;
            this._largeArcFlag = largeArcFlag;
            this._sweepFlag = sweepFlag;
        }
        window.SVGPathSegArcRel.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegArcRel.prototype.toString = function () {
            return "[object SVGPathSegArcRel]";
        }
        window.SVGPathSegArcRel.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._r1 + " " + this._r2 + " " + this._angle + " " + (this._largeArcFlag ? "1" : "0") + " " + (this._sweepFlag ? "1" : "0") + " " +
                this._x + " " + this._y;
        }
        window.SVGPathSegArcRel.prototype.clone = function () {
            return new window.SVGPathSegArcRel(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag);
        }
        Object.defineProperty(window.SVGPathSegArcRel.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegArcRel.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegArcRel.prototype, "r1", {
            get: function () {
                return this._r1;
            },
            set: function (r1) {
                this._r1 = r1;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegArcRel.prototype, "r2", {
            get: function () {
                return this._r2;
            },
            set: function (r2) {
                this._r2 = r2;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegArcRel.prototype, "angle", {
            get: function () {
                return this._angle;
            },
            set: function (angle) {
                this._angle = angle;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegArcRel.prototype, "largeArcFlag", {
            get: function () {
                return this._largeArcFlag;
            },
            set: function (largeArcFlag) {
                this._largeArcFlag = largeArcFlag;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegArcRel.prototype, "sweepFlag", {
            get: function () {
                return this._sweepFlag;
            },
            set: function (sweepFlag) {
                this._sweepFlag = sweepFlag;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegLinetoHorizontalAbs = function (owningPathSegList, x) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS, "H", owningPathSegList);
            this._x = x;
        }
        window.SVGPathSegLinetoHorizontalAbs.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegLinetoHorizontalAbs.prototype.toString = function () {
            return "[object SVGPathSegLinetoHorizontalAbs]";
        }
        window.SVGPathSegLinetoHorizontalAbs.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x;
        }
        window.SVGPathSegLinetoHorizontalAbs.prototype.clone = function () {
            return new window.SVGPathSegLinetoHorizontalAbs(undefined, this._x);
        }
        Object.defineProperty(window.SVGPathSegLinetoHorizontalAbs.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegLinetoHorizontalRel = function (owningPathSegList, x) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL, "h", owningPathSegList);
            this._x = x;
        }
        window.SVGPathSegLinetoHorizontalRel.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegLinetoHorizontalRel.prototype.toString = function () {
            return "[object SVGPathSegLinetoHorizontalRel]";
        }
        window.SVGPathSegLinetoHorizontalRel.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x;
        }
        window.SVGPathSegLinetoHorizontalRel.prototype.clone = function () {
            return new window.SVGPathSegLinetoHorizontalRel(undefined, this._x);
        }
        Object.defineProperty(window.SVGPathSegLinetoHorizontalRel.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegLinetoVerticalAbs = function (owningPathSegList, y) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS, "V", owningPathSegList);
            this._y = y;
        }
        window.SVGPathSegLinetoVerticalAbs.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegLinetoVerticalAbs.prototype.toString = function () {
            return "[object SVGPathSegLinetoVerticalAbs]";
        }
        window.SVGPathSegLinetoVerticalAbs.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._y;
        }
        window.SVGPathSegLinetoVerticalAbs.prototype.clone = function () {
            return new window.SVGPathSegLinetoVerticalAbs(undefined, this._y);
        }
        Object.defineProperty(window.SVGPathSegLinetoVerticalAbs.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegLinetoVerticalRel = function (owningPathSegList, y) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL, "v", owningPathSegList);
            this._y = y;
        }
        window.SVGPathSegLinetoVerticalRel.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegLinetoVerticalRel.prototype.toString = function () {
            return "[object SVGPathSegLinetoVerticalRel]";
        }
        window.SVGPathSegLinetoVerticalRel.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._y;
        }
        window.SVGPathSegLinetoVerticalRel.prototype.clone = function () {
            return new window.SVGPathSegLinetoVerticalRel(undefined, this._y);
        }
        Object.defineProperty(window.SVGPathSegLinetoVerticalRel.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegCurvetoCubicSmoothAbs = function (owningPathSegList, x, y, x2, y2) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS, "S", owningPathSegList);
            this._x = x;
            this._y = y;
            this._x2 = x2;
            this._y2 = y2;
        }
        window.SVGPathSegCurvetoCubicSmoothAbs.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegCurvetoCubicSmoothAbs.prototype.toString = function () {
            return "[object SVGPathSegCurvetoCubicSmoothAbs]";
        }
        window.SVGPathSegCurvetoCubicSmoothAbs.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y;
        }
        window.SVGPathSegCurvetoCubicSmoothAbs.prototype.clone = function () {
            return new window.SVGPathSegCurvetoCubicSmoothAbs(undefined, this._x, this._y, this._x2, this._y2);
        }
        Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothAbs.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothAbs.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothAbs.prototype, "x2", {
            get: function () {
                return this._x2;
            },
            set: function (x2) {
                this._x2 = x2;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothAbs.prototype, "y2", {
            get: function () {
                return this._y2;
            },
            set: function (y2) {
                this._y2 = y2;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegCurvetoCubicSmoothRel = function (owningPathSegList, x, y, x2, y2) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL, "s", owningPathSegList);
            this._x = x;
            this._y = y;
            this._x2 = x2;
            this._y2 = y2;
        }
        window.SVGPathSegCurvetoCubicSmoothRel.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegCurvetoCubicSmoothRel.prototype.toString = function () {
            return "[object SVGPathSegCurvetoCubicSmoothRel]";
        }
        window.SVGPathSegCurvetoCubicSmoothRel.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y;
        }
        window.SVGPathSegCurvetoCubicSmoothRel.prototype.clone = function () {
            return new window.SVGPathSegCurvetoCubicSmoothRel(undefined, this._x, this._y, this._x2, this._y2);
        }
        Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothRel.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothRel.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothRel.prototype, "x2", {
            get: function () {
                return this._x2;
            },
            set: function (x2) {
                this._x2 = x2;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothRel.prototype, "y2", {
            get: function () {
                return this._y2;
            },
            set: function (y2) {
                this._y2 = y2;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegCurvetoQuadraticSmoothAbs = function (owningPathSegList, x, y) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS, "T", owningPathSegList);
            this._x = x;
            this._y = y;
        }
        window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype.toString = function () {
            return "[object SVGPathSegCurvetoQuadraticSmoothAbs]";
        }
        window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x + " " + this._y;
        }
        window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype.clone = function () {
            return new window.SVGPathSegCurvetoQuadraticSmoothAbs(undefined, this._x, this._y);
        }
        Object.defineProperty(window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });

        window.SVGPathSegCurvetoQuadraticSmoothRel = function (owningPathSegList, x, y) {
            window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL, "t", owningPathSegList);
            this._x = x;
            this._y = y;
        }
        window.SVGPathSegCurvetoQuadraticSmoothRel.prototype = Object.create(window.SVGPathSeg.prototype);
        window.SVGPathSegCurvetoQuadraticSmoothRel.prototype.toString = function () {
            return "[object SVGPathSegCurvetoQuadraticSmoothRel]";
        }
        window.SVGPathSegCurvetoQuadraticSmoothRel.prototype._asPathString = function () {
            return this.pathSegTypeAsLetter + " " + this._x + " " + this._y;
        }
        window.SVGPathSegCurvetoQuadraticSmoothRel.prototype.clone = function () {
            return new window.SVGPathSegCurvetoQuadraticSmoothRel(undefined, this._x, this._y);
        }
        Object.defineProperty(window.SVGPathSegCurvetoQuadraticSmoothRel.prototype, "x", {
            get: function () {
                return this._x;
            },
            set: function (x) {
                this._x = x;
                this._segmentChanged();
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathSegCurvetoQuadraticSmoothRel.prototype, "y", {
            get: function () {
                return this._y;
            },
            set: function (y) {
                this._y = y;
                this._segmentChanged();
            },
            enumerable: true
        });

        // Add createSVGPathSeg* functions to window.SVGPathElement.
        // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-Interfacewindow.SVGPathElement.
        window.SVGPathElement.prototype.createSVGPathSegClosePath = function () {
            return new window.SVGPathSegClosePath(undefined);
        }
        window.SVGPathElement.prototype.createSVGPathSegMovetoAbs = function (x, y) {
            return new window.SVGPathSegMovetoAbs(undefined, x, y);
        }
        window.SVGPathElement.prototype.createSVGPathSegMovetoRel = function (x, y) {
            return new window.SVGPathSegMovetoRel(undefined, x, y);
        }
        window.SVGPathElement.prototype.createSVGPathSegLinetoAbs = function (x, y) {
            return new window.SVGPathSegLinetoAbs(undefined, x, y);
        }
        window.SVGPathElement.prototype.createSVGPathSegLinetoRel = function (x, y) {
            return new window.SVGPathSegLinetoRel(undefined, x, y);
        }
        window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicAbs = function (x, y, x1, y1, x2, y2) {
            return new window.SVGPathSegCurvetoCubicAbs(undefined, x, y, x1, y1, x2, y2);
        }
        window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicRel = function (x, y, x1, y1, x2, y2) {
            return new window.SVGPathSegCurvetoCubicRel(undefined, x, y, x1, y1, x2, y2);
        }
        window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticAbs = function (x, y, x1, y1) {
            return new window.SVGPathSegCurvetoQuadraticAbs(undefined, x, y, x1, y1);
        }
        window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticRel = function (x, y, x1, y1) {
            return new window.SVGPathSegCurvetoQuadraticRel(undefined, x, y, x1, y1);
        }
        window.SVGPathElement.prototype.createSVGPathSegArcAbs = function (x, y, r1, r2, angle, largeArcFlag, sweepFlag) {
            return new window.SVGPathSegArcAbs(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag);
        }
        window.SVGPathElement.prototype.createSVGPathSegArcRel = function (x, y, r1, r2, angle, largeArcFlag, sweepFlag) {
            return new window.SVGPathSegArcRel(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag);
        }
        window.SVGPathElement.prototype.createSVGPathSegLinetoHorizontalAbs = function (x) {
            return new window.SVGPathSegLinetoHorizontalAbs(undefined, x);
        }
        window.SVGPathElement.prototype.createSVGPathSegLinetoHorizontalRel = function (x) {
            return new window.SVGPathSegLinetoHorizontalRel(undefined, x);
        }
        window.SVGPathElement.prototype.createSVGPathSegLinetoVerticalAbs = function (y) {
            return new window.SVGPathSegLinetoVerticalAbs(undefined, y);
        }
        window.SVGPathElement.prototype.createSVGPathSegLinetoVerticalRel = function (y) {
            return new window.SVGPathSegLinetoVerticalRel(undefined, y);
        }
        window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothAbs = function (x, y, x2, y2) {
            return new window.SVGPathSegCurvetoCubicSmoothAbs(undefined, x, y, x2, y2);
        }
        window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothRel = function (x, y, x2, y2) {
            return new window.SVGPathSegCurvetoCubicSmoothRel(undefined, x, y, x2, y2);
        }
        window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothAbs = function (x, y) {
            return new window.SVGPathSegCurvetoQuadraticSmoothAbs(undefined, x, y);
        }
        window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothRel = function (x, y) {
            return new window.SVGPathSegCurvetoQuadraticSmoothRel(undefined, x, y);
        }

        if (!("getPathSegAtLength" in window.SVGPathElement.prototype)) {
            // Add getPathSegAtLength to SVGPathElement.
            // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-__svg__SVGPathElement__getPathSegAtLength
            // This polyfill requires SVGPathElement.getTotalLength to implement the distance-along-a-path algorithm.
            window.SVGPathElement.prototype.getPathSegAtLength = function (distance) {
                if (distance === undefined || !isFinite(distance))
                    throw "Invalid arguments.";

                var measurementElement = document.createElementNS("http://www.w3.org/2000/svg", "path");
                measurementElement.setAttribute("d", this.getAttribute("d"));
                var lastPathSegment = measurementElement.pathSegList.numberOfItems - 1;

                // If the path is empty, return 0.
                if (lastPathSegment <= 0)
                    return 0;

                do {
                    measurementElement.pathSegList.removeItem(lastPathSegment);
                    if (distance > measurementElement.getTotalLength())
                        break;
                    lastPathSegment--;
                } while (lastPathSegment > 0);
                return lastPathSegment;
            }
        }
    }

    if (!("SVGPathSegList" in window)) {
        // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSegList
        window.SVGPathSegList = function (pathElement) {
            this._pathElement = pathElement;
            this._list = this._parsePath(this._pathElement.getAttribute("d"));

            // Use a MutationObserver to catch changes to the path's "d" attribute.
            this._mutationObserverConfig = {
                "attributes": true,
                "attributeFilter": ["d"]
            };
            this._pathElementMutationObserver = new MutationObserver(this._updateListFromPathMutations.bind(this));
            this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig);
        }

        window.SVGPathSegList.prototype.classname = "SVGPathSegList";

        Object.defineProperty(window.SVGPathSegList.prototype, "numberOfItems", {
            get: function () {
                this._checkPathSynchronizedToList();
                return this._list.length;
            },
            enumerable: true
        });

        // Add the pathSegList accessors to window.SVGPathElement.
        // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGAnimatedPathData
        Object.defineProperty(window.SVGPathElement.prototype, "pathSegList", {
            get: function () {
                if (!this._pathSegList)
                    this._pathSegList = new window.SVGPathSegList(this);
                return this._pathSegList;
            },
            enumerable: true
        });
        // FIXME: The following are not implemented and simply return window.SVGPathElement.pathSegList.
        Object.defineProperty(window.SVGPathElement.prototype, "normalizedPathSegList", {
            get: function () {
                return this.pathSegList;
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathElement.prototype, "animatedPathSegList", {
            get: function () {
                return this.pathSegList;
            },
            enumerable: true
        });
        Object.defineProperty(window.SVGPathElement.prototype, "animatedNormalizedPathSegList", {
            get: function () {
                return this.pathSegList;
            },
            enumerable: true
        });

        // Process any pending mutations to the path element and update the list as needed.
        // This should be the first call of all public functions and is needed because
        // MutationObservers are not synchronous so we can have pending asynchronous mutations.
        window.SVGPathSegList.prototype._checkPathSynchronizedToList = function () {
            this._updateListFromPathMutations(this._pathElementMutationObserver.takeRecords());
        }

        window.SVGPathSegList.prototype._updateListFromPathMutations = function (mutationRecords) {
            if (!this._pathElement)
                return;
            var hasPathMutations = false;
            mutationRecords.forEach(function (record) {
                if (record.attributeName == "d")
                    hasPathMutations = true;
            });
            if (hasPathMutations)
                this._list = this._parsePath(this._pathElement.getAttribute("d"));
        }

        // Serialize the list and update the path's 'd' attribute.
        window.SVGPathSegList.prototype._writeListToPath = function () {
            this._pathElementMutationObserver.disconnect();
            this._pathElement.setAttribute("d", window.SVGPathSegList._pathSegArrayAsString(this._list));
            this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig);
        }

        // When a path segment changes the list needs to be synchronized back to the path element.
        window.SVGPathSegList.prototype.segmentChanged = function (pathSeg) {
            this._writeListToPath();
        }

        window.SVGPathSegList.prototype.clear = function () {
            this._checkPathSynchronizedToList();

            this._list.forEach(function (pathSeg) {
                pathSeg._owningPathSegList = null;
            });
            this._list = [];
            this._writeListToPath();
        }

        window.SVGPathSegList.prototype.initialize = function (newItem) {
            this._checkPathSynchronizedToList();

            this._list = [newItem];
            newItem._owningPathSegList = this;
            this._writeListToPath();
            return newItem;
        }

        window.SVGPathSegList.prototype._checkValidIndex = function (index) {
            if (isNaN(index) || index < 0 || index >= this.numberOfItems)
                throw "INDEX_SIZE_ERR";
        }

        window.SVGPathSegList.prototype.getItem = function (index) {
            this._checkPathSynchronizedToList();

            this._checkValidIndex(index);
            return this._list[index];
        }

        window.SVGPathSegList.prototype.insertItemBefore = function (newItem, index) {
            this._checkPathSynchronizedToList();

            // Spec: If the index is greater than or equal to numberOfItems, then the new item is appended to the end of the list.
            if (index > this.numberOfItems)
                index = this.numberOfItems;
            if (newItem._owningPathSegList) {
                // SVG2 spec says to make a copy.
                newItem = newItem.clone();
            }
            this._list.splice(index, 0, newItem);
            newItem._owningPathSegList = this;
            this._writeListToPath();
            return newItem;
        }

        window.SVGPathSegList.prototype.replaceItem = function (newItem, index) {
            this._checkPathSynchronizedToList();

            if (newItem._owningPathSegList) {
                // SVG2 spec says to make a copy.
                newItem = newItem.clone();
            }
            this._checkValidIndex(index);
            this._list[index] = newItem;
            newItem._owningPathSegList = this;
            this._writeListToPath();
            return newItem;
        }

        window.SVGPathSegList.prototype.removeItem = function (index) {
            this._checkPathSynchronizedToList();

            this._checkValidIndex(index);
            var item = this._list[index];
            this._list.splice(index, 1);
            this._writeListToPath();
            return item;
        }

        window.SVGPathSegList.prototype.appendItem = function (newItem) {
            this._checkPathSynchronizedToList();

            if (newItem._owningPathSegList) {
                // SVG2 spec says to make a copy.
                newItem = newItem.clone();
            }
            this._list.push(newItem);
            newItem._owningPathSegList = this;
            // TODO: Optimize this to just append to the existing attribute.
            this._writeListToPath();
            return newItem;
        }

        window.SVGPathSegList._pathSegArrayAsString = function (pathSegArray) {
            var string = "";
            var first = true;
            pathSegArray.forEach(function (pathSeg) {
                if (first) {
                    first = false;
                    string += pathSeg._asPathString();
                } else {
                    string += " " + pathSeg._asPathString();
                }
            });
            return string;
        }

        // This closely follows SVGPathParser::parsePath from Source/core/svg/SVGPathParser.cpp.
        window.SVGPathSegList.prototype._parsePath = function (string) {
            if (!string || string.length == 0)
                return [];

            var owningPathSegList = this;

            var Builder = function () {
                this.pathSegList = [];
            }

            Builder.prototype.appendSegment = function (pathSeg) {
                this.pathSegList.push(pathSeg);
            }

            var Source = function (string) {
                this._string = string;
                this._currentIndex = 0;
                this._endIndex = this._string.length;
                this._previousCommand = window.SVGPathSeg.PATHSEG_UNKNOWN;

                this._skipOptionalSpaces();
            }

            Source.prototype._isCurrentSpace = function () {
                var character = this._string[this._currentIndex];
                return character <= " " && (character == " " || character == "\n" || character == "\t" || character == "\r" || character == "\f");
            }

            Source.prototype._skipOptionalSpaces = function () {
                while (this._currentIndex < this._endIndex && this._isCurrentSpace())
                    this._currentIndex++;
                return this._currentIndex < this._endIndex;
            }

            Source.prototype._skipOptionalSpacesOrDelimiter = function () {
                if (this._currentIndex < this._endIndex && !this._isCurrentSpace() && this._string.charAt(this._currentIndex) != ",")
                    return false;
                if (this._skipOptionalSpaces()) {
                    if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == ",") {
                        this._currentIndex++;
                        this._skipOptionalSpaces();
                    }
                }
                return this._currentIndex < this._endIndex;
            }

            Source.prototype.hasMoreData = function () {
                return this._currentIndex < this._endIndex;
            }

            Source.prototype.peekSegmentType = function () {
                var lookahead = this._string[this._currentIndex];
                return this._pathSegTypeFromChar(lookahead);
            }

            Source.prototype._pathSegTypeFromChar = function (lookahead) {
                switch (lookahead) {
                case "Z":
                case "z":
                    return window.SVGPathSeg.PATHSEG_CLOSEPATH;
                case "M":
                    return window.SVGPathSeg.PATHSEG_MOVETO_ABS;
                case "m":
                    return window.SVGPathSeg.PATHSEG_MOVETO_REL;
                case "L":
                    return window.SVGPathSeg.PATHSEG_LINETO_ABS;
                case "l":
                    return window.SVGPathSeg.PATHSEG_LINETO_REL;
                case "C":
                    return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS;
                case "c":
                    return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL;
                case "Q":
                    return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS;
                case "q":
                    return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL;
                case "A":
                    return window.SVGPathSeg.PATHSEG_ARC_ABS;
                case "a":
                    return window.SVGPathSeg.PATHSEG_ARC_REL;
                case "H":
                    return window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS;
                case "h":
                    return window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL;
                case "V":
                    return window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS;
                case "v":
                    return window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL;
                case "S":
                    return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS;
                case "s":
                    return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL;
                case "T":
                    return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS;
                case "t":
                    return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL;
                default:
                    return window.SVGPathSeg.PATHSEG_UNKNOWN;
                }
            }

            Source.prototype._nextCommandHelper = function (lookahead, previousCommand) {
                // Check for remaining coordinates in the current command.
                if ((lookahead == "+" || lookahead == "-" || lookahead == "." || (lookahead >= "0" && lookahead <= "9")) && previousCommand != window.SVGPathSeg.PATHSEG_CLOSEPATH) {
                    if (previousCommand == window.SVGPathSeg.PATHSEG_MOVETO_ABS)
                        return window.SVGPathSeg.PATHSEG_LINETO_ABS;
                    if (previousCommand == window.SVGPathSeg.PATHSEG_MOVETO_REL)
                        return window.SVGPathSeg.PATHSEG_LINETO_REL;
                    return previousCommand;
                }
                return window.SVGPathSeg.PATHSEG_UNKNOWN;
            }

            Source.prototype.initialCommandIsMoveTo = function () {
                // If the path is empty it is still valid, so return true.
                if (!this.hasMoreData())
                    return true;
                var command = this.peekSegmentType();
                // Path must start with moveTo.
                return command == window.SVGPathSeg.PATHSEG_MOVETO_ABS || command == window.SVGPathSeg.PATHSEG_MOVETO_REL;
            }

            // Parse a number from an SVG path. This very closely follows genericParseNumber(...) from Source/core/svg/SVGParserUtilities.cpp.
            // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-PathDataBNF
            Source.prototype._parseNumber = function () {
                var exponent = 0;
                var integer = 0;
                var frac = 1;
                var decimal = 0;
                var sign = 1;
                var expsign = 1;

                var startIndex = this._currentIndex;

                this._skipOptionalSpaces();

                // Read the sign.
                if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == "+")
                    this._currentIndex++;
                else if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == "-") {
                    this._currentIndex++;
                    sign = -1;
                }

                if (this._currentIndex == this._endIndex || ((this._string.charAt(this._currentIndex) < "0" || this._string.charAt(this._currentIndex) > "9") && this._string.charAt(this._currentIndex) !=
                        "."))
                    // The first character of a number must be one of [0-9+-.].
                    return undefined;

                // Read the integer part, build right-to-left.
                var startIntPartIndex = this._currentIndex;
                while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= "0" && this._string.charAt(this._currentIndex) <= "9")
                    this._currentIndex++; // Advance to first non-digit.

                if (this._currentIndex != startIntPartIndex) {
                    var scanIntPartIndex = this._currentIndex - 1;
                    var multiplier = 1;
                    while (scanIntPartIndex >= startIntPartIndex) {
                        integer += multiplier * (this._string.charAt(scanIntPartIndex--) - "0");
                        multiplier *= 10;
                    }
                }

                // Read the decimals.
                if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == ".") {
                    this._currentIndex++;

                    // There must be a least one digit following the .
                    if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < "0" || this._string.charAt(this._currentIndex) > "9")
                        return undefined;
                    while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= "0" && this._string.charAt(this._currentIndex) <= "9") {
                        frac *= 10;
                        decimal += (this._string.charAt(this._currentIndex) - "0") / frac;
                        this._currentIndex += 1;
                    }
                }

                // Read the exponent part.
                if (this._currentIndex != startIndex && this._currentIndex + 1 < this._endIndex && (this._string.charAt(this._currentIndex) == "e" || this._string.charAt(this._currentIndex) ==
                        "E") && (this._string.charAt(this._currentIndex + 1) != "x" && this._string.charAt(this._currentIndex + 1) != "m")) {
                    this._currentIndex++;

                    // Read the sign of the exponent.
                    if (this._string.charAt(this._currentIndex) == "+") {
                        this._currentIndex++;
                    } else if (this._string.charAt(this._currentIndex) == "-") {
                        this._currentIndex++;
                        expsign = -1;
                    }

                    // There must be an exponent.
                    if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < "0" || this._string.charAt(this._currentIndex) > "9")
                        return undefined;

                    while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= "0" && this._string.charAt(this._currentIndex) <= "9") {
                        exponent *= 10;
                        exponent += (this._string.charAt(this._currentIndex) - "0");
                        this._currentIndex++;
                    }
                }

                var number = integer + decimal;
                number *= sign;

                if (exponent)
                    number *= Math.pow(10, expsign * exponent);

                if (startIndex == this._currentIndex)
                    return undefined;

                this._skipOptionalSpacesOrDelimiter();

                return number;
            }

            Source.prototype._parseArcFlag = function () {
                if (this._currentIndex >= this._endIndex)
                    return undefined;
                var flag = false;
                var flagChar = this._string.charAt(this._currentIndex++);
                if (flagChar == "0")
                    flag = false;
                else if (flagChar == "1")
                    flag = true;
                else
                    return undefined;

                this._skipOptionalSpacesOrDelimiter();
                return flag;
            }

            Source.prototype.parseSegment = function () {
                var lookahead = this._string[this._currentIndex];
                var command = this._pathSegTypeFromChar(lookahead);
                if (command == window.SVGPathSeg.PATHSEG_UNKNOWN) {
                    // Possibly an implicit command. Not allowed if this is the first command.
                    if (this._previousCommand == window.SVGPathSeg.PATHSEG_UNKNOWN)
                        return null;
                    command = this._nextCommandHelper(lookahead, this._previousCommand);
                    if (command == window.SVGPathSeg.PATHSEG_UNKNOWN)
                        return null;
                } else {
                    this._currentIndex++;
                }

                this._previousCommand = command;

                switch (command) {
                case window.SVGPathSeg.PATHSEG_MOVETO_REL:
                    return new window.SVGPathSegMovetoRel(owningPathSegList, this._parseNumber(), this._parseNumber());
                case window.SVGPathSeg.PATHSEG_MOVETO_ABS:
                    return new window.SVGPathSegMovetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber());
                case window.SVGPathSeg.PATHSEG_LINETO_REL:
                    return new window.SVGPathSegLinetoRel(owningPathSegList, this._parseNumber(), this._parseNumber());
                case window.SVGPathSeg.PATHSEG_LINETO_ABS:
                    return new window.SVGPathSegLinetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber());
                case window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL:
                    return new window.SVGPathSegLinetoHorizontalRel(owningPathSegList, this._parseNumber());
                case window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS:
                    return new window.SVGPathSegLinetoHorizontalAbs(owningPathSegList, this._parseNumber());
                case window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL:
                    return new window.SVGPathSegLinetoVerticalRel(owningPathSegList, this._parseNumber());
                case window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS:
                    return new window.SVGPathSegLinetoVerticalAbs(owningPathSegList, this._parseNumber());
                case window.SVGPathSeg.PATHSEG_CLOSEPATH:
                    this._skipOptionalSpaces();
                    return new window.SVGPathSegClosePath(owningPathSegList);
                case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL:
                    var points = {
                        x1: this._parseNumber(),
                        y1: this._parseNumber(),
                        x2: this._parseNumber(),
                        y2: this._parseNumber(),
                        x: this._parseNumber(),
                        y: this._parseNumber()
                    };
                    return new window.SVGPathSegCurvetoCubicRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2);
                case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS:
                    var points = {
                        x1: this._parseNumber(),
                        y1: this._parseNumber(),
                        x2: this._parseNumber(),
                        y2: this._parseNumber(),
                        x: this._parseNumber(),
                        y: this._parseNumber()
                    };
                    return new window.SVGPathSegCurvetoCubicAbs(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2);
                case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL:
                    var points = {
                        x2: this._parseNumber(),
                        y2: this._parseNumber(),
                        x: this._parseNumber(),
                        y: this._parseNumber()
                    };
                    return new window.SVGPathSegCurvetoCubicSmoothRel(owningPathSegList, points.x, points.y, points.x2, points.y2);
                case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS:
                    var points = {
                        x2: this._parseNumber(),
                        y2: this._parseNumber(),
                        x: this._parseNumber(),
                        y: this._parseNumber()
                    };
                    return new window.SVGPathSegCurvetoCubicSmoothAbs(owningPathSegList, points.x, points.y, points.x2, points.y2);
                case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL:
                    var points = {
                        x1: this._parseNumber(),
                        y1: this._parseNumber(),
                        x: this._parseNumber(),
                        y: this._parseNumber()
                    };
                    return new window.SVGPathSegCurvetoQuadraticRel(owningPathSegList, points.x, points.y, points.x1, points.y1);
                case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS:
                    var points = {
                        x1: this._parseNumber(),
                        y1: this._parseNumber(),
                        x: this._parseNumber(),
                        y: this._parseNumber()
                    };
                    return new window.SVGPathSegCurvetoQuadraticAbs(owningPathSegList, points.x, points.y, points.x1, points.y1);
                case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL:
                    return new window.SVGPathSegCurvetoQuadraticSmoothRel(owningPathSegList, this._parseNumber(), this._parseNumber());
                case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS:
                    return new window.SVGPathSegCurvetoQuadraticSmoothAbs(owningPathSegList, this._parseNumber(), this._parseNumber());
                case window.SVGPathSeg.PATHSEG_ARC_REL:
                    var points = {
                        x1: this._parseNumber(),
                        y1: this._parseNumber(),
                        arcAngle: this._parseNumber(),
                        arcLarge: this._parseArcFlag(),
                        arcSweep: this._parseArcFlag(),
                        x: this._parseNumber(),
                        y: this._parseNumber()
                    };
                    return new window.SVGPathSegArcRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep);
                case window.SVGPathSeg.PATHSEG_ARC_ABS:
                    var points = {
                        x1: this._parseNumber(),
                        y1: this._parseNumber(),
                        arcAngle: this._parseNumber(),
                        arcLarge: this._parseArcFlag(),
                        arcSweep: this._parseArcFlag(),
                        x: this._parseNumber(),
                        y: this._parseNumber()
                    };
                    return new window.SVGPathSegArcAbs(owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep);
                default:
                    throw "Unknown path seg type."
                }
            }

            var builder = new Builder();
            var source = new Source(string);

            if (!source.initialCommandIsMoveTo())
                return [];
            while (source.hasMoreData()) {
                var pathSeg = source.parseSegment();
                if (!pathSeg)
                    return [];
                builder.appendSegment(pathSeg);
            }

            return builder.pathSegList;
        }
    }
}());

// String.padEnd polyfill for IE11
//
// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
if (!String.prototype.padEnd) {
    String.prototype.padEnd = function padEnd(targetLength, padString) {
        targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
        padString = String((typeof padString !== 'undefined' ? padString : ' '));
        if (this.length > targetLength) {
            return String(this);
        } else {
            targetLength = targetLength - this.length;
            if (targetLength > padString.length) {
                padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
            }
            return String(this) + padString.slice(0, targetLength);
        }
    };
}

/* jshint ignore:end */
src/clip.js000064400000004653151701472650006640 0ustar00import { ChartInternal } from './core';

ChartInternal.prototype.getClipPath = function (id) {
    var isIE9 = window.navigator.appVersion.toLowerCase().indexOf("msie 9.") >= 0;
    return "url(" + (isIE9 ? "" : document.URL.split('#')[0]) + "#" + id + ")";
};
ChartInternal.prototype.appendClip = function (parent, id) {
    return parent.append("clipPath").attr("id", id).append("rect");
};
ChartInternal.prototype.getAxisClipX = function (forHorizontal) {
    // axis line width + padding for left
    var left = Math.max(30, this.margin.left);
    return forHorizontal ? -(1 + left) : -(left - 1);
};
ChartInternal.prototype.getAxisClipY = function (forHorizontal) {
    return forHorizontal ? -20 : -this.margin.top;
};
ChartInternal.prototype.getXAxisClipX = function () {
    var $$ = this;
    return $$.getAxisClipX(!$$.config.axis_rotated);
};
ChartInternal.prototype.getXAxisClipY = function () {
    var $$ = this;
    return $$.getAxisClipY(!$$.config.axis_rotated);
};
ChartInternal.prototype.getYAxisClipX = function () {
    var $$ = this;
    return $$.config.axis_y_inner ? -1 : $$.getAxisClipX($$.config.axis_rotated);
};
ChartInternal.prototype.getYAxisClipY = function () {
    var $$ = this;
    return $$.getAxisClipY($$.config.axis_rotated);
};
ChartInternal.prototype.getAxisClipWidth = function (forHorizontal) {
    var $$ = this,
        left = Math.max(30, $$.margin.left),
        right = Math.max(30, $$.margin.right);
    // width + axis line width + padding for left/right
    return forHorizontal ? $$.width + 2 + left + right : $$.margin.left + 20;
};
ChartInternal.prototype.getAxisClipHeight = function (forHorizontal) {
    // less than 20 is not enough to show the axis label 'outer' without legend
    return (forHorizontal ? this.margin.bottom : (this.margin.top + this.height)) + 20;
};
ChartInternal.prototype.getXAxisClipWidth = function () {
    var $$ = this;
    return $$.getAxisClipWidth(!$$.config.axis_rotated);
};
ChartInternal.prototype.getXAxisClipHeight = function () {
    var $$ = this;
    return $$.getAxisClipHeight(!$$.config.axis_rotated);
};
ChartInternal.prototype.getYAxisClipWidth = function () {
    var $$ = this;
    return $$.getAxisClipWidth($$.config.axis_rotated) + ($$.config.axis_y_inner ? 20 : 0);
};
ChartInternal.prototype.getYAxisClipHeight = function () {
    var $$ = this;
    return $$.getAxisClipHeight($$.config.axis_rotated);
};
src/config.js000064400000021537151701472650007156 0ustar00import { ChartInternal } from './core';
import { isDefined } from './util';

ChartInternal.prototype.getDefaultConfig = function () {
    var config = {
        bindto: '#chart',
        svg_classname: undefined,
        size_width: undefined,
        size_height: undefined,
        padding_left: undefined,
        padding_right: undefined,
        padding_top: undefined,
        padding_bottom: undefined,
        resize_auto: true,
        zoom_enabled: false,
        zoom_initialRange: undefined,
        zoom_type: 'scroll',
        zoom_disableDefaultBehavior: false,
        zoom_privileged: false,
        zoom_rescale: false,
        zoom_onzoom: function () {},
        zoom_onzoomstart: function () {},
        zoom_onzoomend: function () {},
        zoom_x_min: undefined,
        zoom_x_max: undefined,
        interaction_brighten: true,
        interaction_enabled: true,
        onmouseover: function () {},
        onmouseout: function () {},
        onresize: function () {},
        onresized: function () {},
        oninit: function () {},
        onrendered: function () {},
        transition_duration: 350,
        data_x: undefined,
        data_xs: {},
        data_xFormat: '%Y-%m-%d',
        data_xLocaltime: true,
        data_xSort: true,
        data_idConverter: function (id) { return id; },
        data_names: {},
        data_classes: {},
        data_groups: [],
        data_axes: {},
        data_type: undefined,
        data_types: {},
        data_labels: {},
        data_order: 'desc',
        data_regions: {},
        data_color: undefined,
        data_colors: {},
        data_hide: false,
        data_filter: undefined,
        data_selection_enabled: false,
        data_selection_grouped: false,
        data_selection_isselectable: function () { return true; },
        data_selection_multiple: true,
        data_selection_draggable: false,
        data_onclick: function () {},
        data_onmouseover: function () {},
        data_onmouseout: function () {},
        data_onselected: function () {},
        data_onunselected: function () {},
        data_url: undefined,
        data_headers: undefined,
        data_json: undefined,
        data_rows: undefined,
        data_columns: undefined,
        data_mimeType: undefined,
        data_keys: undefined,
        // configuration for no plot-able data supplied.
        data_empty_label_text: "",
        // subchart
        subchart_show: false,
        subchart_size_height: 60,
        subchart_axis_x_show: true,
        subchart_onbrush: function () {},
        // color
        color_pattern: [],
        color_threshold: {},
        // legend
        legend_show: true,
        legend_hide: false,
        legend_position: 'bottom',
        legend_inset_anchor: 'top-left',
        legend_inset_x: 10,
        legend_inset_y: 0,
        legend_inset_step: undefined,
        legend_item_onclick: undefined,
        legend_item_onmouseover: undefined,
        legend_item_onmouseout: undefined,
        legend_equally: false,
        legend_padding: 0,
        legend_item_tile_width: 10,
        legend_item_tile_height: 10,
        // axis
        axis_rotated: false,
        axis_x_show: true,
        axis_x_type: 'indexed',
        axis_x_localtime: true,
        axis_x_categories: [],
        axis_x_tick_centered: false,
        axis_x_tick_format: undefined,
        axis_x_tick_culling: {},
        axis_x_tick_culling_max: 10,
        axis_x_tick_count: undefined,
        axis_x_tick_fit: true,
        axis_x_tick_values: null,
        axis_x_tick_rotate: 0,
        axis_x_tick_outer: true,
        axis_x_tick_multiline: true,
        axis_x_tick_multilineMax: 0,
        axis_x_tick_width: null,
        axis_x_max: undefined,
        axis_x_min: undefined,
        axis_x_padding: {},
        axis_x_height: undefined,
        axis_x_selection: undefined,
        axis_x_label: {},
        axis_x_inner: undefined,
        axis_y_show: true,
        axis_y_type: undefined,
        axis_y_max: undefined,
        axis_y_min: undefined,
        axis_y_inverted: false,
        axis_y_center: undefined,
        axis_y_inner: undefined,
        axis_y_label: {},
        axis_y_tick_format: undefined,
        axis_y_tick_outer: true,
        axis_y_tick_values: null,
        axis_y_tick_rotate: 0,
        axis_y_tick_count: undefined,
        axis_y_tick_time_type: undefined,
        axis_y_tick_time_interval: undefined,
        axis_y_padding: {},
        axis_y_default: undefined,
        axis_y2_show: false,
        axis_y2_max: undefined,
        axis_y2_min: undefined,
        axis_y2_inverted: false,
        axis_y2_center: undefined,
        axis_y2_inner: undefined,
        axis_y2_label: {},
        axis_y2_tick_format: undefined,
        axis_y2_tick_outer: true,
        axis_y2_tick_values: null,
        axis_y2_tick_count: undefined,
        axis_y2_padding: {},
        axis_y2_default: undefined,
        // grid
        grid_x_show: false,
        grid_x_type: 'tick',
        grid_x_lines: [],
        grid_y_show: false,
        // not used
        // grid_y_type: 'tick',
        grid_y_lines: [],
        grid_y_ticks: 10,
        grid_focus_show: true,
        grid_lines_front: true,
        // point - point of each data
        point_show: true,
        point_r: 2.5,
        point_sensitivity: 10,
        point_focus_expand_enabled: true,
        point_focus_expand_r: undefined,
        point_select_r: undefined,
        // line
        line_connectNull: false,
        line_step_type: 'step',
        // bar
        bar_width: undefined,
        bar_width_ratio: 0.6,
        bar_width_max: undefined,
        bar_zerobased: true,
        bar_space: 0,
        // area
        area_zerobased: true,
        area_above: false,
        // pie
        pie_label_show: true,
        pie_label_format: undefined,
        pie_label_threshold: 0.05,
        pie_label_ratio: undefined,
        pie_expand: {},
        pie_expand_duration: 50,
        // gauge
        gauge_fullCircle: false,
        gauge_label_show: true,
        gauge_labelLine_show: true,
        gauge_label_format: undefined,
        gauge_min: 0,
        gauge_max: 100,
        gauge_startingAngle: -1 * Math.PI/2,
        gauge_label_extents: undefined,
        gauge_units: undefined,
        gauge_width: undefined,
        gauge_arcs_minWidth: 5,
        gauge_expand: {},
        gauge_expand_duration: 50,
        // donut
        donut_label_show: true,
        donut_label_format: undefined,
        donut_label_threshold: 0.05,
        donut_label_ratio: undefined,
        donut_width: undefined,
        donut_title: "",
        donut_expand: {},
        donut_expand_duration: 50,
        // spline
        spline_interpolation_type: 'cardinal',
        // region - region to change style
        regions: [],
        // tooltip - show when mouseover on each data
        tooltip_show: true,
        tooltip_grouped: true,
        tooltip_order: undefined,
        tooltip_format_title: undefined,
        tooltip_format_name: undefined,
        tooltip_format_value: undefined,
        tooltip_position: undefined,
        tooltip_contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
            return this.getTooltipContent ? this.getTooltipContent(d, defaultTitleFormat, defaultValueFormat, color) : '';
        },
        tooltip_init_show: false,
        tooltip_init_x: 0,
        tooltip_init_position: {top: '0px', left: '50px'},
        tooltip_onshow: function () {},
        tooltip_onhide: function () {},
        // title
        title_text: undefined,
        title_padding: {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
        },
        title_position: 'top-center',
    };

    Object.keys(this.additionalConfig).forEach(function (key) {
        config[key] = this.additionalConfig[key];
    }, this);

    return config;
};
ChartInternal.prototype.additionalConfig = {};

ChartInternal.prototype.loadConfig = function (config) {
    var this_config = this.config, target, keys, read;
    function find() {
        var key = keys.shift();
//        console.log("key =>", key, ", target =>", target);
        if (key && target && typeof target === 'object' && key in target) {
            target = target[key];
            return find();
        }
        else if (!key) {
            return target;
        }
        else {
            return undefined;
        }
    }
    Object.keys(this_config).forEach(function (key) {
        target = config;
        keys = key.split('_');
        read = find();
//        console.log("CONFIG : ", key, read);
        if (isDefined(read)) {
            this_config[key] = read;
        }
    });
};
src/scss/chart.scss000064400000001044151701472650010313 0ustar00.c3 svg {
  font: 10px sans-serif;
  -webkit-tap-highlight-color: rgba(0,0,0,0);
}
.c3 path, .c3 line {
  fill: none;
  stroke: #000;
}
.c3 text {
  -webkit-user-select: none;
     -moz-user-select: none;
          user-select: none;
}

.c3-legend-item-tile,
.c3-xgrid-focus,
.c3-ygrid,
.c3-event-rect,
.c3-bars path {
  shape-rendering: crispEdges;
}

.c3-chart-arc path {
  stroke: #fff;
}

.c3-chart-arc rect {
    stroke: white;
    stroke-width: 1;
}

.c3-chart-arc text {
  fill: #fff;
  font-size: 13px;
}
src/scss/tooltip.scss000064400000001436151701472650010711 0ustar00.c3-tooltip-container {
  z-index: 10;
}
.c3-tooltip {
  border-collapse:collapse;
  border-spacing:0;
  background-color:#fff;
  empty-cells:show;
  -webkit-box-shadow: 7px 7px 12px -9px rgb(119,119,119);
     -moz-box-shadow: 7px 7px 12px -9px rgb(119,119,119);
          box-shadow: 7px 7px 12px -9px rgb(119,119,119);
  opacity: 0.9;
}
.c3-tooltip tr {
  border:1px solid #CCC;
}
.c3-tooltip th {
  background-color: #aaa;
  font-size:14px;
  padding:2px 5px;
  text-align:left;
  color:#FFF;
}
.c3-tooltip td {
  font-size:13px;
  padding: 3px 6px;
  background-color:#fff;
  border-left:1px dotted #999;
}
.c3-tooltip td > span {
  display: inline-block;
  width: 10px;
  height: 10px;
  margin-right: 6px;
}
.c3-tooltip td.value{
  text-align: right;
}
src/scss/axis.scss000064400000000220151701472650010151 0ustar00.c3-axis-x .tick {
}
.c3-axis-x-label {
}

.c3-axis-y .tick {
}
.c3-axis-y-label {
}

.c3-axis-y2 .tick {
}
.c3-axis-y2-label {
}
src/scss/grid.scss000064400000000223151701472650010135 0ustar00.c3-grid line {
  stroke: #aaa;
}
.c3-grid text {
  fill: #aaa;
}
.c3-xgrid, .c3-ygrid {
  stroke-dasharray: 3 3;
}
.c3-xgrid-focus {
}
src/scss/arc.scss000064400000001075151701472650007763 0ustar00.c3-chart-arcs-title {
  dominant-baseline: middle;
  font-size: 1.3em;
}

.c3-chart-arcs .c3-chart-arcs-background {
  fill: #e0e0e0;
  stroke: #FFF;
}
.c3-chart-arcs .c3-chart-arcs-gauge-unit {
  fill: #000;
  font-size: 16px;
}
.c3-chart-arcs .c3-chart-arcs-gauge-max {
  fill: #777;
}
.c3-chart-arcs .c3-chart-arcs-gauge-min {
  fill: #777;
}

.c3-chart-arc .c3-gauge-value {
  fill: #000;
/*  font-size: 28px !important;*/
}

.c3-chart-arc.c3-target g path {
  opacity: 1;
}

.c3-chart-arc.c3-target.c3-focused g path {
  opacity: 1;
}
src/scss/point.scss000064400000000204151701472650010340 0ustar00.c3-circle._expanded_ {
  stroke-width: 1px;
  stroke: white;
}
.c3-selected-circle {
  fill: white;
  stroke-width: 2px;
}
src/scss/brush.scss000064400000000055151701472650010336 0ustar00.c3-brush .extent {
  fill-opacity: .1;
}
src/scss/focus.scss000064400000000310151701472650010324 0ustar00.c3-target.c3-focused {
  opacity: 1;
}
.c3-target.c3-focused path.c3-line, .c3-target.c3-focused path.c3-step {
  stroke-width: 2px;
}
.c3-target.c3-defocused {
  opacity: 0.3 !important;
}
src/scss/text.scss000064400000000116151701472650010175 0ustar00.c3-text {
}

.c3-text.c3-empty {
  fill: #808080;
  font-size: 2em;
}
src/scss/zoom.scss000064400000000346151701472650010202 0ustar00.c3-drag-zoom.enabled{
  pointer-events: all!important;
  visibility: visible;
}

.c3-drag-zoom.disabled{
    pointer-events: none!important;
    visibility: hidden;
}

.c3-drag-zoom .extent {
    fill-opacity: .1;
}
src/scss/select_drag.scss000064400000000023151701472650011462 0ustar00.c3-dragarea {
}
src/scss/area.scss000064400000000064151701472650010123 0ustar00.c3-area {
  stroke-width: 0;
  opacity: 0.2;
}
src/scss/main.scss000064400000001240151701472650010134 0ustar00/*-- Chart --*/

@import 'chart';

/*-- Axis --*/

@import 'axis';

/*-- Grid --*/

@import 'grid';

/*-- Text on Chart --*/

@import 'text';

/*-- Line --*/

@import 'line';

/*-- Point --*/

@import 'point';

/*-- Bar --*/

@import 'bar';

/*-- Focus --*/

@import 'focus';

/*-- Region --*/

@import 'region';

/*-- Brush --*/

@import 'brush';

/*-- Select - Drag --*/

@import 'select_drag';

/*-- Legend --*/

@import 'legend';

/*-- Title --*/

@import 'title';

/*-- Tooltip --*/

@import 'tooltip';

/*-- Area --*/

@import 'area';

/*-- Arc --*/

@import 'arc';

/*-- Zoom --*/

@import 'zoom';
src/scss/title.scss000064400000000052151701472650010331 0ustar00.c3-title {
  font: 14px sans-serif;
}
src/scss/line.scss000064400000000045151701472650010141 0ustar00.c3-line {
  stroke-width: 1px;
}
src/scss/legend.scss000064400000000302151701472650010444 0ustar00.c3-legend-item {
  font-size: 12px;
}
.c3-legend-item-hidden {
  opacity: 0.15;
}

.c3-legend-background {
  opacity: 0.75;
  fill: white;
  stroke: lightgray;
  stroke-width: 1
}
src/scss/region.scss000064400000000072151701472650010475 0ustar00.c3-region {
  fill: steelblue;
  fill-opacity: .1;
}
src/scss/bar.scss000064400000000146151701472650007760 0ustar00.c3-bar {
  stroke-width: 0;
}
.c3-bar._expanded_ {
  fill-opacity: 1;
  fill-opacity: 0.75;
}
src/api.color.js000064400000000246151701472650007571 0ustar00import { Chart } from './core';

// TODO: fix
Chart.prototype.color = function (id) {
    var $$ = this.internal;
    return $$.color(id); // more patterns
};
src/tooltip.js000064400000020160151701472650007372 0ustar00import CLASS from './class';
import {
    ChartInternal
} from './core';
import {
    isValue,
    isFunction,
    isArray,
    isString,
    sanitise
} from './util';

ChartInternal.prototype.initTooltip = function () {
    var $$ = this,
        config = $$.config,
        i;
    $$.tooltip = $$.selectChart
        .style("position", "relative")
        .append("div")
        .attr('class', CLASS.tooltipContainer)
        .style("position", "absolute")
        .style("pointer-events", "none")
        .style("display", "none");
    // Show tooltip if needed
    if (config.tooltip_init_show) {
        if ($$.isTimeSeries() && isString(config.tooltip_init_x)) {
            config.tooltip_init_x = $$.parseDate(config.tooltip_init_x);
            for (i = 0; i < $$.data.targets[0].values.length; i++) {
                if (($$.data.targets[0].values[i].x - config.tooltip_init_x) === 0) {
                    break;
                }
            }
            config.tooltip_init_x = i;
        }
        $$.tooltip.html(config.tooltip_contents.call($$, $$.data.targets.map(function (d) {
            return $$.addName(d.values[config.tooltip_init_x]);
        }), $$.axis.getXAxisTickFormat(), $$.getYFormat($$.hasArcType()), $$.color));
        $$.tooltip.style("top", config.tooltip_init_position.top)
            .style("left", config.tooltip_init_position.left)
            .style("display", "block");
    }
};
ChartInternal.prototype.getTooltipSortFunction = function () {
    var $$ = this,
        config = $$.config;

    if (config.data_groups.length === 0 || config.tooltip_order !== undefined) {
        // if data are not grouped or if an order is specified
        // for the tooltip values we sort them by their values

        var order = config.tooltip_order;
        if (order === undefined) {
            order = config.data_order;
        }

        var valueOf = function (obj) {
            return obj ? obj.value : null;
        };

        // if data are not grouped, we sort them by their value
        if (isString(order) && order.toLowerCase() === 'asc') {
            return function (a, b) {
                return valueOf(a) - valueOf(b);
            };
        } else if (isString(order) && order.toLowerCase() === 'desc') {
            return function (a, b) {
                return valueOf(b) - valueOf(a);
            };
        } else if (isFunction(order)) {

            // if the function is from data_order we need
            // to wrap the returned function in order to format
            // the sorted value to the expected format

            var sortFunction = order;

            if (config.tooltip_order === undefined) {
                sortFunction = function (a, b) {
                    return order(a ? {
                        id: a.id,
                        values: [a]
                    } : null, b ? {
                        id: b.id,
                        values: [b]
                    } : null);
                };
            }

            return sortFunction;

        } else if (isArray(order)) {
            return function (a, b) {
                return order.indexOf(a.id) - order.indexOf(b.id);
            };
        }
    } else {
        // if data are grouped, we follow the order of grouped targets
        var ids = $$.orderTargets($$.data.targets).map(function (i) {
            return i.id;
        });

        // if it was either asc or desc we need to invert the order
        // returned by orderTargets
        if ($$.isOrderAsc() || $$.isOrderDesc()) {
            ids = ids.reverse();
        }

        return function (a, b) {
            return ids.indexOf(a.id) - ids.indexOf(b.id);
        };
    }
};
ChartInternal.prototype.getTooltipContent = function (d, defaultTitleFormat, defaultValueFormat, color) {
    var $$ = this,
        config = $$.config,
        titleFormat = config.tooltip_format_title || defaultTitleFormat,
        nameFormat = config.tooltip_format_name || function (name) {
            return name;
        },
        valueFormat = config.tooltip_format_value || defaultValueFormat,
        text, i, title, value, name, bgcolor;

    var tooltipSortFunction = this.getTooltipSortFunction();
    if (tooltipSortFunction) {
        d.sort(tooltipSortFunction);
    }

    for (i = 0; i < d.length; i++) {
        if (!(d[i] && (d[i].value || d[i].value === 0))) {
            continue;
        }

        if (!text) {
            title = sanitise(titleFormat ? titleFormat(d[i].x) : d[i].x);
            text = "<table class='" + $$.CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : "");
        }

        value = sanitise(valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index, d));
        if (value !== undefined) {
            // Skip elements when their name is set to null
            if (d[i].name === null) {
                continue;
            }
            name = sanitise(nameFormat(d[i].name, d[i].ratio, d[i].id, d[i].index));
            bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);

            text += "<tr class='" + $$.CLASS.tooltipName + "-" + $$.getTargetSelectorSuffix(d[i].id) + "'>";
            text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>";
            text += "<td class='value'>" + value + "</td>";
            text += "</tr>";
        }
    }
    return text + "</table>";
};
ChartInternal.prototype.tooltipPosition = function (dataToShow, tWidth, tHeight, element) {
    var $$ = this,
        config = $$.config,
        d3 = $$.d3;
    var svgLeft, tooltipLeft, tooltipRight, tooltipTop, chartRight;
    var forArc = $$.hasArcType(),
        mouse = d3.mouse(element);
    // Determin tooltip position
    if (forArc) {
        tooltipLeft = (($$.width - ($$.isLegendRight ? $$.getLegendWidth() : 0)) / 2) + mouse[0];
        tooltipTop = ($$.hasType('gauge') ? $$.height : $$.height / 2) + mouse[1] + 20;
    } else {
        svgLeft = $$.getSvgLeft(true);
        if (config.axis_rotated) {
            tooltipLeft = svgLeft + mouse[0] + 100;
            tooltipRight = tooltipLeft + tWidth;
            chartRight = $$.currentWidth - $$.getCurrentPaddingRight();
            tooltipTop = $$.x(dataToShow[0].x) + 20;
        } else {
            tooltipLeft = svgLeft + $$.getCurrentPaddingLeft(true) + $$.x(dataToShow[0].x) + 20;
            tooltipRight = tooltipLeft + tWidth;
            chartRight = svgLeft + $$.currentWidth - $$.getCurrentPaddingRight();
            tooltipTop = mouse[1] + 15;
        }

        if (tooltipRight > chartRight) {
            // 20 is needed for Firefox to keep tooltip width
            tooltipLeft -= tooltipRight - chartRight + 20;
        }
        if (tooltipTop + tHeight > $$.currentHeight) {
            tooltipTop -= tHeight + 30;
        }
    }
    if (tooltipTop < 0) {
        tooltipTop = 0;
    }
    return {
        top: tooltipTop,
        left: tooltipLeft
    };
};
ChartInternal.prototype.showTooltip = function (selectedData, element) {
    var $$ = this,
        config = $$.config;
    var tWidth, tHeight, position;
    var forArc = $$.hasArcType(),
        dataToShow = selectedData.filter(function (d) {
            return d && isValue(d.value);
        }),
        positionFunction = config.tooltip_position || ChartInternal.prototype.tooltipPosition;
    if (dataToShow.length === 0 || !config.tooltip_show) {
        return;
    }
    $$.tooltip.html(config.tooltip_contents.call($$, selectedData, $$.axis.getXAxisTickFormat(), $$.getYFormat(forArc), $$.color)).style("display", "block");

    // Get tooltip dimensions
    tWidth = $$.tooltip.property('offsetWidth');
    tHeight = $$.tooltip.property('offsetHeight');

    position = positionFunction.call(this, dataToShow, tWidth, tHeight, element);
    // Set tooltip
    $$.tooltip
        .style("top", position.top + "px")
        .style("left", position.left + 'px');
};
ChartInternal.prototype.hideTooltip = function () {
    this.tooltip.style("display", "none");
};
src/index.js000064400000002203151701472650007005 0ustar00import { c3 } from './core';

import './polyfill';
import './api.axis';
import './api.category';
import './api.chart';
import './api.color';
import './api.data';
import './api.flow';
import './api.focus';
import './api.grid';
import './api.group';
import './api.legend';
import './api.load';
import './api.region';
import './api.selection';
import './api.show';
import './api.tooltip';
import './api.transform';
import './api.x';
import './api.zoom';
import './arc';
import './axis';
import './cache';
import './category';
import './class';
import './class-utils';
import './clip';
import './color';
import './config';
import './data.convert';
import './data';
import './data.load';
import './domain';
import './drag';
import './format';
import './grid';
import './interaction';
import './legend';
import './region';
import './scale';
import './selection';
import './shape.bar';
import './shape';
import './shape.line';
import './size';
import './subchart';
import './text';
import './title';
import './tooltip';
import './type';
import './ua';
import './util';
import './zoom';

export default c3;
src/api.grid.js000064400000002156151701472650007402 0ustar00import { Chart } from './core';

Chart.prototype.xgrids = function (grids) {
    var $$ = this.internal, config = $$.config;
    if (! grids) { return config.grid_x_lines; }
    config.grid_x_lines = grids;
    $$.redrawWithoutRescale();
    return config.grid_x_lines;
};
Chart.prototype.xgrids.add = function (grids) {
    var $$ = this.internal;
    return this.xgrids($$.config.grid_x_lines.concat(grids ? grids : []));
};
Chart.prototype.xgrids.remove = function (params) { // TODO: multiple
    var $$ = this.internal;
    $$.removeGridLines(params, true);
};

Chart.prototype.ygrids = function (grids) {
    var $$ = this.internal, config = $$.config;
    if (! grids) { return config.grid_y_lines; }
    config.grid_y_lines = grids;
    $$.redrawWithoutRescale();
    return config.grid_y_lines;
};
Chart.prototype.ygrids.add = function (grids) {
    var $$ = this.internal;
    return this.ygrids($$.config.grid_y_lines.concat(grids ? grids : []));
};
Chart.prototype.ygrids.remove = function (params) { // TODO: multiple
    var $$ = this.internal;
    $$.removeGridLines(params, false);
};
src/domain.js000064400000025675151701472650007167 0ustar00import { ChartInternal } from './core';
import { isValue, isDefined, diffDomain, notEmpty } from './util';

ChartInternal.prototype.getYDomainMin = function (targets) {
    var $$ = this, config = $$.config,
        ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets),
        j, k, baseId, idsInGroup, id, hasNegativeValue;
    if (config.data_groups.length > 0) {
        hasNegativeValue = $$.hasNegativeValueInTargets(targets);
        for (j = 0; j < config.data_groups.length; j++) {
            // Determine baseId
            idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; });
            if (idsInGroup.length === 0) { continue; }
            baseId = idsInGroup[0];
            // Consider negative values
            if (hasNegativeValue && ys[baseId]) {
                ys[baseId].forEach(function (v, i) {
                    ys[baseId][i] = v < 0 ? v : 0;
                });
            }
            // Compute min
            for (k = 1; k < idsInGroup.length; k++) {
                id = idsInGroup[k];
                if (! ys[id]) { continue; }
                ys[id].forEach(function (v, i) {
                    if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasNegativeValue && +v > 0)) {
                        ys[baseId][i] += +v;
                    }
                });
            }
        }
    }
    return $$.d3.min(Object.keys(ys).map(function (key) { return $$.d3.min(ys[key]); }));
};
ChartInternal.prototype.getYDomainMax = function (targets) {
    var $$ = this, config = $$.config,
        ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets),
        j, k, baseId, idsInGroup, id, hasPositiveValue;
    if (config.data_groups.length > 0) {
        hasPositiveValue = $$.hasPositiveValueInTargets(targets);
        for (j = 0; j < config.data_groups.length; j++) {
            // Determine baseId
            idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; });
            if (idsInGroup.length === 0) { continue; }
            baseId = idsInGroup[0];
            // Consider positive values
            if (hasPositiveValue && ys[baseId]) {
                ys[baseId].forEach(function (v, i) {
                    ys[baseId][i] = v > 0 ? v : 0;
                });
            }
            // Compute max
            for (k = 1; k < idsInGroup.length; k++) {
                id = idsInGroup[k];
                if (! ys[id]) { continue; }
                ys[id].forEach(function (v, i) {
                    if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasPositiveValue && +v < 0)) {
                        ys[baseId][i] += +v;
                    }
                });
            }
        }
    }
    return $$.d3.max(Object.keys(ys).map(function (key) { return $$.d3.max(ys[key]); }));
};
ChartInternal.prototype.getYDomain = function (targets, axisId, xDomain) {
    var $$ = this, config = $$.config,
        targetsByAxisId = targets.filter(function (t) { return $$.axis.getId(t.id) === axisId; }),
        yTargets = xDomain ? $$.filterByXDomain(targetsByAxisId, xDomain) : targetsByAxisId,
        yMin = axisId === 'y2' ? config.axis_y2_min : config.axis_y_min,
        yMax = axisId === 'y2' ? config.axis_y2_max : config.axis_y_max,
        yDomainMin = $$.getYDomainMin(yTargets),
        yDomainMax = $$.getYDomainMax(yTargets),
        domain, domainLength, padding, padding_top, padding_bottom,
        center = axisId === 'y2' ? config.axis_y2_center : config.axis_y_center,
        yDomainAbs, lengths, diff, ratio, isAllPositive, isAllNegative,
        isZeroBased = ($$.hasType('bar', yTargets) && config.bar_zerobased) || ($$.hasType('area', yTargets) && config.area_zerobased),
        isInverted = axisId === 'y2' ? config.axis_y2_inverted : config.axis_y_inverted,
        showHorizontalDataLabel = $$.hasDataLabel() && config.axis_rotated,
        showVerticalDataLabel = $$.hasDataLabel() && !config.axis_rotated;

    // MEMO: avoid inverting domain unexpectedly
    yDomainMin = isValue(yMin) ? yMin : isValue(yMax) ? (yDomainMin < yMax ? yDomainMin : yMax - 10) : yDomainMin;
    yDomainMax = isValue(yMax) ? yMax : isValue(yMin) ? (yMin < yDomainMax ? yDomainMax : yMin + 10) : yDomainMax;

    if (yTargets.length === 0) { // use current domain if target of axisId is none
        return axisId === 'y2' ? $$.y2.domain() : $$.y.domain();
    }
    if (isNaN(yDomainMin)) { // set minimum to zero when not number
        yDomainMin = 0;
    }
    if (isNaN(yDomainMax)) { // set maximum to have same value as yDomainMin
        yDomainMax = yDomainMin;
    }
    if (yDomainMin === yDomainMax) {
        yDomainMin < 0 ? yDomainMax = 0 : yDomainMin = 0;
    }
    isAllPositive = yDomainMin >= 0 && yDomainMax >= 0;
    isAllNegative = yDomainMin <= 0 && yDomainMax <= 0;

    // Cancel zerobased if axis_*_min / axis_*_max specified
    if ((isValue(yMin) && isAllPositive) || (isValue(yMax) && isAllNegative)) {
        isZeroBased = false;
    }

    // Bar/Area chart should be 0-based if all positive|negative
    if (isZeroBased) {
        if (isAllPositive) { yDomainMin = 0; }
        if (isAllNegative) { yDomainMax = 0; }
    }

    domainLength = Math.abs(yDomainMax - yDomainMin);
    padding = padding_top = padding_bottom = domainLength * 0.1;

    if (typeof center !== 'undefined') {
        yDomainAbs = Math.max(Math.abs(yDomainMin), Math.abs(yDomainMax));
        yDomainMax = center + yDomainAbs;
        yDomainMin = center - yDomainAbs;
    }
    // add padding for data label
    if (showHorizontalDataLabel) {
        lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'width');
        diff = diffDomain($$.y.range());
        ratio = [lengths[0] / diff, lengths[1] / diff];
        padding_top += domainLength * (ratio[1] / (1 - ratio[0] - ratio[1]));
        padding_bottom += domainLength * (ratio[0] / (1 - ratio[0] - ratio[1]));
    } else if (showVerticalDataLabel) {
        lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'height');
        padding_top += $$.axis.convertPixelsToAxisPadding(lengths[1], domainLength);
        padding_bottom += $$.axis.convertPixelsToAxisPadding(lengths[0], domainLength);
    }
    if (axisId === 'y' && notEmpty(config.axis_y_padding)) {
        padding_top = $$.axis.getPadding(config.axis_y_padding, 'top', padding_top, domainLength);
        padding_bottom = $$.axis.getPadding(config.axis_y_padding, 'bottom', padding_bottom, domainLength);
    }
    if (axisId === 'y2' && notEmpty(config.axis_y2_padding)) {
        padding_top = $$.axis.getPadding(config.axis_y2_padding, 'top', padding_top, domainLength);
        padding_bottom = $$.axis.getPadding(config.axis_y2_padding, 'bottom', padding_bottom, domainLength);
    }
    // Bar/Area chart should be 0-based if all positive|negative
    if (isZeroBased) {
        if (isAllPositive) { padding_bottom = yDomainMin; }
        if (isAllNegative) { padding_top = -yDomainMax; }
    }
    domain = [yDomainMin - padding_bottom, yDomainMax + padding_top];
    return isInverted ? domain.reverse() : domain;
};
ChartInternal.prototype.getXDomainMin = function (targets) {
    var $$ = this, config = $$.config;
    return isDefined(config.axis_x_min) ?
        ($$.isTimeSeries() ? this.parseDate(config.axis_x_min) : config.axis_x_min) :
    $$.d3.min(targets, function (t) { return $$.d3.min(t.values, function (v) { return v.x; }); });
};
ChartInternal.prototype.getXDomainMax = function (targets) {
    var $$ = this, config = $$.config;
    return isDefined(config.axis_x_max) ?
        ($$.isTimeSeries() ? this.parseDate(config.axis_x_max) : config.axis_x_max) :
    $$.d3.max(targets, function (t) { return $$.d3.max(t.values, function (v) { return v.x; }); });
};
ChartInternal.prototype.getXDomainPadding = function (domain) {
    var $$ = this, config = $$.config,
        diff = domain[1] - domain[0],
        maxDataCount, padding, paddingLeft, paddingRight;
    if ($$.isCategorized()) {
        padding = 0;
    } else if ($$.hasType('bar')) {
        maxDataCount = $$.getMaxDataCount();
        padding = maxDataCount > 1 ? (diff / (maxDataCount - 1)) / 2 : 0.5;
    } else {
        padding = diff * 0.01;
    }
    if (typeof config.axis_x_padding === 'object' && notEmpty(config.axis_x_padding)) {
        paddingLeft = isValue(config.axis_x_padding.left) ? config.axis_x_padding.left : padding;
        paddingRight = isValue(config.axis_x_padding.right) ? config.axis_x_padding.right : padding;
    } else if (typeof config.axis_x_padding === 'number') {
        paddingLeft = paddingRight = config.axis_x_padding;
    } else {
        paddingLeft = paddingRight = padding;
    }
    return {left: paddingLeft, right: paddingRight};
};
ChartInternal.prototype.getXDomain = function (targets) {
    var $$ = this,
        xDomain = [$$.getXDomainMin(targets), $$.getXDomainMax(targets)],
        firstX = xDomain[0], lastX = xDomain[1],
        padding = $$.getXDomainPadding(xDomain),
        min = 0, max = 0;
    // show center of x domain if min and max are the same
    if ((firstX - lastX) === 0 && !$$.isCategorized()) {
        if ($$.isTimeSeries()) {
            firstX = new Date(firstX.getTime() * 0.5);
            lastX = new Date(lastX.getTime() * 1.5);
        } else {
            firstX = firstX === 0 ? 1 : (firstX * 0.5);
            lastX = lastX === 0 ? -1 : (lastX * 1.5);
        }
    }
    if (firstX || firstX === 0) {
        min = $$.isTimeSeries() ? new Date(firstX.getTime() - padding.left) : firstX - padding.left;
    }
    if (lastX || lastX === 0) {
        max = $$.isTimeSeries() ? new Date(lastX.getTime() + padding.right) : lastX + padding.right;
    }
    return [min, max];
};
ChartInternal.prototype.updateXDomain = function (targets, withUpdateXDomain, withUpdateOrgXDomain, withTrim, domain) {
    var $$ = this, config = $$.config;

    if (withUpdateOrgXDomain) {
        $$.x.domain(domain ? domain : $$.d3.extent($$.getXDomain(targets)));
        $$.orgXDomain = $$.x.domain();
        if (config.zoom_enabled) { $$.zoom.update(); }
        $$.subX.domain($$.x.domain());
        if ($$.brush) { $$.brush.updateScale($$.subX); }
    }
    if (withUpdateXDomain) {
        $$.x.domain(domain ? domain : (!$$.brush || $$.brush.empty()) ? $$.orgXDomain : $$.brush.selectionAsValue());
    }

    // Trim domain when too big by zoom mousemove event
    if (withTrim) { $$.x.domain($$.trimXDomain($$.x.orgDomain())); }

    return $$.x.domain();
};
ChartInternal.prototype.trimXDomain = function (domain) {
    var zoomDomain = this.getZoomDomain(),
        min = zoomDomain[0], max = zoomDomain[1];
    if (domain[0] <= min) {
        domain[1] = +domain[1] + (min - domain[0]);
        domain[0] = min;
    }
    if (max <= domain[1]) {
        domain[0] = +domain[0] - (domain[1] - max);
        domain[1] = max;
    }
    return domain;
};
src/format.js000064400000003513151701472650007173 0ustar00import { ChartInternal } from './core';
import { isValue } from './util';

ChartInternal.prototype.getYFormat = function (forArc) {
    var $$ = this,
        formatForY = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.yFormat,
        formatForY2 = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.y2Format;
    return function (v, ratio, id) {
        var format = $$.axis.getId(id) === 'y2' ? formatForY2 : formatForY;
        return format.call($$, v, ratio);
    };
};
ChartInternal.prototype.yFormat = function (v) {
    var $$ = this, config = $$.config,
        format = config.axis_y_tick_format ? config.axis_y_tick_format : $$.defaultValueFormat;
    return format(v);
};
ChartInternal.prototype.y2Format = function (v) {
    var $$ = this, config = $$.config,
        format = config.axis_y2_tick_format ? config.axis_y2_tick_format : $$.defaultValueFormat;
    return format(v);
};
ChartInternal.prototype.defaultValueFormat = function (v) {
    return isValue(v) ? +v : "";
};
ChartInternal.prototype.defaultArcValueFormat = function (v, ratio) {
    return (ratio * 100).toFixed(1) + '%';
};
ChartInternal.prototype.dataLabelFormat = function (targetId) {
    var $$ = this, data_labels = $$.config.data_labels,
        format, defaultFormat = function (v) { return isValue(v) ? +v : ""; };
    // find format according to axis id
    if (typeof data_labels.format === 'function') {
        format = data_labels.format;
    } else if (typeof data_labels.format === 'object') {
        if (data_labels.format[targetId]) {
            format = data_labels.format[targetId] === true ? defaultFormat : data_labels.format[targetId];
        } else {
            format = function () { return ''; };
        }
    } else {
        format = defaultFormat;
    }
    return format;
};
src/api.tooltip.js000064400000002172151701472650010145 0ustar00import { Chart } from './core';

Chart.prototype.tooltip = function () {};
Chart.prototype.tooltip.show = function (args) {
    var $$ = this.internal, targets, data, mouse = {};

    // determine mouse position on the chart
    if (args.mouse) {
        mouse = args.mouse;
    }
    else {
        // determine focus data
        if (args.data) {
            data = args.data;
        }
        else if (typeof args.x !== 'undefined') {
            if (args.id) {
                targets = $$.data.targets.filter(function(t){ return t.id === args.id; });
            } else {
                targets = $$.data.targets;
            }
            data = $$.filterByX(targets, args.x).slice(0,1)[0];
        }
        mouse = data ? $$.getMousePosition(data) : null;
    }

    // emulate mouse events to show
    $$.dispatchEvent('mousemove', mouse);

    $$.config.tooltip_onshow.call($$, data);
};
Chart.prototype.tooltip.hide = function () {
    // TODO: get target data by checking the state of focus
    this.internal.dispatchEvent('mouseout', 0);

    this.internal.config.tooltip_onhide.call(this);
};
src/shape.bar.js000064400000012751151701472650007552 0ustar00import CLASS from './class';
import { ChartInternal } from './core';
import { isValue } from './util';

ChartInternal.prototype.initBar = function () {
    var $$ = this;
    $$.main.select('.' + CLASS.chart).append("g")
        .attr("class", CLASS.chartBars);
};
ChartInternal.prototype.updateTargetsForBar = function (targets) {
    var $$ = this, config = $$.config,
        mainBars, mainBarEnter,
        classChartBar = $$.classChartBar.bind($$),
        classBars = $$.classBars.bind($$),
        classFocus = $$.classFocus.bind($$);
    mainBars = $$.main.select('.' + CLASS.chartBars).selectAll('.' + CLASS.chartBar)
        .data(targets)
        .attr('class', function (d) { return classChartBar(d) + classFocus(d); });
    mainBarEnter = mainBars.enter().append('g')
        .attr('class', classChartBar)
        .style("pointer-events", "none");
    // Bars for each data
    mainBarEnter.append('g')
        .attr("class", classBars)
        .style("cursor", function (d) { return config.data_selection_isselectable(d) ? "pointer" : null; });

};
ChartInternal.prototype.updateBar = function (durationForExit) {
    var $$ = this,
        barData = $$.barData.bind($$),
        classBar = $$.classBar.bind($$),
        initialOpacity = $$.initialOpacity.bind($$),
        color = function (d) { return $$.color(d.id); };
    var mainBar = $$.main.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar)
        .data(barData);
    var mainBarEnter = mainBar.enter().append('path')
        .attr("class", classBar)
        .style("stroke", color)
        .style("fill", color);
    $$.mainBar = mainBarEnter.merge(mainBar)
        .style("opacity", initialOpacity);
    mainBar.exit().transition().duration(durationForExit)
        .style("opacity", 0);
};
ChartInternal.prototype.redrawBar = function (drawBar, withTransition, transition) {
    return [
        (withTransition ? this.mainBar.transition(transition) : this.mainBar)
            .attr('d', drawBar)
            .style("stroke", this.color)
            .style("fill", this.color)
            .style("opacity", 1)
    ];
};
ChartInternal.prototype.getBarW = function (axis, barTargetsNum) {
    var $$ = this, config = $$.config,
        w = typeof config.bar_width === 'number' ? config.bar_width : barTargetsNum ? (axis.tickInterval() * config.bar_width_ratio) / barTargetsNum : 0;
    return config.bar_width_max && w > config.bar_width_max ? config.bar_width_max : w;
};
ChartInternal.prototype.getBars = function (i, id) {
    var $$ = this;
    return (id ? $$.main.selectAll('.' + CLASS.bars + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.bar + (isValue(i) ? '-' + i : ''));
};
ChartInternal.prototype.expandBars = function (i, id, reset) {
    var $$ = this;
    if (reset) { $$.unexpandBars(); }
    $$.getBars(i, id).classed(CLASS.EXPANDED, true);
};
ChartInternal.prototype.unexpandBars = function (i) {
    var $$ = this;
    $$.getBars(i).classed(CLASS.EXPANDED, false);
};
ChartInternal.prototype.generateDrawBar = function (barIndices, isSub) {
    var $$ = this, config = $$.config,
        getPoints = $$.generateGetBarPoints(barIndices, isSub);
    return function (d, i) {
        // 4 points that make a bar
        var points = getPoints(d, i);

        // switch points if axis is rotated, not applicable for sub chart
        var indexX = config.axis_rotated ? 1 : 0;
        var indexY = config.axis_rotated ? 0 : 1;

        var path = 'M ' + points[0][indexX] + ',' + points[0][indexY] + ' ' +
                'L' + points[1][indexX] + ',' + points[1][indexY] + ' ' +
                'L' + points[2][indexX] + ',' + points[2][indexY] + ' ' +
                'L' + points[3][indexX] + ',' + points[3][indexY] + ' ' +
                'z';

        return path;
    };
};
ChartInternal.prototype.generateGetBarPoints = function (barIndices, isSub) {
    var $$ = this,
        axis = isSub ? $$.subXAxis : $$.xAxis,
        barTargetsNum = barIndices.__max__ + 1,
        barW = $$.getBarW(axis, barTargetsNum),
        barX = $$.getShapeX(barW, barTargetsNum, barIndices, !!isSub),
        barY = $$.getShapeY(!!isSub),
        barOffset = $$.getShapeOffset($$.isBarType, barIndices, !!isSub),
        barSpaceOffset = barW * ($$.config.bar_space / 2),
        yScale = isSub ? $$.getSubYScale : $$.getYScale;
    return function (d, i) {
        var y0 = yScale.call($$, d.id)(0),
            offset = barOffset(d, i) || y0, // offset is for stacked bar chart
            posX = barX(d), posY = barY(d);
        // fix posY not to overflow opposite quadrant
        if ($$.config.axis_rotated) {
            if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; }
        }
        // 4 points that make a bar
        return [
            [posX + barSpaceOffset, offset],
            [posX + barSpaceOffset, posY - (y0 - offset)],
            [posX + barW - barSpaceOffset, posY - (y0 - offset)],
            [posX + barW - barSpaceOffset, offset]
        ];
    };
};
ChartInternal.prototype.isWithinBar = function (mouse, that) {
    var box = that.getBoundingClientRect(),
        seg0 = that.pathSegList.getItem(0), seg1 = that.pathSegList.getItem(1),
        x = Math.min(seg0.x, seg1.x), y = Math.min(seg0.y, seg1.y),
        w = box.width, h = box.height, offset = 2,
        sx = x - offset, ex = x + w + offset, sy = y + h + offset, ey = y - offset;
    return sx < mouse[0] && mouse[0] < ex && ey < mouse[1] && mouse[1] < sy;
};
src/api.region.js000064400000002705151701472650007740 0ustar00import CLASS from './class';
import { Chart } from './core';

Chart.prototype.regions = function (regions) {
    var $$ = this.internal, config = $$.config;
    if (!regions) { return config.regions; }
    config.regions = regions;
    $$.redrawWithoutRescale();
    return config.regions;
};
Chart.prototype.regions.add = function (regions) {
    var $$ = this.internal, config = $$.config;
    if (!regions) { return config.regions; }
    config.regions = config.regions.concat(regions);
    $$.redrawWithoutRescale();
    return config.regions;
};
Chart.prototype.regions.remove = function (options) {
    var $$ = this.internal, config = $$.config,
        duration, classes, regions;

    options = options || {};
    duration = $$.getOption(options, "duration", config.transition_duration);
    classes = $$.getOption(options, "classes", [CLASS.region]);

    regions = $$.main.select('.' + CLASS.regions).selectAll(classes.map(function (c) { return '.' + c; }));
    (duration ? regions.transition().duration(duration) : regions)
        .style('opacity', 0)
        .remove();

    config.regions = config.regions.filter(function (region) {
        var found = false;
        if (!region['class']) {
            return true;
        }
        region['class'].split(' ').forEach(function (c) {
            if (classes.indexOf(c) >= 0) { found = true; }
        });
        return !found;
    });

    return config.regions;
};
src/region.js000064400000007033151701472650007167 0ustar00import CLASS from './class';
import { ChartInternal } from './core';
import { isValue } from './util';

ChartInternal.prototype.initRegion = function () {
    var $$ = this;
    $$.region = $$.main.append('g')
        .attr("clip-path", $$.clipPath)
        .attr("class", CLASS.regions);
};
ChartInternal.prototype.updateRegion = function (duration) {
    var $$ = this, config = $$.config;

    // hide if arc type
    $$.region.style('visibility', $$.hasArcType() ? 'hidden' : 'visible');

    var mainRegion = $$.main.select('.' + CLASS.regions).selectAll('.' + CLASS.region)
        .data(config.regions);
    var mainRegionEnter = mainRegion.enter().append('rect')
        .attr("x", $$.regionX.bind($$))
        .attr("y", $$.regionY.bind($$))
        .attr("width", $$.regionWidth.bind($$))
        .attr("height", $$.regionHeight.bind($$))
        .style("fill-opacity", 0);
    $$.mainRegion = mainRegionEnter.merge(mainRegion)
        .attr('class', $$.classRegion.bind($$));
    mainRegion.exit().transition().duration(duration)
        .style("opacity", 0)
        .remove();
};
ChartInternal.prototype.redrawRegion = function (withTransition, transition) {
    var $$ = this, regions = $$.mainRegion;
    return [(withTransition ? regions.transition(transition) : regions)
            .attr("x", $$.regionX.bind($$))
            .attr("y", $$.regionY.bind($$))
            .attr("width", $$.regionWidth.bind($$))
            .attr("height", $$.regionHeight.bind($$))
            .style("fill-opacity", function (d) { return isValue(d.opacity) ? d.opacity : 0.1; })
    ];
};
ChartInternal.prototype.regionX = function (d) {
    var $$ = this, config = $$.config,
        xPos, yScale = d.axis === 'y' ? $$.y : $$.y2;
    if (d.axis === 'y' || d.axis === 'y2') {
        xPos = config.axis_rotated ? ('start' in d ? yScale(d.start) : 0) : 0;
    } else {
        xPos = config.axis_rotated ? 0 : ('start' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.start) : d.start) : 0);
    }
    return xPos;
};
ChartInternal.prototype.regionY = function (d) {
    var $$ = this, config = $$.config,
        yPos, yScale = d.axis === 'y' ? $$.y : $$.y2;
    if (d.axis === 'y' || d.axis === 'y2') {
        yPos = config.axis_rotated ? 0 : ('end' in d ? yScale(d.end) : 0);
    } else {
        yPos = config.axis_rotated ? ('start' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.start) : d.start) : 0) : 0;
    }
    return yPos;
};
ChartInternal.prototype.regionWidth = function (d) {
    var $$ = this, config = $$.config,
        start = $$.regionX(d), end, yScale = d.axis === 'y' ? $$.y : $$.y2;
    if (d.axis === 'y' || d.axis === 'y2') {
        end = config.axis_rotated ? ('end' in d ? yScale(d.end) : $$.width) : $$.width;
    } else {
        end = config.axis_rotated ? $$.width : ('end' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.end) : d.end) : $$.width);
    }
    return end < start ? 0 : end - start;
};
ChartInternal.prototype.regionHeight = function (d) {
    var $$ = this, config = $$.config,
        start = this.regionY(d), end, yScale = d.axis === 'y' ? $$.y : $$.y2;
    if (d.axis === 'y' || d.axis === 'y2') {
        end = config.axis_rotated ? $$.height : ('start' in d ? yScale(d.start) : $$.height);
    } else {
        end = config.axis_rotated ? ('end' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.end) : d.end) : $$.height) : $$.height;
    }
    return end < start ? 0 : end - start;
};
ChartInternal.prototype.isRegionOnX = function (d) {
    return !d.axis || d.axis === 'x';
};
src/chart-internal.js000064400000000423151701472650010613 0ustar00export function ChartInternal(api) {
    var $$ = this;
    $$.d3 = window.d3 ? window.d3 : typeof require !== 'undefined' ? require("d3") : undefined;
    $$.api = api;
    $$.config = $$.getDefaultConfig();
    $$.data = {};
    $$.cache = {};
    $$.axes = {};
}
src/util.js000064400000003262151701472650006661 0ustar00export var asHalfPixel = function(n) {
    return Math.ceil(n) + 0.5;
};
export var ceil10 = function(v) {
    return Math.ceil(v / 10) * 10;
};
export var diffDomain = function(d) {
    return d[1] - d[0];
};
export var getOption = function(options, key, defaultValue) {
    return isDefined(options[key]) ? options[key] : defaultValue;
};
export var getPathBox = function(path) {
    var box = path.getBoundingClientRect(),
        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 };
};
export var hasValue = function(dict, value) {
    var found = false;
    Object.keys(dict).forEach(function(key) {
        if (dict[key] === value) { found = true; }
    });
    return found;
};
export var isArray = function(o) {
    return Array.isArray(o);
};
export var isDefined = function(v) {
    return typeof v !== 'undefined';
};
export var isEmpty = function(o) {
    return typeof o === 'undefined' || o === null || (isString(o) && o.length === 0) || (typeof o === 'object' && Object.keys(o).length === 0);
};
export var isFunction = function(o) {
    return typeof o === 'function';
};
export var isString = function(o) {
    return typeof o === 'string';
};
export var isUndefined = function(v) {
    return typeof v === 'undefined';
};
export var isValue = function(v) {
    return v || v === 0;
};
export var notEmpty = function(o) {
    return !isEmpty(o);
};
export var sanitise = function(str) {
    return typeof str === 'string' ? str.replace(/</g, '&lt;').replace(/>/g, '&gt;') : str;
};
src/data.convert.js000064400000021431151701472650010272 0ustar00import { ChartInternal } from './core';
import { isValue, isUndefined, isDefined, notEmpty, isArray } from './util';

ChartInternal.prototype.convertUrlToData = function (url, mimeType, headers, keys, done) {
    var $$ = this, type = mimeType ? mimeType : 'csv', f, converter;

    if (type === 'json') {
        f = $$.d3.json;
        converter = $$.convertJsonToData;
    } else if (type === 'tsv') {
        f = $$.d3.tsv;
        converter = $$.convertXsvToData;
    } else {
        f = $$.d3.csv;
        converter = $$.convertXsvToData;
    }

    f(url, headers).then(function (data) {
        done.call($$, converter.call($$, data, keys));
    }).catch(function (error) {
        throw error;
    });
};
ChartInternal.prototype.convertXsvToData = function (xsv) {
    var keys = xsv.columns, rows = xsv;
    if (rows.length === 0) {
        return { keys, rows: [ keys.reduce((row, key) => Object.assign(row, { [key]: null }), {}) ] };
    } else {
        // [].concat() is to convert result into a plain array otherwise
        // test is not happy because rows have properties.
        return { keys, rows: [].concat(xsv) };
    }
};
ChartInternal.prototype.convertJsonToData = function (json, keys) {
    var $$ = this,
        new_rows = [], targetKeys, data;
    if (keys) { // when keys specified, json would be an array that includes objects
        if (keys.x) {
            targetKeys = keys.value.concat(keys.x);
            $$.config.data_x = keys.x;
        } else {
            targetKeys = keys.value;
        }
        new_rows.push(targetKeys);
        json.forEach(function (o) {
            var new_row = [];
            targetKeys.forEach(function (key) {
                // convert undefined to null because undefined data will be removed in convertDataToTargets()
                var v = $$.findValueInJson(o, key);
                if (isUndefined(v)) {
                    v = null;
                }
                new_row.push(v);
            });
            new_rows.push(new_row);
        });
        data = $$.convertRowsToData(new_rows);
    } else {
        Object.keys(json).forEach(function (key) {
            new_rows.push([key].concat(json[key]));
        });
        data = $$.convertColumnsToData(new_rows);
    }
    return data;
};
ChartInternal.prototype.findValueInJson = function (object, path) {
    path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties (replace [] with .)
    path = path.replace(/^\./, '');           // strip a leading dot
    var pathArray = path.split('.');
    for (var i = 0; i < pathArray.length; ++i) {
        var k = pathArray[i];
        if (k in object) {
            object = object[k];
        } else {
            return;
        }
    }
    return object;
};

/**
 * Converts the rows to normalized data.
 * @param {any[][]} rows The row data
 * @return {Object}
 */
ChartInternal.prototype.convertRowsToData = (rows) => {
    const newRows = [];
    const keys = rows[0];

    for (let i = 1; i < rows.length; i++) {
        const newRow = {};
        for (let j = 0; j < rows[i].length; j++) {
            if (isUndefined(rows[i][j])) {
                throw new Error("Source data is missing a component at (" + i + "," + j + ")!");
            }
            newRow[keys[j]] = rows[i][j];
        }
        newRows.push(newRow);
    }
    return { keys, rows: newRows };
};

/**
 * Converts the columns to normalized data.
 * @param {any[][]} columns The column data
 * @return {Object}
 */
ChartInternal.prototype.convertColumnsToData = (columns) => {
    const newRows = [];
    const keys = [];

    for (let i = 0; i < columns.length; i++) {
        const key = columns[i][0];
        for (let j = 1; j < columns[i].length; j++) {
            if (isUndefined(newRows[j - 1])) {
                newRows[j - 1] = {};
            }
            if (isUndefined(columns[i][j])) {
                throw new Error("Source data is missing a component at (" + i + "," + j + ")!");
            }
            newRows[j - 1][key] = columns[i][j];
        }
        keys.push(key);
    }

    return { keys, rows: newRows };
};

/**
 * Converts the data format into the target format.
 * @param {!Object} data
 * @param {!Array} data.keys Ordered list of target IDs.
 * @param {!Array} data.rows Rows of data to convert.
 * @param {boolean} appendXs True to append to $$.data.xs, False to replace.
 * @return {!Array}
 */
ChartInternal.prototype.convertDataToTargets = function (data, appendXs) {
    var $$ = this, config = $$.config, targets, ids, xs, keys;

    // handles format where keys are not orderly provided
    if (isArray(data)) {
        keys = Object.keys(data[ 0 ]);
    } else {
        keys = data.keys;
        data = data.rows;
    }

    ids = keys.filter($$.isNotX, $$);
    xs = keys.filter($$.isX, $$);

    // save x for update data by load when custom x and c3.x API
    ids.forEach(function (id) {
        var xKey = $$.getXKey(id);

        if ($$.isCustomX() || $$.isTimeSeries()) {
            // if included in input data
            if (xs.indexOf(xKey) >= 0) {
                $$.data.xs[id] = (appendXs && $$.data.xs[id] ? $$.data.xs[id] : []).concat(
                    data.map(function (d) { return d[xKey]; })
                        .filter(isValue)
                        .map(function (rawX, i) { return $$.generateTargetX(rawX, id, i); })
                );
            }
            // if not included in input data, find from preloaded data of other id's x
            else if (config.data_x) {
                $$.data.xs[id] = $$.getOtherTargetXs();
            }
            // if not included in input data, find from preloaded data
            else if (notEmpty(config.data_xs)) {
                $$.data.xs[id] = $$.getXValuesOfXKey(xKey, $$.data.targets);
            }
            // MEMO: if no x included, use same x of current will be used
        } else {
            $$.data.xs[id] = data.map(function (d, i) { return i; });
        }
    });


    // check x is defined
    ids.forEach(function (id) {
        if (!$$.data.xs[id]) {
            throw new Error('x is not defined for id = "' + id + '".');
        }
    });

    // convert to target
    targets = ids.map(function (id, index) {
        var convertedId = config.data_idConverter(id);
        return {
            id: convertedId,
            id_org: id,
            values: data.map(function (d, i) {
                var xKey = $$.getXKey(id), rawX = d[xKey],
                    value = d[id] !== null && !isNaN(d[id]) ? +d[id] : null, x;
                // use x as categories if custom x and categorized
                if ($$.isCustomX() && $$.isCategorized() && !isUndefined(rawX)) {
                    if (index === 0 && i === 0) {
                        config.axis_x_categories = [];
                    }
                    x = config.axis_x_categories.indexOf(rawX);
                    if (x === -1) {
                        x = config.axis_x_categories.length;
                        config.axis_x_categories.push(rawX);
                    }
                } else {
                    x  = $$.generateTargetX(rawX, id, i);
                }
                // mark as x = undefined if value is undefined and filter to remove after mapped
                if (isUndefined(d[id]) || $$.data.xs[id].length <= i) {
                    x = undefined;
                }
                return {x: x, value: value, id: convertedId};
            }).filter(function (v) { return isDefined(v.x); })
        };
    });

    // finish targets
    targets.forEach(function (t) {
        var i;
        // sort values by its x
        if (config.data_xSort) {
            t.values = t.values.sort(function (v1, v2) {
                var x1 = v1.x || v1.x === 0 ? v1.x : Infinity,
                    x2 = v2.x || v2.x === 0 ? v2.x : Infinity;
                return x1 - x2;
            });
        }
        // indexing each value
        i = 0;
        t.values.forEach(function (v) {
            v.index = i++;
        });
        // this needs to be sorted because its index and value.index is identical
        $$.data.xs[t.id].sort(function (v1, v2) {
            return v1 - v2;
        });
    });

    // cache information about values
    $$.hasNegativeValue = $$.hasNegativeValueInTargets(targets);
    $$.hasPositiveValue = $$.hasPositiveValueInTargets(targets);

    // set target types
    if (config.data_type) {
        $$.setTargetType($$.mapToIds(targets).filter(function (id) { return ! (id in config.data_types); }), config.data_type);
    }

    // cache as original id keyed
    targets.forEach(function (d) {
        $$.addCache(d.id_org, d);
    });

    return targets;
};
src/api.group.js000064400000000476151701472650007614 0ustar00import { Chart } from './core';
import { isUndefined } from './util';

Chart.prototype.groups = function (groups) {
    var $$ = this.internal, config = $$.config;
    if (isUndefined(groups)) { return config.data_groups; }
    config.data_groups = groups;
    $$.redraw();
    return config.data_groups;
};
src/shape.js000064400000010377151701472650007011 0ustar00import CLASS from './class';
import { ChartInternal } from './core';
import { isUndefined } from './util';

ChartInternal.prototype.getShapeIndices = function (typeFilter) {
    var $$ = this, config = $$.config,
        indices = {}, i = 0, j, k;
    $$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$)).forEach(function (d) {
        for (j = 0; j < config.data_groups.length; j++) {
            if (config.data_groups[j].indexOf(d.id) < 0) { continue; }
            for (k = 0; k < config.data_groups[j].length; k++) {
                if (config.data_groups[j][k] in indices) {
                    indices[d.id] = indices[config.data_groups[j][k]];
                    break;
                }
            }
        }
        if (isUndefined(indices[d.id])) { indices[d.id] = i++; }
    });
    indices.__max__ = i - 1;
    return indices;
};
ChartInternal.prototype.getShapeX = function (offset, targetsNum, indices, isSub) {
    var $$ = this, scale = isSub ? $$.subX : $$.x;
    return function (d) {
        var index = d.id in indices ? indices[d.id] : 0;
        return d.x || d.x === 0 ? scale(d.x) - offset * (targetsNum / 2 - index) : 0;
    };
};
ChartInternal.prototype.getShapeY = function (isSub) {
    var $$ = this;
    return function (d) {
        var scale = isSub ? $$.getSubYScale(d.id) : $$.getYScale(d.id);
        return scale(d.value);
    };
};
ChartInternal.prototype.getShapeOffset = function (typeFilter, indices, isSub) {
    var $$ = this,
        targets = $$.orderTargets($$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$))),
        targetIds = targets.map(function (t) { return t.id; });
    return function (d, i) {
        var scale = isSub ? $$.getSubYScale(d.id) : $$.getYScale(d.id),
            y0 = scale(0), offset = y0;
        targets.forEach(function (t) {
            var values = $$.isStepType(d) ? $$.convertValuesToStep(t.values) : t.values;
            if (t.id === d.id || indices[t.id] !== indices[d.id]) { return; }
            if (targetIds.indexOf(t.id) < targetIds.indexOf(d.id)) {
                // check if the x values line up
                if (typeof values[i] === 'undefined' || +values[i].x !== +d.x) {  // "+" for timeseries
                    // if not, try to find the value that does line up
                    i = -1;
                    values.forEach(function (v, j) {
                        if (v.x === d.x) {
                            i = j;
                        }
                    });
                }
                if (i in values && values[i].value * d.value >= 0) {
                    offset += scale(values[i].value) - y0;
                }
            }
        });
        return offset;
    };
};
ChartInternal.prototype.isWithinShape = function (that, d) {
    var $$ = this,
        shape = $$.d3.select(that), isWithin;
    if (!$$.isTargetToShow(d.id)) {
        isWithin = false;
    }
    else if (that.nodeName === 'circle') {
        isWithin = $$.isStepType(d) ? $$.isWithinStep(that, $$.getYScale(d.id)(d.value)) : $$.isWithinCircle(that, $$.pointSelectR(d) * 1.5);
    }
    else if (that.nodeName === 'path') {
        isWithin = shape.classed(CLASS.bar) ? $$.isWithinBar($$.d3.mouse(that), that) : true;
    }
    return isWithin;
};


ChartInternal.prototype.getInterpolate = function (d) {
    var $$ = this, d3 = $$.d3,
        types = {
            'linear': d3.curveLinear,
            'linear-closed': d3.curveLinearClosed,
            'basis': d3.curveBasis,
            'basis-open': d3.curveBasisOpen,
            'basis-closed': d3.curveBasisClosed,
            'bundle': d3.curveBundle,
            'cardinal': d3.curveCardinal,
            'cardinal-open': d3.curveCardinalOpen,
            'cardinal-closed': d3.curveCardinalClosed,
            'monotone': d3.curveMonotoneX,
            'step': d3.curveStep,
            'step-before': d3.curveStepBefore,
            'step-after': d3.curveStepAfter
        },
        type;

    if ($$.isSplineType(d)) {
        type = types[$$.config.spline_interpolation_type] || types.cardinal;
    }
    else if ($$.isStepType(d)) {
        type = types[$$.config.line_step_type];
    }
    else {
        type = types.linear;
    }
    return type;
};
src/api.zoom.js000064400000003755151701472650007447 0ustar00import { Chart } from './core';
import { isDefined } from './util';

Chart.prototype.zoom = function (domain) {
    var $$ = this.internal;
    if (domain) {
        if ($$.isTimeSeries()) {
            domain = domain.map(function (x) { return $$.parseDate(x); });
        }
        if ($$.config.subchart_show) {
            $$.brush.selectionAsValue(domain, true);
        }
        else {
            $$.updateXDomain(null, true, false, false, domain);
            $$.redraw({withY: $$.config.zoom_rescale, withSubchart: false});
        }
        $$.config.zoom_onzoom.call(this, $$.x.orgDomain());
        return domain;
    } else {
        return $$.x.domain();
    }
};
Chart.prototype.zoom.enable = function (enabled) {
    var $$ = this.internal;
    $$.config.zoom_enabled = enabled;
    $$.updateAndRedraw();
};
Chart.prototype.unzoom = function () {
    var $$ = this.internal;
    if ($$.config.subchart_show) {
        $$.brush.clear();
    }
    else {
        $$.updateXDomain(null, true, false, false, $$.subX.domain());
        $$.redraw({withY: $$.config.zoom_rescale, withSubchart: false});
    }
};

Chart.prototype.zoom.max = function (max) {
    var $$ = this.internal, config = $$.config, d3 = $$.d3;
    if (max === 0 || max) {
        config.zoom_x_max = d3.max([$$.orgXDomain[1], max]);
    }
    else {
        return config.zoom_x_max;
    }
};

Chart.prototype.zoom.min = function (min) {
    var $$ = this.internal, config = $$.config, d3 = $$.d3;
    if (min === 0 || min) {
        config.zoom_x_min = d3.min([$$.orgXDomain[0], min]);
    }
    else {
        return config.zoom_x_min;
    }
};

Chart.prototype.zoom.range = function (range) {
    if (arguments.length) {
        if (isDefined(range.max)) { this.domain.max(range.max); }
        if (isDefined(range.min)) { this.domain.min(range.min); }
    } else {
        return {
            max: this.domain.max(),
            min: this.domain.min()
        };
    }
};
src/api.x.js000064400000001035151701472650006717 0ustar00import { Chart } from './core';

Chart.prototype.x = function (x) {
    var $$ = this.internal;
    if (arguments.length) {
        $$.updateTargetX($$.data.targets, x);
        $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
    }
    return $$.data.xs;
};
Chart.prototype.xs = function (xs) {
    var $$ = this.internal;
    if (arguments.length) {
        $$.updateTargetXs($$.data.targets, xs);
        $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
    }
    return $$.data.xs;
};
src/cache.js000064400000001106151701472650006742 0ustar00import { ChartInternal } from './core';

ChartInternal.prototype.hasCaches = function (ids) {
    for (var i = 0; i < ids.length; i++) {
        if (! (ids[i] in this.cache)) { return false; }
    }
    return true;
};
ChartInternal.prototype.addCache = function (id, target) {
    this.cache[id] = this.cloneTarget(target);
};
ChartInternal.prototype.getCaches = function (ids) {
    var targets = [], i;
    for (i = 0; i < ids.length; i++) {
        if (ids[i] in this.cache) { targets.push(this.cloneTarget(this.cache[ids[i]])); }
    }
    return targets;
};
src/ua.js000064400000000525151701472650006310 0ustar00import { ChartInternal } from './core';

ChartInternal.prototype.isSafari = function () {
    var ua = window.navigator.userAgent;
    return ua.indexOf('Safari') >= 0 && ua.indexOf('Chrome') < 0;
};
ChartInternal.prototype.isChrome = function () {
    var ua = window.navigator.userAgent;
    return ua.indexOf('Chrome') >= 0;
};
src/api.selection.js000064400000005306151701472650010442 0ustar00import CLASS from './class';
import { Chart } from './core';
import { isDefined } from './util';

Chart.prototype.selected = function (targetId) {
    var $$ = this.internal, d3 = $$.d3;
    return d3.merge(
        $$.main.selectAll('.' + CLASS.shapes + $$.getTargetSelectorSuffix(targetId)).selectAll('.' + CLASS.shape)
            .filter(function () { return d3.select(this).classed(CLASS.SELECTED); })
            .map(function (d) { return d.map(function (d) { var data = d.__data__; return data.data ? data.data : data; }); })
    );
};
Chart.prototype.select = function (ids, indices, resetOther) {
    var $$ = this.internal, d3 = $$.d3, config = $$.config;
    if (! config.data_selection_enabled) { return; }
    $$.main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) {
        var shape = d3.select(this), id = d.data ? d.data.id : d.id,
            toggle = $$.getToggle(this, d).bind($$),
            isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0,
            isTargetIndex = !indices || indices.indexOf(i) >= 0,
            isSelected = shape.classed(CLASS.SELECTED);
        // line/area selection not supported yet
        if (shape.classed(CLASS.line) || shape.classed(CLASS.area)) {
            return;
        }
        if (isTargetId && isTargetIndex) {
            if (config.data_selection_isselectable(d) && !isSelected) {
                toggle(true, shape.classed(CLASS.SELECTED, true), d, i);
            }
        } else if (isDefined(resetOther) && resetOther) {
            if (isSelected) {
                toggle(false, shape.classed(CLASS.SELECTED, false), d, i);
            }
        }
    });
};
Chart.prototype.unselect = function (ids, indices) {
    var $$ = this.internal, d3 = $$.d3, config = $$.config;
    if (! config.data_selection_enabled) { return; }
    $$.main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) {
        var shape = d3.select(this), id = d.data ? d.data.id : d.id,
            toggle = $$.getToggle(this, d).bind($$),
            isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0,
            isTargetIndex = !indices || indices.indexOf(i) >= 0,
            isSelected = shape.classed(CLASS.SELECTED);
        // line/area selection not supported yet
        if (shape.classed(CLASS.line) || shape.classed(CLASS.area)) {
            return;
        }
        if (isTargetId && isTargetIndex) {
            if (config.data_selection_isselectable(d)) {
                if (isSelected) {
                    toggle(false, shape.classed(CLASS.SELECTED, false), d, i);
                }
            }
        }
    });
};
src/api.data.js000064400000002076151701472650007367 0ustar00import { Chart } from './core';

Chart.prototype.data = function (targetIds) {
    var targets = this.internal.data.targets;
    return typeof targetIds === 'undefined' ? targets : targets.filter(function (t) {
        return [].concat(targetIds).indexOf(t.id) >= 0;
    });
};
Chart.prototype.data.shown = function (targetIds) {
    return this.internal.filterTargetsToShow(this.data(targetIds));
};
Chart.prototype.data.values = function (targetId) {
    var targets, values = null;
    if (targetId) {
        targets = this.data(targetId);
        values = targets[0] ? targets[0].values.map(function (d) { return d.value; }) : null;
    }
    return values;
};
Chart.prototype.data.names = function (names) {
    this.internal.clearLegendItemTextBoxCache();
    return this.internal.updateDataAttributes('names', names);
};
Chart.prototype.data.colors = function (colors) {
    return this.internal.updateDataAttributes('colors', colors);
};
Chart.prototype.data.axes = function (axes) {
    return this.internal.updateDataAttributes('axes', axes);
};
src/api.transform.js000064400000001367151701472650010473 0ustar00import { Chart, ChartInternal } from './core';

Chart.prototype.transform = function (type, targetIds) {
    var $$ = this.internal,
        options = ['pie', 'donut'].indexOf(type) >= 0 ? {withTransform: true} : null;
    $$.transformTo(targetIds, type, options);
};

ChartInternal.prototype.transformTo = function (targetIds, type, optionsForRedraw) {
    var $$ = this,
        withTransitionForAxis = !$$.hasArcType(),
        options = optionsForRedraw || {withTransitionForAxis: withTransitionForAxis};
    options.withTransitionForTransform = false;
    $$.transiting = false;
    $$.setTargetType(targetIds, type);
    $$.updateTargets($$.data.targets); // this is needed when transforming to arc
    $$.updateAndRedraw(options);
};
src/legend.js000064400000035500151701472650007142 0ustar00import CLASS from './class';
import { ChartInternal } from './core';
import { isDefined, isEmpty, getOption } from './util';

ChartInternal.prototype.initLegend = function () {
    var $$ = this;
    $$.legendItemTextBox = {};
    $$.legendHasRendered = false;
    $$.legend = $$.svg.append("g").attr("transform", $$.getTranslate('legend'));
    if (!$$.config.legend_show) {
        $$.legend.style('visibility', 'hidden');
        $$.hiddenLegendIds = $$.mapToIds($$.data.targets);
        return;
    }
    // MEMO: call here to update legend box and tranlate for all
    // MEMO: translate will be upated by this, so transform not needed in updateLegend()
    $$.updateLegendWithDefaults();
};
ChartInternal.prototype.updateLegendWithDefaults = function () {
    var $$ = this;
    $$.updateLegend($$.mapToIds($$.data.targets), {withTransform: false, withTransitionForTransform: false, withTransition: false});
};
ChartInternal.prototype.updateSizeForLegend = function (legendHeight, legendWidth) {
    var $$ = this, config = $$.config, insetLegendPosition = {
        top: $$.isLegendTop ? $$.getCurrentPaddingTop() + config.legend_inset_y + 5.5 : $$.currentHeight - legendHeight - $$.getCurrentPaddingBottom() - config.legend_inset_y,
        left: $$.isLegendLeft ? $$.getCurrentPaddingLeft() + config.legend_inset_x + 0.5 : $$.currentWidth - legendWidth - $$.getCurrentPaddingRight() - config.legend_inset_x + 0.5
    };

    $$.margin3 = {
        top: $$.isLegendRight ? 0 : $$.isLegendInset ? insetLegendPosition.top : $$.currentHeight - legendHeight,
        right: NaN,
        bottom: 0,
        left: $$.isLegendRight ? $$.currentWidth - legendWidth : $$.isLegendInset ? insetLegendPosition.left : 0
    };
};
ChartInternal.prototype.transformLegend = function (withTransition) {
    var $$ = this;
    (withTransition ? $$.legend.transition() : $$.legend).attr("transform", $$.getTranslate('legend'));
};
ChartInternal.prototype.updateLegendStep = function (step) {
    this.legendStep = step;
};
ChartInternal.prototype.updateLegendItemWidth = function (w) {
    this.legendItemWidth = w;
};
ChartInternal.prototype.updateLegendItemHeight = function (h) {
    this.legendItemHeight = h;
};
ChartInternal.prototype.getLegendWidth = function () {
    var $$ = this;
    return $$.config.legend_show ? $$.isLegendRight || $$.isLegendInset ? $$.legendItemWidth * ($$.legendStep + 1) : $$.currentWidth : 0;
};
ChartInternal.prototype.getLegendHeight = function () {
    var $$ = this, h = 0;
    if ($$.config.legend_show) {
        if ($$.isLegendRight) {
            h = $$.currentHeight;
        } else {
            h = Math.max(20, $$.legendItemHeight) * ($$.legendStep + 1);
        }
    }
    return h;
};
ChartInternal.prototype.opacityForLegend = function (legendItem) {
    return legendItem.classed(CLASS.legendItemHidden) ? null : 1;
};
ChartInternal.prototype.opacityForUnfocusedLegend = function (legendItem) {
    return legendItem.classed(CLASS.legendItemHidden) ? null : 0.3;
};
ChartInternal.prototype.toggleFocusLegend = function (targetIds, focus) {
    var $$ = this;
    targetIds = $$.mapToTargetIds(targetIds);
    $$.legend.selectAll('.' + CLASS.legendItem)
        .filter(function (id) { return targetIds.indexOf(id) >= 0; })
        .classed(CLASS.legendItemFocused, focus)
      .transition().duration(100)
        .style('opacity', function () {
            var opacity = focus ? $$.opacityForLegend : $$.opacityForUnfocusedLegend;
            return opacity.call($$, $$.d3.select(this));
        });
};
ChartInternal.prototype.revertLegend = function () {
    var $$ = this, d3 = $$.d3;
    $$.legend.selectAll('.' + CLASS.legendItem)
        .classed(CLASS.legendItemFocused, false)
        .transition().duration(100)
        .style('opacity', function () { return $$.opacityForLegend(d3.select(this)); });
};
ChartInternal.prototype.showLegend = function (targetIds) {
    var $$ = this, config = $$.config;
    if (!config.legend_show) {
        config.legend_show = true;
        $$.legend.style('visibility', 'visible');
        if (!$$.legendHasRendered) {
            $$.updateLegendWithDefaults();
        }
    }
    $$.removeHiddenLegendIds(targetIds);
    $$.legend.selectAll($$.selectorLegends(targetIds))
        .style('visibility', 'visible')
        .transition()
        .style('opacity', function () { return $$.opacityForLegend($$.d3.select(this)); });
};
ChartInternal.prototype.hideLegend = function (targetIds) {
    var $$ = this, config = $$.config;
    if (config.legend_show && isEmpty(targetIds)) {
        config.legend_show = false;
        $$.legend.style('visibility', 'hidden');
    }
    $$.addHiddenLegendIds(targetIds);
    $$.legend.selectAll($$.selectorLegends(targetIds))
        .style('opacity', 0)
        .style('visibility', 'hidden');
};
ChartInternal.prototype.clearLegendItemTextBoxCache = function () {
    this.legendItemTextBox = {};
};
ChartInternal.prototype.updateLegend = function (targetIds, options, transitions) {
    var $$ = this, config = $$.config;
    var xForLegend, xForLegendText, xForLegendRect, yForLegend, yForLegendText, yForLegendRect, x1ForLegendTile, x2ForLegendTile, yForLegendTile;
    var paddingTop = 4, paddingRight = 10, maxWidth = 0, maxHeight = 0, posMin = 10, tileWidth = config.legend_item_tile_width + 5;
    var l, totalLength = 0, offsets = {}, widths = {}, heights = {}, margins = [0], steps = {}, step = 0;
    var withTransition, withTransitionForTransform;
    var texts, rects, tiles, background;

    // Skip elements when their name is set to null
    targetIds = targetIds.filter(function(id) {
        return !isDefined(config.data_names[id]) || config.data_names[id] !== null;
    });

    options = options || {};
    withTransition = getOption(options, "withTransition", true);
    withTransitionForTransform = getOption(options, "withTransitionForTransform", true);

    function getTextBox(textElement, id) {
        if (!$$.legendItemTextBox[id]) {
            $$.legendItemTextBox[id] = $$.getTextRect(textElement.textContent, CLASS.legendItem, textElement);
        }
        return $$.legendItemTextBox[id];
    }

    function updatePositions(textElement, id, index) {
        var reset = index === 0, isLast = index === targetIds.length - 1,
            box = getTextBox(textElement, id),
            itemWidth = box.width + tileWidth + (isLast && !($$.isLegendRight || $$.isLegendInset) ? 0 : paddingRight) + config.legend_padding,
            itemHeight = box.height + paddingTop,
            itemLength = $$.isLegendRight || $$.isLegendInset ? itemHeight : itemWidth,
            areaLength = $$.isLegendRight || $$.isLegendInset ? $$.getLegendHeight() : $$.getLegendWidth(),
            margin, maxLength;

        // MEMO: care about condifion of step, totalLength
        function updateValues(id, withoutStep) {
            if (!withoutStep) {
                margin = (areaLength - totalLength - itemLength) / 2;
                if (margin < posMin) {
                    margin = (areaLength - itemLength) / 2;
                    totalLength = 0;
                    step++;
                }
            }
            steps[id] = step;
            margins[step] = $$.isLegendInset ? 10 : margin;
            offsets[id] = totalLength;
            totalLength += itemLength;
        }

        if (reset) {
            totalLength = 0;
            step = 0;
            maxWidth = 0;
            maxHeight = 0;
        }

        if (config.legend_show && !$$.isLegendToShow(id)) {
            widths[id] = heights[id] = steps[id] = offsets[id] = 0;
            return;
        }

        widths[id] = itemWidth;
        heights[id] = itemHeight;

        if (!maxWidth || itemWidth >= maxWidth) { maxWidth = itemWidth; }
        if (!maxHeight || itemHeight >= maxHeight) { maxHeight = itemHeight; }
        maxLength = $$.isLegendRight || $$.isLegendInset ? maxHeight : maxWidth;

        if (config.legend_equally) {
            Object.keys(widths).forEach(function (id) { widths[id] = maxWidth; });
            Object.keys(heights).forEach(function (id) { heights[id] = maxHeight; });
            margin = (areaLength - maxLength * targetIds.length) / 2;
            if (margin < posMin) {
                totalLength = 0;
                step = 0;
                targetIds.forEach(function (id) { updateValues(id); });
            }
            else {
                updateValues(id, true);
            }
        } else {
            updateValues(id);
        }
    }

    if ($$.isLegendInset) {
        step = config.legend_inset_step ? config.legend_inset_step : targetIds.length;
        $$.updateLegendStep(step);
    }

    if ($$.isLegendRight) {
        xForLegend = function (id) { return maxWidth * steps[id]; };
        yForLegend = function (id) { return margins[steps[id]] + offsets[id]; };
    } else if ($$.isLegendInset) {
        xForLegend = function (id) { return maxWidth * steps[id] + 10; };
        yForLegend = function (id) { return margins[steps[id]] + offsets[id]; };
    } else {
        xForLegend = function (id) { return margins[steps[id]] + offsets[id]; };
        yForLegend = function (id) { return maxHeight * steps[id]; };
    }
    xForLegendText = function (id, i) { return xForLegend(id, i) + 4 + config.legend_item_tile_width; };
    yForLegendText = function (id, i) { return yForLegend(id, i) + 9; };
    xForLegendRect = function (id, i) { return xForLegend(id, i); };
    yForLegendRect = function (id, i) { return yForLegend(id, i) - 5; };
    x1ForLegendTile = function (id, i) { return xForLegend(id, i) - 2; };
    x2ForLegendTile = function (id, i) { return xForLegend(id, i) - 2 + config.legend_item_tile_width; };
    yForLegendTile = function (id, i) { return yForLegend(id, i) + 4; };

    // Define g for legend area
    l = $$.legend.selectAll('.' + CLASS.legendItem)
        .data(targetIds)
        .enter().append('g')
        .attr('class', function (id) { return $$.generateClass(CLASS.legendItem, id); })
        .style('visibility', function (id) { return $$.isLegendToShow(id) ? 'visible' : 'hidden'; })
        .style('cursor', 'pointer')
        .on('click', function (id) {
            if (config.legend_item_onclick) {
                config.legend_item_onclick.call($$, id);
            } else {
                if ($$.d3.event.altKey) {
                    $$.api.hide();
                    $$.api.show(id);
                } else {
                    $$.api.toggle(id);
                    $$.isTargetToShow(id) ? $$.api.focus(id) : $$.api.revert();
                }
            }
        })
        .on('mouseover', function (id) {
            if (config.legend_item_onmouseover) {
                config.legend_item_onmouseover.call($$, id);
            }
            else {
                $$.d3.select(this).classed(CLASS.legendItemFocused, true);
                if (!$$.transiting && $$.isTargetToShow(id)) {
                    $$.api.focus(id);
                }
            }
        })
        .on('mouseout', function (id) {
            if (config.legend_item_onmouseout) {
                config.legend_item_onmouseout.call($$, id);
            }
            else {
                $$.d3.select(this).classed(CLASS.legendItemFocused, false);
                $$.api.revert();
            }
        });
    l.append('text')
        .text(function (id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id; })
        .each(function (id, i) { updatePositions(this, id, i); })
        .style("pointer-events", "none")
        .attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendText : -200)
        .attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendText);
    l.append('rect')
        .attr("class", CLASS.legendItemEvent)
        .style('fill-opacity', 0)
        .attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendRect : -200)
        .attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendRect);
    l.append('line')
        .attr('class', CLASS.legendItemTile)
        .style('stroke', $$.color)
        .style("pointer-events", "none")
        .attr('x1', $$.isLegendRight || $$.isLegendInset ? x1ForLegendTile : -200)
        .attr('y1', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendTile)
        .attr('x2', $$.isLegendRight || $$.isLegendInset ? x2ForLegendTile : -200)
        .attr('y2', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendTile)
        .attr('stroke-width', config.legend_item_tile_height);

    // Set background for inset legend
    background = $$.legend.select('.' + CLASS.legendBackground + ' rect');
    if ($$.isLegendInset && maxWidth > 0 && background.size() === 0) {
        background = $$.legend.insert('g', '.' + CLASS.legendItem)
            .attr("class", CLASS.legendBackground)
            .append('rect');
    }

    texts = $$.legend.selectAll('text')
        .data(targetIds)
        .text(function (id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id; }) // MEMO: needed for update
        .each(function (id, i) { updatePositions(this, id, i); });
    (withTransition ? texts.transition() : texts)
        .attr('x', xForLegendText)
        .attr('y', yForLegendText);

    rects = $$.legend.selectAll('rect.' + CLASS.legendItemEvent)
        .data(targetIds);
    (withTransition ? rects.transition() : rects)
        .attr('width', function (id) { return widths[id]; })
        .attr('height', function (id) { return heights[id]; })
        .attr('x', xForLegendRect)
        .attr('y', yForLegendRect);

    tiles = $$.legend.selectAll('line.' + CLASS.legendItemTile)
            .data(targetIds);
        (withTransition ? tiles.transition() : tiles)
            .style('stroke', $$.levelColor ? function(id) {
                return $$.levelColor($$.cache[id].values[0].value);
            } : $$.color)
            .attr('x1', x1ForLegendTile)
            .attr('y1', yForLegendTile)
            .attr('x2', x2ForLegendTile)
            .attr('y2', yForLegendTile);

    if (background) {
        (withTransition ? background.transition() : background)
            .attr('height', $$.getLegendHeight() - 12)
            .attr('width', maxWidth * (step + 1) + 10);
    }

    // toggle legend state
    $$.legend.selectAll('.' + CLASS.legendItem)
        .classed(CLASS.legendItemHidden, function (id) { return !$$.isTargetToShow(id); });

    // Update all to reflect change of legend
    $$.updateLegendItemWidth(maxWidth);
    $$.updateLegendItemHeight(maxHeight);
    $$.updateLegendStep(step);
    // Update size and scale
    $$.updateSizes();
    $$.updateScales();
    $$.updateSvgSize();
    // Update g positions
    $$.transformAll(withTransitionForTransform, transitions);
    $$.legendHasRendered = true;
};
src/api.load.js000064400000004006151701472650007370 0ustar00import { Chart } from './core';

Chart.prototype.load = function (args) {
    var $$ = this.internal, config = $$.config;
    // update xs if specified
    if (args.xs) {
        $$.addXs(args.xs);
    }
    // update names if exists
    if ('names' in args) {
        Chart.prototype.data.names.bind(this)(args.names);
    }
    // update classes if exists
    if ('classes' in args) {
        Object.keys(args.classes).forEach(function (id) {
            config.data_classes[id] = args.classes[id];
        });
    }
    // update categories if exists
    if ('categories' in args && $$.isCategorized()) {
        config.axis_x_categories = args.categories;
    }
    // update axes if exists
    if ('axes' in args) {
        Object.keys(args.axes).forEach(function (id) {
            config.data_axes[id] = args.axes[id];
        });
    }
    // update colors if exists
    if ('colors' in args) {
        Object.keys(args.colors).forEach(function (id) {
            config.data_colors[id] = args.colors[id];
        });
    }
    // use cache if exists
    if ('cacheIds' in args && $$.hasCaches(args.cacheIds)) {
        $$.load($$.getCaches(args.cacheIds), args.done);
        return;
    }
    // unload if needed
    if ('unload' in args) {
        // TODO: do not unload if target will load (included in url/rows/columns)
        $$.unload($$.mapToTargetIds((typeof args.unload === 'boolean' && args.unload) ? null : args.unload), function () {
            $$.loadFromArgs(args);
        });
    } else {
        $$.loadFromArgs(args);
    }
};

Chart.prototype.unload = function (args) {
    var $$ = this.internal;
    args = args || {};
    if (args instanceof Array) {
        args = {ids: args};
    } else if (typeof args === 'string') {
        args = {ids: [args]};
    }
    $$.unload($$.mapToTargetIds(args.ids), function () {
        $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
        if (args.done) { args.done(); }
    });
};
src/arc.js000064400000053207151701472650006455 0ustar00import CLASS from './class';
import { ChartInternal } from './core';
import { isFunction } from './util';

ChartInternal.prototype.initPie = function () {
    var $$ = this, d3 = $$.d3;
    $$.pie = d3.pie().value(function (d) {
        return d.values.reduce(function (a, b) { return a + b.value; }, 0);
    });

    let orderFct = $$.getOrderFunction();

    // we need to reverse the returned order if asc or desc to have the slice in expected order.
    if (orderFct && ($$.isOrderAsc() || $$.isOrderDesc())) {
        let defaultSort = orderFct;
        orderFct = (t1, t2) => defaultSort(t1, t2) * -1;
    }

    $$.pie.sort(orderFct || null);
};

ChartInternal.prototype.updateRadius = function () {
    var $$ = this, config = $$.config,
        w = config.gauge_width || config.donut_width,
        gaugeArcWidth = $$.filterTargetsToShow($$.data.targets).length * $$.config.gauge_arcs_minWidth;
    $$.radiusExpanded = Math.min($$.arcWidth, $$.arcHeight) / 2 * ($$.hasType('gauge') ? 0.85 : 1);
    $$.radius = $$.radiusExpanded * 0.95;
    $$.innerRadiusRatio = w ? ($$.radius - w) / $$.radius : 0.6;
    $$.innerRadius = $$.hasType('donut') || $$.hasType('gauge') ? $$.radius * $$.innerRadiusRatio : 0;
    $$.gaugeArcWidth = w ? w : (gaugeArcWidth <= $$.radius - $$.innerRadius ? $$.radius - $$.innerRadius : (gaugeArcWidth <= $$.radius ? gaugeArcWidth : $$.radius));
};

ChartInternal.prototype.updateArc = function () {
    var $$ = this;
    $$.svgArc = $$.getSvgArc();
    $$.svgArcExpanded = $$.getSvgArcExpanded();
    $$.svgArcExpandedSub = $$.getSvgArcExpanded(0.98);
};

ChartInternal.prototype.updateAngle = function (d) {
    var $$ = this, config = $$.config,
        found = false, index = 0,
        gMin, gMax, gTic, gValue;

    if (!config) {
        return null;
    }

    $$.pie($$.filterTargetsToShow($$.data.targets)).forEach(function (t) {
        if (! found && t.data.id === d.data.id) {
            found = true;
            d = t;
            d.index = index;
        }
        index++;
    });
    if (isNaN(d.startAngle)) {
        d.startAngle = 0;
    }
    if (isNaN(d.endAngle)) {
        d.endAngle = d.startAngle;
    }
    if ($$.isGaugeType(d.data)) {
        gMin = config.gauge_min;
        gMax = config.gauge_max;
        gTic = (Math.PI * (config.gauge_fullCircle ? 2 : 1)) / (gMax - gMin);
        gValue = d.value < gMin ? 0 : d.value < gMax ? d.value - gMin : (gMax - gMin);
        d.startAngle = config.gauge_startingAngle;
        d.endAngle = d.startAngle + gTic * gValue;
    }
    return found ? d : null;
};

ChartInternal.prototype.getSvgArc = function () {
    var $$ = this, hasGaugeType = $$.hasType('gauge'),
        singleArcWidth = $$.gaugeArcWidth / $$.filterTargetsToShow($$.data.targets).length,
        arc = $$.d3.arc().outerRadius(function(d) {
            return hasGaugeType ? $$.radius - singleArcWidth * d.index : $$.radius;
        }).innerRadius(function(d) {
            return hasGaugeType ? $$.radius - singleArcWidth * (d.index + 1) : $$.innerRadius;
        }),
        newArc = function (d, withoutUpdate) {
            var updated;
            if (withoutUpdate) { return arc(d); } // for interpolate
            updated = $$.updateAngle(d);
            return updated ? arc(updated) : "M 0 0";
        };
    // TODO: extends all function
    newArc.centroid = arc.centroid;
    return newArc;
};

ChartInternal.prototype.getSvgArcExpanded = function (rate) {
    rate = rate || 1;
    var $$ = this, hasGaugeType = $$.hasType('gauge'),
        singleArcWidth = $$.gaugeArcWidth / $$.filterTargetsToShow($$.data.targets).length,
        expandWidth = Math.min($$.radiusExpanded * rate - $$.radius, singleArcWidth * 0.8 - (1 - rate) * 100),
        arc = $$.d3.arc().outerRadius(function(d){
            return hasGaugeType ? $$.radius - singleArcWidth * d.index + expandWidth : $$.radiusExpanded * rate;
        }).innerRadius(function(d){
            return hasGaugeType ? $$.radius - singleArcWidth * (d.index + 1) : $$.innerRadius;
        });
    return function (d) {
        var updated = $$.updateAngle(d);
        return updated ? arc(updated) : "M 0 0";
    };
};

ChartInternal.prototype.getArc = function (d, withoutUpdate, force) {
    return force || this.isArcType(d.data) ? this.svgArc(d, withoutUpdate) : "M 0 0";
};


ChartInternal.prototype.transformForArcLabel = function (d) {
    var $$ = this, config = $$.config,
        updated = $$.updateAngle(d), c, x, y, h, ratio, translate = "", hasGauge = $$.hasType('gauge');
    if (updated && !hasGauge) {
        c = this.svgArc.centroid(updated);
        x = isNaN(c[0]) ? 0 : c[0];
        y = isNaN(c[1]) ? 0 : c[1];
        h = Math.sqrt(x * x + y * y);
        if ($$.hasType('donut') && config.donut_label_ratio) {
            ratio = isFunction(config.donut_label_ratio) ? config.donut_label_ratio(d, $$.radius, h) : config.donut_label_ratio;
        } else if ($$.hasType('pie') && config.pie_label_ratio) {
            ratio = isFunction(config.pie_label_ratio) ? config.pie_label_ratio(d, $$.radius, h) : config.pie_label_ratio;
        } else {
            ratio = $$.radius && h ? (36 / $$.radius > 0.375 ? 1.175 - 36 / $$.radius : 0.8) * $$.radius / h : 0;
        }
        translate = "translate(" + (x * ratio) +  ',' + (y * ratio) +  ")";
    }
    else if (updated && hasGauge && $$.filterTargetsToShow($$.data.targets).length > 1) {
        var y1 = Math.sin(updated.endAngle - Math.PI / 2);
        x = Math.cos(updated.endAngle - Math.PI / 2) * ($$.radiusExpanded + 25);
        y = y1 * ($$.radiusExpanded + 15 - Math.abs(y1 * 10)) + 3;
        translate = "translate(" + x +  ',' + y +  ")";
    }
    return translate;
};

ChartInternal.prototype.getArcRatio = function (d) {
    var $$ = this,
        config = $$.config,
        whole = Math.PI * ($$.hasType('gauge') && !config.gauge_fullCircle ? 1 : 2);
    return d ? (d.endAngle - d.startAngle) / whole : null;
};

ChartInternal.prototype.convertToArcData = function (d) {
    return this.addName({
        id: d.data.id,
        value: d.value,
        ratio: this.getArcRatio(d),
        index: d.index
    });
};

ChartInternal.prototype.textForArcLabel = function (d) {
    var $$ = this,
        updated, value, ratio, id, format;
    if (! $$.shouldShowArcLabel()) { return ""; }
    updated = $$.updateAngle(d);
    value = updated ? updated.value : null;
    ratio = $$.getArcRatio(updated);
    id = d.data.id;
    if (! $$.hasType('gauge') && ! $$.meetsArcLabelThreshold(ratio)) { return ""; }
    format = $$.getArcLabelFormat();
    return format ? format(value, ratio, id) : $$.defaultArcValueFormat(value, ratio);
};

ChartInternal.prototype.textForGaugeMinMax = function (value, isMax) {
    var $$ = this,
        format = $$.getGaugeLabelExtents();

    return format ? format(value, isMax) : value;
};

ChartInternal.prototype.expandArc = function (targetIds) {
    var $$ = this, interval;

    // MEMO: avoid to cancel transition
    if ($$.transiting) {
        interval = window.setInterval(function () {
            if (!$$.transiting) {
                window.clearInterval(interval);
                if ($$.legend.selectAll('.c3-legend-item-focused').size() > 0) {
                    $$.expandArc(targetIds);
                }
            }
        }, 10);
        return;
    }

    targetIds = $$.mapToTargetIds(targetIds);

    $$.svg.selectAll($$.selectorTargets(targetIds, '.' + CLASS.chartArc)).each(function (d) {
        if (! $$.shouldExpand(d.data.id)) { return; }
        $$.d3.select(this).selectAll('path')
            .transition().duration($$.expandDuration(d.data.id))
            .attr("d", $$.svgArcExpanded)
            .transition().duration($$.expandDuration(d.data.id) * 2)
            .attr("d", $$.svgArcExpandedSub)
            .each(function (d) {
                if ($$.isDonutType(d.data)) {
                    // callback here
                }
            });
    });
};

ChartInternal.prototype.unexpandArc = function (targetIds) {
    var $$ = this;

    if ($$.transiting) { return; }

    targetIds = $$.mapToTargetIds(targetIds);

    $$.svg.selectAll($$.selectorTargets(targetIds, '.' + CLASS.chartArc)).selectAll('path')
        .transition().duration(function(d) {
            return $$.expandDuration(d.data.id);
        })
        .attr("d", $$.svgArc);
    $$.svg.selectAll('.' + CLASS.arc);
};

ChartInternal.prototype.expandDuration = function (id) {
    var $$ = this, config = $$.config;

    if ($$.isDonutType(id)) {
        return config.donut_expand_duration;
    } else if ($$.isGaugeType(id)) {
        return config.gauge_expand_duration;
    } else if ($$.isPieType(id)) {
        return config.pie_expand_duration;
    } else {
        return 50;
    }

};

ChartInternal.prototype.shouldExpand = function (id) {
    var $$ = this, config = $$.config;
    return ($$.isDonutType(id) && config.donut_expand) ||
           ($$.isGaugeType(id) && config.gauge_expand) ||
           ($$.isPieType(id) && config.pie_expand);
};

ChartInternal.prototype.shouldShowArcLabel = function () {
    var $$ = this, config = $$.config, shouldShow = true;
    if ($$.hasType('donut')) {
        shouldShow = config.donut_label_show;
    } else if ($$.hasType('pie')) {
        shouldShow = config.pie_label_show;
    }
    // when gauge, always true
    return shouldShow;
};

ChartInternal.prototype.meetsArcLabelThreshold = function (ratio) {
    var $$ = this, config = $$.config,
        threshold = $$.hasType('donut') ? config.donut_label_threshold : config.pie_label_threshold;
    return ratio >= threshold;
};

ChartInternal.prototype.getArcLabelFormat = function () {
    var $$ = this, config = $$.config,
        format = config.pie_label_format;
    if ($$.hasType('gauge')) {
        format = config.gauge_label_format;
    } else if ($$.hasType('donut')) {
        format = config.donut_label_format;
    }
    return format;
};

ChartInternal.prototype.getGaugeLabelExtents = function () {
    var $$ = this, config = $$.config;
    return config.gauge_label_extents;
};

ChartInternal.prototype.getArcTitle = function () {
    var $$ = this;
    return $$.hasType('donut') ? $$.config.donut_title : "";
};

ChartInternal.prototype.updateTargetsForArc = function (targets) {
    var $$ = this, main = $$.main,
        mainPies, mainPieEnter,
        classChartArc = $$.classChartArc.bind($$),
        classArcs = $$.classArcs.bind($$),
        classFocus = $$.classFocus.bind($$);
    mainPies = main.select('.' + CLASS.chartArcs).selectAll('.' + CLASS.chartArc)
        .data($$.pie(targets))
        .attr("class", function (d) { return classChartArc(d) + classFocus(d.data); });
    mainPieEnter = mainPies.enter().append("g")
        .attr("class", classChartArc);
    mainPieEnter.append('g')
        .attr('class', classArcs);
    mainPieEnter.append("text")
        .attr("dy", $$.hasType('gauge') ? "-.1em" : ".35em")
        .style("opacity", 0)
        .style("text-anchor", "middle")
        .style("pointer-events", "none");
    // MEMO: can not keep same color..., but not bad to update color in redraw
    //mainPieUpdate.exit().remove();
};

ChartInternal.prototype.initArc = function () {
    var $$ = this;
    $$.arcs = $$.main.select('.' + CLASS.chart).append("g")
        .attr("class", CLASS.chartArcs)
        .attr("transform", $$.getTranslate('arc'));
    $$.arcs.append('text')
        .attr('class', CLASS.chartArcsTitle)
        .style("text-anchor", "middle")
        .text($$.getArcTitle());
};

ChartInternal.prototype.redrawArc = function (duration, durationForExit, withTransform) {
    var $$ = this, d3 = $$.d3, config = $$.config, main = $$.main,
        arcs, mainArc,
	arcLabelLines, mainArcLabelLine,
	hasGaugeType = $$.hasType('gauge');
    arcs = main.selectAll('.' + CLASS.arcs).selectAll('.' + CLASS.arc)
        .data($$.arcData.bind($$));
    mainArc = arcs.enter().append('path')
        .attr("class", $$.classArc.bind($$))
        .style("fill", function (d) { return $$.color(d.data); })
        .style("cursor", function (d) { return config.interaction_enabled && config.data_selection_isselectable(d) ? "pointer" : null; })
        .each(function (d) {
            if ($$.isGaugeType(d.data)) {
                d.startAngle = d.endAngle = config.gauge_startingAngle;
            }
            this._current = d;
        })
        .merge(arcs);
    if (hasGaugeType) {
        arcLabelLines = main.selectAll('.' + CLASS.arcs).selectAll('.' + CLASS.arcLabelLine)
            .data($$.arcData.bind($$));
        mainArcLabelLine = arcLabelLines.enter().append('rect')
            .attr("class", function (d) { return CLASS.arcLabelLine + ' ' + CLASS.target + ' ' + CLASS.target + '-' + d.data.id; })
        .merge(arcLabelLines);

        if ($$.filterTargetsToShow($$.data.targets).length === 1) {
            mainArcLabelLine.style("display", "none");
        }
        else {
            mainArcLabelLine
                .style("fill", function (d) { return config.color_pattern.length > 0 ? $$.levelColor(d.data.values[0].value) : $$.color(d.data); })
                .style("display", config.gauge_labelLine_show ? "" : "none")
                .each(function (d) {
                    var lineLength = 0, lineThickness = 2, x = 0, y = 0, transform = "";
                    if ($$.hiddenTargetIds.indexOf(d.data.id) < 0) {
                        var updated = $$.updateAngle(d),
                            innerLineLength = $$.gaugeArcWidth / $$.filterTargetsToShow($$.data.targets).length * (updated.index + 1),
                            lineAngle = updated.endAngle - Math.PI / 2,
                            arcInnerRadius = $$.radius - innerLineLength,
                            linePositioningAngle = lineAngle - (arcInnerRadius === 0 ? 0 : (1 / arcInnerRadius));
                        lineLength = $$.radiusExpanded - $$.radius + innerLineLength;
                        x = Math.cos(linePositioningAngle) * arcInnerRadius;
                        y = Math.sin(linePositioningAngle) * arcInnerRadius;
                        transform = "rotate(" + (lineAngle * 180 / Math.PI) + ", " + x + ", " + y + ")";
                    }
                    d3.select(this)
                        .attr('x', x)
                        .attr('y', y)
                        .attr('width', lineLength)
                        .attr('height', lineThickness)
                        .attr('transform', transform)
                        .style("stroke-dasharray", "0, " + (lineLength + lineThickness) + ", 0");
                });
        }
    }
    mainArc
        .attr("transform", function (d) { return !$$.isGaugeType(d.data) && withTransform ? "scale(0)" : ""; })
        .on('mouseover', config.interaction_enabled ? function (d) {
            var updated, arcData;
            if ($$.transiting) { // skip while transiting
                return;
            }
            updated = $$.updateAngle(d);
            if (updated) {
                arcData = $$.convertToArcData(updated);
                // transitions
                $$.expandArc(updated.data.id);
                $$.api.focus(updated.data.id);
                $$.toggleFocusLegend(updated.data.id, true);
                $$.config.data_onmouseover(arcData, this);
            }
        } : null)
        .on('mousemove', config.interaction_enabled ? function (d) {
            var updated = $$.updateAngle(d), arcData, selectedData;
            if (updated) {
                arcData = $$.convertToArcData(updated),
                selectedData = [arcData];
                $$.showTooltip(selectedData, this);
            }
        } : null)
        .on('mouseout', config.interaction_enabled ? function (d) {
            var updated, arcData;
            if ($$.transiting) { // skip while transiting
                return;
            }
            updated = $$.updateAngle(d);
            if (updated) {
                arcData = $$.convertToArcData(updated);
                // transitions
                $$.unexpandArc(updated.data.id);
                $$.api.revert();
                $$.revertLegend();
                $$.hideTooltip();
                $$.config.data_onmouseout(arcData, this);
            }
        } : null)
        .on('click', config.interaction_enabled ? function (d, i) {
            var updated = $$.updateAngle(d), arcData;
            if (updated) {
                arcData = $$.convertToArcData(updated);
                if ($$.toggleShape) {
                    $$.toggleShape(this, arcData, i);
                }
                $$.config.data_onclick.call($$.api, arcData, this);
            }
        } : null)
        .each(function () { $$.transiting = true; })
        .transition().duration(duration)
        .attrTween("d", function (d) {
            var updated = $$.updateAngle(d), interpolate;
            if (! updated) {
                return function () { return "M 0 0"; };
            }
            //                if (this._current === d) {
            //                    this._current = {
            //                        startAngle: Math.PI*2,
            //                        endAngle: Math.PI*2,
            //                    };
            //                }
            if (isNaN(this._current.startAngle)) {
                this._current.startAngle = 0;
            }
            if (isNaN(this._current.endAngle)) {
                this._current.endAngle = this._current.startAngle;
            }
            interpolate = d3.interpolate(this._current, updated);
            this._current = interpolate(0);
            return function (t) {
                var interpolated = interpolate(t);
                interpolated.data = d.data; // data.id will be updated by interporator
                return $$.getArc(interpolated, true);
            };
        })
        .attr("transform", withTransform ? "scale(1)" : "")
        .style("fill", function (d) {
            return $$.levelColor ? $$.levelColor(d.data.values[0].value) : $$.color(d.data.id);
        }) // Where gauge reading color would receive customization.
        .call($$.endall, function () {
            $$.transiting = false;
        });
    arcs.exit().transition().duration(durationForExit)
        .style('opacity', 0)
        .remove();
    main.selectAll('.' + CLASS.chartArc).select('text')
        .style("opacity", 0)
        .attr('class', function (d) { return $$.isGaugeType(d.data) ? CLASS.gaugeValue : ''; })
        .text($$.textForArcLabel.bind($$))
        .attr("transform", $$.transformForArcLabel.bind($$))
        .style('font-size', function (d) { return $$.isGaugeType(d.data) && $$.filterTargetsToShow($$.data.targets).length === 1 ? Math.round($$.radius / 5) + 'px' : ''; })
      .transition().duration(duration)
        .style("opacity", function (d) { return $$.isTargetToShow(d.data.id) && $$.isArcType(d.data) ? 1 : 0; });
    main.select('.' + CLASS.chartArcsTitle)
        .style("opacity", $$.hasType('donut') || hasGaugeType ? 1 : 0);

    if (hasGaugeType) {
        let index = 0;
        const backgroundArc = $$.arcs.select('g.' + CLASS.chartArcsBackground).selectAll('path.' + CLASS.chartArcsBackground).data($$.data.targets);

        backgroundArc
            .enter()
            .append("path")
            .attr("class", (d, i) => CLASS.chartArcsBackground + ' ' + CLASS.chartArcsBackground +'-'+ i)
            .merge(backgroundArc)
            .attr("d", d1 => {
                if ($$.hiddenTargetIds.indexOf(d1.id) >= 0) { return "M 0 0"; }

                var d = {
                    data: [{value: config.gauge_max}],
                    startAngle: config.gauge_startingAngle,
                    endAngle: -1 * config.gauge_startingAngle * (config.gauge_fullCircle ? Math.PI : 1),
                    index: index++
                };
                return $$.getArc(d, true, true);
            });

        backgroundArc
            .exit()
            .remove();

        $$.arcs.select('.' + CLASS.chartArcsGaugeUnit)
            .attr("dy", ".75em")
            .text(config.gauge_label_show ? config.gauge_units : '');
        $$.arcs.select('.' + CLASS.chartArcsGaugeMin)
            .attr("dx", -1 * ($$.innerRadius + (($$.radius - $$.innerRadius) / (config.gauge_fullCircle ? 1 : 2))) + "px")
            .attr("dy", "1.2em")
            .text(config.gauge_label_show ? $$.textForGaugeMinMax(config.gauge_min, false) : '');
        $$.arcs.select('.' + CLASS.chartArcsGaugeMax)
            .attr("dx", $$.innerRadius + (($$.radius - $$.innerRadius) / (config.gauge_fullCircle ? 1 : 2)) + "px")
            .attr("dy", "1.2em")
            .text(config.gauge_label_show ? $$.textForGaugeMinMax(config.gauge_max, true) : '');
    }
};
ChartInternal.prototype.initGauge = function () {
    var arcs = this.arcs;
    if (this.hasType('gauge')) {
        arcs.append('g')
            .attr("class", CLASS.chartArcsBackground);
        arcs.append("text")
            .attr("class", CLASS.chartArcsGaugeUnit)
            .style("text-anchor", "middle")
            .style("pointer-events", "none");
        arcs.append("text")
            .attr("class", CLASS.chartArcsGaugeMin)
            .style("text-anchor", "middle")
            .style("pointer-events", "none");
        arcs.append("text")
            .attr("class", CLASS.chartArcsGaugeMax)
            .style("text-anchor", "middle")
            .style("pointer-events", "none");
    }
};
ChartInternal.prototype.getGaugeLabelHeight = function () {
    return this.config.gauge_label_show ? 20 : 0;
};
src/shape.line.js000064400000040655151701472650007741 0ustar00import CLASS from './class';
import { ChartInternal } from './core';
import { isValue, isFunction, isUndefined, isDefined } from './util';

ChartInternal.prototype.initLine = function () {
    var $$ = this;
    $$.main.select('.' + CLASS.chart).append("g")
        .attr("class", CLASS.chartLines);
};
ChartInternal.prototype.updateTargetsForLine = function (targets) {
    var $$ = this, config = $$.config,
        mainLines, mainLineEnter,
        classChartLine = $$.classChartLine.bind($$),
        classLines = $$.classLines.bind($$),
        classAreas = $$.classAreas.bind($$),
        classCircles = $$.classCircles.bind($$),
        classFocus = $$.classFocus.bind($$);
    mainLines = $$.main.select('.' + CLASS.chartLines).selectAll('.' + CLASS.chartLine)
        .data(targets)
        .attr('class', function (d) { return classChartLine(d) + classFocus(d); });
    mainLineEnter = mainLines.enter().append('g')
        .attr('class', classChartLine)
        .style('opacity', 0)
        .style("pointer-events", "none");
    // Lines for each data
    mainLineEnter.append('g')
        .attr("class", classLines);
    // Areas
    mainLineEnter.append('g')
        .attr('class', classAreas);
    // Circles for each data point on lines
    mainLineEnter.append('g')
        .attr("class", function (d) { return $$.generateClass(CLASS.selectedCircles, d.id); });
    mainLineEnter.append('g')
        .attr("class", classCircles)
        .style("cursor", function (d) { return config.data_selection_isselectable(d) ? "pointer" : null; });
    // Update date for selected circles
    targets.forEach(function (t) {
        $$.main.selectAll('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(t.id)).selectAll('.' + CLASS.selectedCircle).each(function (d) {
            d.value = t.values[d.index].value;
        });
    });
    // MEMO: can not keep same color...
    //mainLineUpdate.exit().remove();
};
ChartInternal.prototype.updateLine = function (durationForExit) {
    var $$ = this;
    var mainLine = $$.main.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line)
        .data($$.lineData.bind($$));
    var mainLineEnter = mainLine.enter().append('path')
        .attr('class', $$.classLine.bind($$))
        .style("stroke", $$.color);
    $$.mainLine = mainLineEnter.merge(mainLine)
        .style("opacity", $$.initialOpacity.bind($$))
        .style('shape-rendering', function (d) { return $$.isStepType(d) ? 'crispEdges' : ''; })
        .attr('transform', null);
    mainLine.exit().transition().duration(durationForExit)
        .style('opacity', 0);
};
ChartInternal.prototype.redrawLine = function (drawLine, withTransition, transition) {
    return [
        (withTransition ? this.mainLine.transition(transition) : this.mainLine)
            .attr("d", drawLine)
            .style("stroke", this.color)
            .style("opacity", 1)
    ];
};
ChartInternal.prototype.generateDrawLine = function (lineIndices, isSub) {
    var $$ = this, config = $$.config,
        line = $$.d3.line(),
        getPoints = $$.generateGetLinePoints(lineIndices, isSub),
        yScaleGetter = isSub ? $$.getSubYScale : $$.getYScale,
        xValue = function (d) { return (isSub ? $$.subxx : $$.xx).call($$, d); },
        yValue = function (d, i) {
            return config.data_groups.length > 0 ? getPoints(d, i)[0][1] : yScaleGetter.call($$, d.id)(d.value);
        };

    line = config.axis_rotated ? line.x(yValue).y(xValue) : line.x(xValue).y(yValue);
    if (!config.line_connectNull) { line = line.defined(function (d) { return d.value != null; }); }
    return function (d) {
        var values = config.line_connectNull ? $$.filterRemoveNull(d.values) : d.values,
            x = isSub ? $$.subX : $$.x, y = yScaleGetter.call($$, d.id), x0 = 0, y0 = 0, path;
        if ($$.isLineType(d)) {
            if (config.data_regions[d.id]) {
                path = $$.lineWithRegions(values, x, y, config.data_regions[d.id]);
            } else {
                if ($$.isStepType(d)) { values = $$.convertValuesToStep(values); }
                path = line.curve($$.getInterpolate(d))(values);
            }
        } else {
            if (values[0]) {
                x0 = x(values[0].x);
                y0 = y(values[0].value);
            }
            path = config.axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0;
        }
        return path ? path : "M 0 0";
    };
};
ChartInternal.prototype.generateGetLinePoints = function (lineIndices, isSub) { // partial duplication of generateGetBarPoints
    var $$ = this, config = $$.config,
        lineTargetsNum = lineIndices.__max__ + 1,
        x = $$.getShapeX(0, lineTargetsNum, lineIndices, !!isSub),
        y = $$.getShapeY(!!isSub),
        lineOffset = $$.getShapeOffset($$.isLineType, lineIndices, !!isSub),
        yScale = isSub ? $$.getSubYScale : $$.getYScale;
    return function (d, i) {
        var y0 = yScale.call($$, d.id)(0),
            offset = lineOffset(d, i) || y0, // offset is for stacked area chart
            posX = x(d), posY = y(d);
        // fix posY not to overflow opposite quadrant
        if (config.axis_rotated) {
            if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; }
        }
        // 1 point that marks the line position
        return [
            [posX, posY - (y0 - offset)],
            [posX, posY - (y0 - offset)], // needed for compatibility
            [posX, posY - (y0 - offset)], // needed for compatibility
            [posX, posY - (y0 - offset)]  // needed for compatibility
        ];
    };
};


ChartInternal.prototype.lineWithRegions = function (d, x, y, _regions) {
    var $$ = this, config = $$.config,
        prev = -1, i, j,
        s = "M", sWithRegion,
        xp, yp, dx, dy, dd, diff, diffx2,
        xOffset = $$.isCategorized() ? 0.5 : 0,
        xValue, yValue,
        regions = [];

    function isWithinRegions(x, regions) {
        var i;
        for (i = 0; i < regions.length; i++) {
            if (regions[i].start < x && x <= regions[i].end) { return true; }
        }
        return false;
    }

    // Check start/end of regions
    if (isDefined(_regions)) {
        for (i = 0; i < _regions.length; i++) {
            regions[i] = {};
            if (isUndefined(_regions[i].start)) {
                regions[i].start = d[0].x;
            } else {
                regions[i].start = $$.isTimeSeries() ? $$.parseDate(_regions[i].start) : _regions[i].start;
            }
            if (isUndefined(_regions[i].end)) {
                regions[i].end = d[d.length - 1].x;
            } else {
                regions[i].end = $$.isTimeSeries() ? $$.parseDate(_regions[i].end) : _regions[i].end;
            }
        }
    }

    // Set scales
    xValue = config.axis_rotated ? function (d) { return y(d.value); } : function (d) { return x(d.x); };
    yValue = config.axis_rotated ? function (d) { return x(d.x); } : function (d) { return y(d.value); };

    // Define svg generator function for region
    function generateM(points) {
        return 'M' + points[0][0] + ' ' + points[0][1] + ' ' + points[1][0] + ' ' + points[1][1];
    }
    if ($$.isTimeSeries()) {
        sWithRegion = function (d0, d1, j, diff) {
            var x0 = d0.x.getTime(), x_diff = d1.x - d0.x,
                xv0 = new Date(x0 + x_diff * j),
                xv1 = new Date(x0 + x_diff * (j + diff)),
                points;
            if (config.axis_rotated) {
                points = [[y(yp(j)), x(xv0)], [y(yp(j + diff)), x(xv1)]];
            } else {
                points = [[x(xv0), y(yp(j))], [x(xv1), y(yp(j + diff))]];
            }
            return generateM(points);
        };
    } else {
        sWithRegion = function (d0, d1, j, diff) {
            var points;
            if (config.axis_rotated) {
                points = [[y(yp(j), true), x(xp(j))], [y(yp(j + diff), true), x(xp(j + diff))]];
            } else {
                points = [[x(xp(j), true), y(yp(j))], [x(xp(j + diff), true), y(yp(j + diff))]];
            }
            return generateM(points);
        };
    }

    // Generate
    for (i = 0; i < d.length; i++) {

        // Draw as normal
        if (isUndefined(regions) || ! isWithinRegions(d[i].x, regions)) {
            s += " " + xValue(d[i]) + " " + yValue(d[i]);
        }
        // Draw with region // TODO: Fix for horizotal charts
        else {
            xp = $$.getScale(d[i - 1].x + xOffset, d[i].x + xOffset, $$.isTimeSeries());
            yp = $$.getScale(d[i - 1].value, d[i].value);

            dx = x(d[i].x) - x(d[i - 1].x);
            dy = y(d[i].value) - y(d[i - 1].value);
            dd = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
            diff = 2 / dd;
            diffx2 = diff * 2;

            for (j = diff; j <= 1; j += diffx2) {
                s += sWithRegion(d[i - 1], d[i], j, diff);
            }
        }
        prev = d[i].x;
    }

    return s;
};


ChartInternal.prototype.updateArea = function (durationForExit) {
    var $$ = this, d3 = $$.d3;
    var mainArea = $$.main.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area)
        .data($$.lineData.bind($$));
    var mainAreaEnter = mainArea.enter().append('path')
        .attr("class", $$.classArea.bind($$))
        .style("fill", $$.color)
        .style("opacity", function () { $$.orgAreaOpacity = +d3.select(this).style('opacity'); return 0; });
    $$.mainArea = mainAreaEnter.merge(mainArea)
        .style("opacity", $$.orgAreaOpacity);
    mainArea.exit().transition().duration(durationForExit)
        .style('opacity', 0);
};
ChartInternal.prototype.redrawArea = function (drawArea, withTransition, transition) {
    return [
        (withTransition ? this.mainArea.transition(transition) : this.mainArea)
            .attr("d", drawArea)
            .style("fill", this.color)
            .style("opacity", this.orgAreaOpacity)
    ];
};
ChartInternal.prototype.generateDrawArea = function (areaIndices, isSub) {
    var $$ = this, config = $$.config, area = $$.d3.area(),
        getPoints = $$.generateGetAreaPoints(areaIndices, isSub),
        yScaleGetter = isSub ? $$.getSubYScale : $$.getYScale,
        xValue = function (d) { return (isSub ? $$.subxx : $$.xx).call($$, d); },
        value0 = function (d, i) {
            return config.data_groups.length > 0 ? getPoints(d, i)[0][1] : yScaleGetter.call($$, d.id)($$.getAreaBaseValue(d.id));
        },
        value1 = function (d, i) {
            return config.data_groups.length > 0 ? getPoints(d, i)[1][1] : yScaleGetter.call($$, d.id)(d.value);
        };

    area = config.axis_rotated ? area.x0(value0).x1(value1).y(xValue) : area.x(xValue).y0(config.area_above ? 0 : value0).y1(value1);
    if (!config.line_connectNull) {
        area = area.defined(function (d) { return d.value !== null; });
    }

    return function (d) {
        var values = config.line_connectNull ? $$.filterRemoveNull(d.values) : d.values,
            x0 = 0, y0 = 0, path;
        if ($$.isAreaType(d)) {
            if ($$.isStepType(d)) { values = $$.convertValuesToStep(values); }
            path = area.curve($$.getInterpolate(d))(values);
        } else {
            if (values[0]) {
                x0 = $$.x(values[0].x);
                y0 = $$.getYScale(d.id)(values[0].value);
            }
            path = config.axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0;
        }
        return path ? path : "M 0 0";
    };
};
ChartInternal.prototype.getAreaBaseValue = function () {
    return 0;
};
ChartInternal.prototype.generateGetAreaPoints = function (areaIndices, isSub) { // partial duplication of generateGetBarPoints
    var $$ = this, config = $$.config,
        areaTargetsNum = areaIndices.__max__ + 1,
        x = $$.getShapeX(0, areaTargetsNum, areaIndices, !!isSub),
        y = $$.getShapeY(!!isSub),
        areaOffset = $$.getShapeOffset($$.isAreaType, areaIndices, !!isSub),
        yScale = isSub ? $$.getSubYScale : $$.getYScale;
    return function (d, i) {
        var y0 = yScale.call($$, d.id)(0),
            offset = areaOffset(d, i) || y0, // offset is for stacked area chart
            posX = x(d), posY = y(d);
        // fix posY not to overflow opposite quadrant
        if (config.axis_rotated) {
            if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; }
        }
        // 1 point that marks the area position
        return [
            [posX, offset],
            [posX, posY - (y0 - offset)],
            [posX, posY - (y0 - offset)], // needed for compatibility
            [posX, offset] // needed for compatibility
        ];
    };
};


ChartInternal.prototype.updateCircle = function (cx, cy) {
    var $$ = this;
    var mainCircle = $$.main.selectAll('.' + CLASS.circles).selectAll('.' + CLASS.circle)
        .data($$.lineOrScatterData.bind($$));
    var mainCircleEnter = mainCircle.enter().append("circle")
        .attr("class", $$.classCircle.bind($$))
        .attr("cx", cx)
        .attr("cy", cy)
        .attr("r", $$.pointR.bind($$))
        .style("fill", $$.color);
    $$.mainCircle = mainCircleEnter.merge(mainCircle)
        .style("opacity", $$.initialOpacityForCircle.bind($$));
    mainCircle.exit()
        .style("opacity", 0);
};
ChartInternal.prototype.redrawCircle = function (cx, cy, withTransition, transition) {
    var $$ = this,
        selectedCircles = $$.main.selectAll('.' + CLASS.selectedCircle);
    return [
        (withTransition ? $$.mainCircle.transition(transition) : $$.mainCircle)
            .style('opacity', this.opacityForCircle.bind($$))
            .style("fill", $$.color)
            .attr("cx", cx)
            .attr("cy", cy),
        (withTransition ? selectedCircles.transition(transition) : selectedCircles)
            .attr("cx", cx)
            .attr("cy", cy)
    ];
};
ChartInternal.prototype.circleX = function (d) {
    return d.x || d.x === 0 ? this.x(d.x) : null;
};
ChartInternal.prototype.updateCircleY = function () {
    var $$ = this, lineIndices, getPoints;
    if ($$.config.data_groups.length > 0) {
        lineIndices = $$.getShapeIndices($$.isLineType),
        getPoints = $$.generateGetLinePoints(lineIndices);
        $$.circleY = function (d, i) {
            return getPoints(d, i)[0][1];
        };
    } else {
        $$.circleY = function (d) {
            return $$.getYScale(d.id)(d.value);
        };
    }
};
ChartInternal.prototype.getCircles = function (i, id) {
    var $$ = this;
    return (id ? $$.main.selectAll('.' + CLASS.circles + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.circle + (isValue(i) ? '-' + i : ''));
};
ChartInternal.prototype.expandCircles = function (i, id, reset) {
    var $$ = this,
        r = $$.pointExpandedR.bind($$);
    if (reset) { $$.unexpandCircles(); }
    $$.getCircles(i, id)
        .classed(CLASS.EXPANDED, true)
        .attr('r', r);
};
ChartInternal.prototype.unexpandCircles = function (i) {
    var $$ = this,
        r = $$.pointR.bind($$);
    $$.getCircles(i)
        .filter(function () { return $$.d3.select(this).classed(CLASS.EXPANDED); })
        .classed(CLASS.EXPANDED, false)
        .attr('r', r);
};
ChartInternal.prototype.pointR = function (d) {
    var $$ = this, config = $$.config;
    return $$.isStepType(d) ? 0 : (isFunction(config.point_r) ? config.point_r(d) : config.point_r);
};
ChartInternal.prototype.pointExpandedR = function (d) {
    var $$ = this, config = $$.config;
    if (config.point_focus_expand_enabled) {
        return isFunction(config.point_focus_expand_r) ? config.point_focus_expand_r(d) : ((config.point_focus_expand_r) ? config.point_focus_expand_r : $$.pointR(d) * 1.75);
    } else {
        return $$.pointR(d);
    }
};
ChartInternal.prototype.pointSelectR = function (d) {
    var $$ = this, config = $$.config;
    return isFunction(config.point_select_r) ? config.point_select_r(d) : ((config.point_select_r) ? config.point_select_r : $$.pointR(d) * 4);
};
ChartInternal.prototype.isWithinCircle = function (that, r) {
    var d3 = this.d3,
        mouse = d3.mouse(that), d3_this = d3.select(that),
        cx = +d3_this.attr("cx"), cy = +d3_this.attr("cy");
    return Math.sqrt(Math.pow(cx - mouse[0], 2) + Math.pow(cy - mouse[1], 2)) < r;
};
ChartInternal.prototype.isWithinStep = function (that, y) {
    return Math.abs(y - this.d3.mouse(that)[1]) < 30;
};
src/grid.js000064400000026534151701472650006640 0ustar00import CLASS from './class';
import { ChartInternal } from './core';
import { isValue } from './util';

ChartInternal.prototype.initGrid = function () {
    var $$ = this, config = $$.config, d3 = $$.d3;
    $$.grid = $$.main.append('g')
        .attr("clip-path", $$.clipPathForGrid)
        .attr('class', CLASS.grid);
    if (config.grid_x_show) {
        $$.grid.append("g").attr("class", CLASS.xgrids);
    }
    if (config.grid_y_show) {
        $$.grid.append('g').attr('class', CLASS.ygrids);
    }
    if (config.grid_focus_show) {
        $$.grid.append('g')
            .attr("class", CLASS.xgridFocus)
            .append('line')
            .attr('class', CLASS.xgridFocus);
    }
    $$.xgrid = d3.selectAll([]);
    if (!config.grid_lines_front) { $$.initGridLines(); }
};
ChartInternal.prototype.initGridLines = function () {
    var $$ = this, d3 = $$.d3;
    $$.gridLines = $$.main.append('g')
        .attr("clip-path", $$.clipPathForGrid)
        .attr('class', CLASS.grid + ' ' + CLASS.gridLines);
    $$.gridLines.append('g').attr("class", CLASS.xgridLines);
    $$.gridLines.append('g').attr('class', CLASS.ygridLines);
    $$.xgridLines = d3.selectAll([]);
};
ChartInternal.prototype.updateXGrid = function (withoutUpdate) {
    var $$ = this, config = $$.config, d3 = $$.d3,
        xgridData = $$.generateGridData(config.grid_x_type, $$.x),
        tickOffset = $$.isCategorized() ? $$.xAxis.tickOffset() : 0;

    $$.xgridAttr = config.axis_rotated ? {
        'x1': 0,
        'x2': $$.width,
        'y1': function (d) { return $$.x(d) - tickOffset; },
        'y2': function (d) { return $$.x(d) - tickOffset; }
    } : {
        'x1': function (d) { return $$.x(d) + tickOffset; },
        'x2': function (d) { return $$.x(d) + tickOffset; },
        'y1': 0,
        'y2': $$.height
    };
    $$.xgridAttr.opacity = function () {
        var pos = +d3.select(this).attr(config.axis_rotated ? 'y1' : 'x1');
        return pos === (config.axis_rotated ? $$.height : 0) ? 0 : 1;
    };

    var xgrid = $$.main.select('.' + CLASS.xgrids).selectAll('.' + CLASS.xgrid)
        .data(xgridData);
    var xgridEnter = xgrid.enter().append('line')
        .attr("class", CLASS.xgrid)
        .attr('x1', $$.xgridAttr.x1)
        .attr('x2', $$.xgridAttr.x2)
        .attr('y1', $$.xgridAttr.y1)
        .attr('y2', $$.xgridAttr.y2)
        .style("opacity", 0);
    $$.xgrid = xgridEnter.merge(xgrid);
    if (!withoutUpdate) {
        $$.xgrid
            .attr('x1', $$.xgridAttr.x1)
            .attr('x2', $$.xgridAttr.x2)
            .attr('y1', $$.xgridAttr.y1)
            .attr('y2', $$.xgridAttr.y2)
            .style("opacity", $$.xgridAttr.opacity);
    }
    xgrid.exit().remove();
};

ChartInternal.prototype.updateYGrid = function () {
    var $$ = this, config = $$.config,
        gridValues = $$.yAxis.tickValues() || $$.y.ticks(config.grid_y_ticks);
    var ygrid = $$.main.select('.' + CLASS.ygrids).selectAll('.' + CLASS.ygrid)
        .data(gridValues);
    var ygridEnter = ygrid.enter().append('line')
        // TODO: x1, x2, y1, y2, opacity need to be set here maybe
        .attr('class', CLASS.ygrid);
    $$.ygrid = ygridEnter.merge(ygrid);
    $$.ygrid
        .attr("x1", config.axis_rotated ? $$.y : 0)
        .attr("x2", config.axis_rotated ? $$.y : $$.width)
        .attr("y1", config.axis_rotated ? 0 : $$.y)
        .attr("y2", config.axis_rotated ? $$.height : $$.y);
    ygrid.exit().remove();
    $$.smoothLines($$.ygrid, 'grid');
};

ChartInternal.prototype.gridTextAnchor = function (d) {
    return d.position ? d.position : "end";
};
ChartInternal.prototype.gridTextDx = function (d) {
    return d.position === 'start' ? 4 : d.position === 'middle' ? 0 : -4;
};
ChartInternal.prototype.xGridTextX = function (d) {
    return d.position === 'start' ? -this.height : d.position === 'middle' ? -this.height / 2 : 0;
};
ChartInternal.prototype.yGridTextX = function (d) {
    return d.position === 'start' ? 0 : d.position === 'middle' ? this.width / 2 : this.width;
};
ChartInternal.prototype.updateGrid = function (duration) {
    var $$ = this, main = $$.main, config = $$.config,
        xgridLine, xgridLineEnter, ygridLine, ygridLineEnter,
        xv = $$.xv.bind($$), yv = $$.yv.bind($$),
        xGridTextX = $$.xGridTextX.bind($$), yGridTextX = $$.yGridTextX.bind($$);

    // hide if arc type
    $$.grid.style('visibility', $$.hasArcType() ? 'hidden' : 'visible');

    main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden");
    if (config.grid_x_show) {
        $$.updateXGrid();
    }
    xgridLine = main.select('.' + CLASS.xgridLines).selectAll('.' + CLASS.xgridLine)
        .data(config.grid_x_lines);
    // enter
    xgridLineEnter = xgridLine.enter().append('g')
        .attr("class", function (d) { return CLASS.xgridLine + (d['class'] ? ' ' + d['class'] : ''); });
    xgridLineEnter.append('line')
        .attr("x1", config.axis_rotated ? 0 : xv)
        .attr("x2", config.axis_rotated ? $$.width : xv)
        .attr("y1", config.axis_rotated ? xv : 0)
        .attr("y2", config.axis_rotated ? xv : $$.height)
        .style("opacity", 0);
    xgridLineEnter.append('text')
        .attr("text-anchor", $$.gridTextAnchor)
        .attr("transform", config.axis_rotated ? "" : "rotate(-90)")
        .attr("x", config.axis_rotated ? yGridTextX : xGridTextX)
        .attr("y", xv)
        .attr('dx', $$.gridTextDx)
        .attr('dy', -5)
        .style("opacity", 0);
    // udpate
    $$.xgridLines = xgridLineEnter.merge(xgridLine);
    // done in d3.transition() of the end of this function
    // exit
    xgridLine.exit().transition().duration(duration)
        .style("opacity", 0)
        .remove();

    // Y-Grid
    if (config.grid_y_show) {
        $$.updateYGrid();
    }
    ygridLine = main.select('.' + CLASS.ygridLines).selectAll('.' + CLASS.ygridLine)
        .data(config.grid_y_lines);
    // enter
    ygridLineEnter = ygridLine.enter().append('g')
        .attr("class", function (d) { return CLASS.ygridLine + (d['class'] ? ' ' + d['class'] : ''); });
    ygridLineEnter.append('line')
        .attr("x1", config.axis_rotated ? yv : 0)
        .attr("x2", config.axis_rotated ? yv : $$.width)
        .attr("y1", config.axis_rotated ? 0 : yv)
        .attr("y2", config.axis_rotated ? $$.height : yv)
        .style("opacity", 0);
    ygridLineEnter.append('text')
        .attr("text-anchor", $$.gridTextAnchor)
        .attr("transform", config.axis_rotated ? "rotate(-90)" : "")
        .attr("x", config.axis_rotated ? xGridTextX : yGridTextX)
        .attr("y", yv)
        .attr('dx', $$.gridTextDx)
        .attr('dy', -5)
        .style("opacity", 0);
    // update
    $$.ygridLines = ygridLineEnter.merge(ygridLine);
    $$.ygridLines.select('line')
      .transition().duration(duration)
        .attr("x1", config.axis_rotated ? yv : 0)
        .attr("x2", config.axis_rotated ? yv : $$.width)
        .attr("y1", config.axis_rotated ? 0 : yv)
        .attr("y2", config.axis_rotated ? $$.height : yv)
        .style("opacity", 1);
    $$.ygridLines.select('text')
      .transition().duration(duration)
        .attr("x", config.axis_rotated ? $$.xGridTextX.bind($$) : $$.yGridTextX.bind($$))
        .attr("y", yv)
        .text(function (d) { return d.text; })
        .style("opacity", 1);
    // exit
    ygridLine.exit().transition().duration(duration)
        .style("opacity", 0)
        .remove();
};
ChartInternal.prototype.redrawGrid = function (withTransition, transition) {
    var $$ = this, config = $$.config, xv = $$.xv.bind($$),
        lines = $$.xgridLines.select('line'),
        texts = $$.xgridLines.select('text');
    return [
        (withTransition ? lines.transition(transition) : lines)
            .attr("x1", config.axis_rotated ? 0 : xv)
            .attr("x2", config.axis_rotated ? $$.width : xv)
            .attr("y1", config.axis_rotated ? xv : 0)
            .attr("y2", config.axis_rotated ? xv : $$.height)
            .style("opacity", 1),
        (withTransition ? texts.transition(transition) : texts)
            .attr("x", config.axis_rotated ? $$.yGridTextX.bind($$) : $$.xGridTextX.bind($$))
            .attr("y", xv)
            .text(function (d) { return d.text; })
            .style("opacity", 1)
    ];
};
ChartInternal.prototype.showXGridFocus = function (selectedData) {
    var $$ = this, config = $$.config,
        dataToShow = selectedData.filter(function (d) { return d && isValue(d.value); }),
        focusEl = $$.main.selectAll('line.' + CLASS.xgridFocus),
        xx = $$.xx.bind($$);
    if (! config.tooltip_show) { return; }
    // Hide when scatter plot exists
    if ($$.hasType('scatter') || $$.hasArcType()) { return; }
    focusEl
        .style("visibility", "visible")
        .data([dataToShow[0]])
        .attr(config.axis_rotated ? 'y1' : 'x1', xx)
        .attr(config.axis_rotated ? 'y2' : 'x2', xx);
    $$.smoothLines(focusEl, 'grid');
};
ChartInternal.prototype.hideXGridFocus = function () {
    this.main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden");
};
ChartInternal.prototype.updateXgridFocus = function () {
    var $$ = this, config = $$.config;
    $$.main.select('line.' + CLASS.xgridFocus)
        .attr("x1", config.axis_rotated ? 0 : -10)
        .attr("x2", config.axis_rotated ? $$.width : -10)
        .attr("y1", config.axis_rotated ? -10 : 0)
        .attr("y2", config.axis_rotated ? -10 : $$.height);
};
ChartInternal.prototype.generateGridData = function (type, scale) {
    var $$ = this,
        gridData = [], xDomain, firstYear, lastYear, i,
        tickNum = $$.main.select("." + CLASS.axisX).selectAll('.tick').size();
    if (type === 'year') {
        xDomain = $$.getXDomain();
        firstYear = xDomain[0].getFullYear();
        lastYear = xDomain[1].getFullYear();
        for (i = firstYear; i <= lastYear; i++) {
            gridData.push(new Date(i + '-01-01 00:00:00'));
        }
    } else {
        gridData = scale.ticks(10);
        if (gridData.length > tickNum) { // use only int
            gridData = gridData.filter(function (d) { return ("" + d).indexOf('.') < 0; });
        }
    }
    return gridData;
};
ChartInternal.prototype.getGridFilterToRemove = function (params) {
    return params ? function (line) {
        var found = false;
        [].concat(params).forEach(function (param) {
            if ((('value' in param && line.value === param.value) || ('class' in param && line['class'] === param['class']))) {
                found = true;
            }
        });
        return found;
    } : function () { return true; };
};
ChartInternal.prototype.removeGridLines = function (params, forX) {
    var $$ = this, config = $$.config,
        toRemove = $$.getGridFilterToRemove(params),
        toShow = function (line) { return !toRemove(line); },
        classLines = forX ? CLASS.xgridLines : CLASS.ygridLines,
        classLine = forX ? CLASS.xgridLine : CLASS.ygridLine;
    $$.main.select('.' + classLines).selectAll('.' + classLine).filter(toRemove)
        .transition().duration(config.transition_duration)
        .style('opacity', 0).remove();
    if (forX) {
        config.grid_x_lines = config.grid_x_lines.filter(toShow);
    } else {
        config.grid_y_lines = config.grid_y_lines.filter(toShow);
    }
};
src/api.flow.js000064400000026460151701472650007430 0ustar00import CLASS from './class';
import { Chart, ChartInternal } from './core';
import { isValue, isDefined, diffDomain } from './util';

Chart.prototype.flow = function (args) {
    var $$ = this.internal,
        targets, data, notfoundIds = [], orgDataCount = $$.getMaxDataCount(),
        dataCount, domain, baseTarget, baseValue, length = 0, tail = 0, diff, to;

    if (args.json) {
        data = $$.convertJsonToData(args.json, args.keys);
    }
    else if (args.rows) {
        data = $$.convertRowsToData(args.rows);
    }
    else if (args.columns) {
        data = $$.convertColumnsToData(args.columns);
    }
    else {
        return;
    }
    targets = $$.convertDataToTargets(data, true);

    // Update/Add data
    $$.data.targets.forEach(function (t) {
        var found = false, i, j;
        for (i = 0; i < targets.length; i++) {
            if (t.id === targets[i].id) {
                found = true;

                if (t.values[t.values.length - 1]) {
                    tail = t.values[t.values.length - 1].index + 1;
                }
                length = targets[i].values.length;

                for (j = 0; j < length; j++) {
                    targets[i].values[j].index = tail + j;
                    if (!$$.isTimeSeries()) {
                        targets[i].values[j].x = tail + j;
                    }
                }
                t.values = t.values.concat(targets[i].values);

                targets.splice(i, 1);
                break;
            }
        }
        if (!found) { notfoundIds.push(t.id); }
    });

    // Append null for not found targets
    $$.data.targets.forEach(function (t) {
        var i, j;
        for (i = 0; i < notfoundIds.length; i++) {
            if (t.id === notfoundIds[i]) {
                tail = t.values[t.values.length - 1].index + 1;
                for (j = 0; j < length; j++) {
                    t.values.push({
                        id: t.id,
                        index: tail + j,
                        x: $$.isTimeSeries() ? $$.getOtherTargetX(tail + j) : tail + j,
                        value: null
                    });
                }
            }
        }
    });

    // Generate null values for new target
    if ($$.data.targets.length) {
        targets.forEach(function (t) {
            var i, missing = [];
            for (i = $$.data.targets[0].values[0].index; i < tail; i++) {
                missing.push({
                    id: t.id,
                    index: i,
                    x: $$.isTimeSeries() ? $$.getOtherTargetX(i) : i,
                    value: null
                });
            }
            t.values.forEach(function (v) {
                v.index += tail;
                if (!$$.isTimeSeries()) {
                    v.x += tail;
                }
            });
            t.values = missing.concat(t.values);
        });
    }
    $$.data.targets = $$.data.targets.concat(targets); // add remained

    // check data count because behavior needs to change when it's only one
    dataCount = $$.getMaxDataCount();
    baseTarget = $$.data.targets[0];
    baseValue = baseTarget.values[0];

    // Update length to flow if needed
    if (isDefined(args.to)) {
        length = 0;
        to = $$.isTimeSeries() ? $$.parseDate(args.to) : args.to;
        baseTarget.values.forEach(function (v) {
            if (v.x < to) { length++; }
        });
    } else if (isDefined(args.length)) {
        length = args.length;
    }

    // If only one data, update the domain to flow from left edge of the chart
    if (!orgDataCount) {
        if ($$.isTimeSeries()) {
            if (baseTarget.values.length > 1) {
                diff = baseTarget.values[baseTarget.values.length - 1].x - baseValue.x;
            } else {
                diff = baseValue.x - $$.getXDomain($$.data.targets)[0];
            }
        } else {
            diff = 1;
        }
        domain = [baseValue.x - diff, baseValue.x];
        $$.updateXDomain(null, true, true, false, domain);
    } else if (orgDataCount === 1) {
        if ($$.isTimeSeries()) {
            diff = (baseTarget.values[baseTarget.values.length - 1].x - baseValue.x) / 2;
            domain = [new Date(+baseValue.x - diff), new Date(+baseValue.x + diff)];
            $$.updateXDomain(null, true, true, false, domain);
        }
    }

    // Set targets
    $$.updateTargets($$.data.targets);

    // Redraw with new targets
    $$.redraw({
        flow: {
            index: baseValue.index,
            length: length,
            duration: isValue(args.duration) ? args.duration : $$.config.transition_duration,
            done: args.done,
            orgDataCount: orgDataCount,
        },
        withLegend: true,
        withTransition: orgDataCount > 1,
        withTrimXDomain: false,
        withUpdateXAxis: true,
    });
};

ChartInternal.prototype.generateFlow = function (args) {
    var $$ = this, config = $$.config, d3 = $$.d3;

    return function () {
        var targets = args.targets,
            flow = args.flow,
            drawBar = args.drawBar,
            drawLine = args.drawLine,
            drawArea = args.drawArea,
            cx = args.cx,
            cy = args.cy,
            xv = args.xv,
            xForText = args.xForText,
            yForText = args.yForText,
            duration = args.duration;

        var translateX, scaleX = 1, transform,
            flowIndex = flow.index,
            flowLength = flow.length,
            flowStart = $$.getValueOnIndex($$.data.targets[0].values, flowIndex),
            flowEnd = $$.getValueOnIndex($$.data.targets[0].values, flowIndex + flowLength),
            orgDomain = $$.x.domain(), domain,
            durationForFlow = flow.duration || duration,
            done = flow.done || function () {},
            wait = $$.generateWait();

        var xgrid,
            xgridLines,
            mainRegion,
            mainText,
            mainBar,
            mainLine,
            mainArea,
            mainCircle;

        // set flag
        $$.flowing = true;

        // remove head data after rendered
        $$.data.targets.forEach(function (d) {
            d.values.splice(0, flowLength);
        });

        // update x domain to generate axis elements for flow
        domain = $$.updateXDomain(targets, true, true);
        // update elements related to x scale
        if ($$.updateXGrid) { $$.updateXGrid(true); }

        xgrid = $$.xgrid || d3.selectAll([]); // xgrid needs to be obtained after updateXGrid
        xgridLines = $$.xgridLines || d3.selectAll([]);
        mainRegion = $$.mainRegion || d3.selectAll([]);
        mainText = $$.mainText || d3.selectAll([]);
        mainBar = $$.mainBar || d3.selectAll([]);
        mainLine = $$.mainLine || d3.selectAll([]);
        mainArea = $$.mainArea || d3.selectAll([]);
        mainCircle = $$.mainCircle || d3.selectAll([]);

        // generate transform to flow
        if (!flow.orgDataCount) { // if empty
            if ($$.data.targets[0].values.length !== 1) {
                translateX = $$.x(orgDomain[0]) - $$.x(domain[0]);
            } else {
                if ($$.isTimeSeries()) {
                    flowStart = $$.getValueOnIndex($$.data.targets[0].values, 0);
                    flowEnd = $$.getValueOnIndex($$.data.targets[0].values, $$.data.targets[0].values.length - 1);
                    translateX = $$.x(flowStart.x) - $$.x(flowEnd.x);
                } else {
                    translateX = diffDomain(domain) / 2;
                }
            }
        } else if (flow.orgDataCount === 1 || (flowStart && flowStart.x) === (flowEnd && flowEnd.x)) {
            translateX = $$.x(orgDomain[0]) - $$.x(domain[0]);
        } else {
            if ($$.isTimeSeries()) {
                translateX = ($$.x(orgDomain[0]) - $$.x(domain[0]));
            } else {
                translateX = ($$.x(flowStart.x) - $$.x(flowEnd.x));
            }
        }
        scaleX = (diffDomain(orgDomain) / diffDomain(domain));
        transform = 'translate(' + translateX + ',0) scale(' + scaleX + ',1)';

        $$.hideXGridFocus();

        var flowTransition = d3.transition().ease(d3.easeLinear).duration(durationForFlow);
        wait.add($$.xAxis($$.axes.x, flowTransition));
        wait.add(mainBar.transition(flowTransition).attr('transform', transform));
        wait.add(mainLine.transition(flowTransition).attr('transform', transform));
        wait.add(mainArea.transition(flowTransition).attr('transform', transform));
        wait.add(mainCircle.transition(flowTransition).attr('transform', transform));
        wait.add(mainText.transition(flowTransition).attr('transform', transform));
        wait.add(mainRegion.filter($$.isRegionOnX).transition(flowTransition).attr('transform', transform));
        wait.add(xgrid.transition(flowTransition).attr('transform', transform));
        wait.add(xgridLines.transition(flowTransition).attr('transform', transform));
        wait(function () {
            var i, shapes = [], texts = [];

            // remove flowed elements
            if (flowLength) {
                for (i = 0; i < flowLength; i++) {
                    shapes.push('.' + CLASS.shape + '-' + (flowIndex + i));
                    texts.push('.' + CLASS.text + '-' + (flowIndex + i));
                }
                $$.svg.selectAll('.' + CLASS.shapes).selectAll(shapes).remove();
                $$.svg.selectAll('.' + CLASS.texts).selectAll(texts).remove();
                $$.svg.select('.' + CLASS.xgrid).remove();
            }

            // draw again for removing flowed elements and reverting attr
            xgrid
                .attr('transform', null)
                .attr('x1', $$.xgridAttr.x1)
                .attr('x2', $$.xgridAttr.x2)
                .attr('y1', $$.xgridAttr.y1)
                .attr('y2', $$.xgridAttr.y2)
                .style("opacity", $$.xgridAttr.opacity);
            xgridLines
                .attr('transform', null);
            xgridLines.select('line')
                .attr("x1", config.axis_rotated ? 0 : xv)
                .attr("x2", config.axis_rotated ? $$.width : xv);
            xgridLines.select('text')
                .attr("x", config.axis_rotated ? $$.width : 0)
                .attr("y", xv);
            mainBar
                .attr('transform', null)
                .attr("d", drawBar);
            mainLine
                .attr('transform', null)
                .attr("d", drawLine);
            mainArea
                .attr('transform', null)
                .attr("d", drawArea);
            mainCircle
                .attr('transform', null)
                .attr("cx", cx)
                .attr("cy", cy);
            mainText
                .attr('transform', null)
                .attr('x', xForText)
                .attr('y', yForText)
                .style('fill-opacity', $$.opacityForText.bind($$));
            mainRegion
                .attr('transform', null);
            mainRegion.filter($$.isRegionOnX)
                .attr("x", $$.regionX.bind($$))
                .attr("width", $$.regionWidth.bind($$));

            // callback for end of flow
            done();

            $$.flowing = false;
        });
    };
};
src/scale.js000064400000007561151701472650007001 0ustar00import { ChartInternal } from './core';

ChartInternal.prototype.getScale = function (min, max, forTimeseries) {
    return (forTimeseries ? this.d3.scaleTime() : this.d3.scaleLinear()).range([min, max]);
};
ChartInternal.prototype.getX = function (min, max, domain, offset) {
    var $$ = this,
        scale = $$.getScale(min, max, $$.isTimeSeries()),
        _scale = domain ? scale.domain(domain) : scale, key;
    // Define customized scale if categorized axis
    if ($$.isCategorized()) {
        offset = offset || function () { return 0; };
        scale = function (d, raw) {
            var v = _scale(d) + offset(d);
            return raw ? v : Math.ceil(v);
        };
    } else {
        scale = function (d, raw) {
            var v = _scale(d);
            return raw ? v : Math.ceil(v);
        };
    }
    // define functions
    for (key in _scale) {
        scale[key] = _scale[key];
    }
    scale.orgDomain = function () {
        return _scale.domain();
    };
    // define custom domain() for categorized axis
    if ($$.isCategorized()) {
        scale.domain = function (domain) {
            if (!arguments.length) {
                domain = this.orgDomain();
                return [domain[0], domain[1] + 1];
            }
            _scale.domain(domain);
            return scale;
        };
    }
    return scale;
};
ChartInternal.prototype.getY = function (min, max, domain) {
    var scale = this.getScale(min, max, this.isTimeSeriesY());
    if (domain) { scale.domain(domain); }
    return scale;
};
ChartInternal.prototype.getYScale = function (id) {
    return this.axis.getId(id) === 'y2' ? this.y2 : this.y;
};
ChartInternal.prototype.getSubYScale = function (id) {
    return this.axis.getId(id) === 'y2' ? this.subY2 : this.subY;
};
ChartInternal.prototype.updateScales = function () {
    var $$ = this, config = $$.config,
        forInit = !$$.x;
    // update edges
    $$.xMin = config.axis_rotated ? 1 : 0;
    $$.xMax = config.axis_rotated ? $$.height : $$.width;
    $$.yMin = config.axis_rotated ? 0 : $$.height;
    $$.yMax = config.axis_rotated ? $$.width : 1;
    $$.subXMin = $$.xMin;
    $$.subXMax = $$.xMax;
    $$.subYMin = config.axis_rotated ? 0 : $$.height2;
    $$.subYMax = config.axis_rotated ? $$.width2 : 1;
    // update scales
    $$.x = $$.getX($$.xMin, $$.xMax, forInit ? undefined : $$.x.orgDomain(), function () { return $$.xAxis.tickOffset(); });
    $$.y = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y_default : $$.y.domain());
    $$.y2 = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y2_default : $$.y2.domain());
    $$.subX = $$.getX($$.xMin, $$.xMax, $$.orgXDomain, function (d) { return d % 1 ? 0 : $$.subXAxis.tickOffset(); });
    $$.subY = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y_default : $$.subY.domain());
    $$.subY2 = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y2_default : $$.subY2.domain());
    // update axes
    $$.xAxisTickFormat = $$.axis.getXAxisTickFormat();
    $$.xAxisTickValues = $$.axis.getXAxisTickValues();
    $$.yAxisTickValues = $$.axis.getYAxisTickValues();
    $$.y2AxisTickValues = $$.axis.getY2AxisTickValues();

    $$.xAxis = $$.axis.getXAxis($$.x, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer);
    $$.subXAxis = $$.axis.getXAxis($$.subX, $$.subXOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer);
    $$.yAxis = $$.axis.getYAxis($$.y, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues, config.axis_y_tick_outer);
    $$.y2Axis = $$.axis.getYAxis($$.y2, $$.y2Orient, config.axis_y2_tick_format, $$.y2AxisTickValues, config.axis_y2_tick_outer);

    // Set initialized scales to brush and zoom
    if (!forInit) {
        if ($$.brush) { $$.brush.updateScale($$.subX); }
    }
    // update for arc
    if ($$.updateArc) { $$.updateArc(); }
};
src/selection.js000064400000007157151701472650007700 0ustar00import CLASS from './class';
import { ChartInternal } from './core';

ChartInternal.prototype.selectPoint = function (target, d, i) {
    var $$ = this, config = $$.config,
        cx = (config.axis_rotated ? $$.circleY : $$.circleX).bind($$),
        cy = (config.axis_rotated ? $$.circleX : $$.circleY).bind($$),
        r = $$.pointSelectR.bind($$);
    config.data_onselected.call($$.api, d, target.node());
    // add selected-circle on low layer g
    $$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i)
        .data([d])
        .enter().append('circle')
        .attr("class", function () { return $$.generateClass(CLASS.selectedCircle, i); })
        .attr("cx", cx)
        .attr("cy", cy)
        .attr("stroke", function () { return $$.color(d); })
        .attr("r", function (d) { return $$.pointSelectR(d) * 1.4; })
        .transition().duration(100)
        .attr("r", r);
};
ChartInternal.prototype.unselectPoint = function (target, d, i) {
    var $$ = this;
    $$.config.data_onunselected.call($$.api, d, target.node());
    // remove selected-circle from low layer g
    $$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i)
        .transition().duration(100).attr('r', 0)
        .remove();
};
ChartInternal.prototype.togglePoint = function (selected, target, d, i) {
    selected ? this.selectPoint(target, d, i) : this.unselectPoint(target, d, i);
};
ChartInternal.prototype.selectPath = function (target, d) {
    var $$ = this;
    $$.config.data_onselected.call($$, d, target.node());
    if ($$.config.interaction_brighten) {
        target.transition().duration(100)
            .style("fill", function () { return $$.d3.rgb($$.color(d)).brighter(0.75); });
    }
};
ChartInternal.prototype.unselectPath = function (target, d) {
    var $$ = this;
    $$.config.data_onunselected.call($$, d, target.node());
    if ($$.config.interaction_brighten) {
        target.transition().duration(100)
            .style("fill", function () { return $$.color(d); });
    }
};
ChartInternal.prototype.togglePath = function (selected, target, d, i) {
    selected ? this.selectPath(target, d, i) : this.unselectPath(target, d, i);
};
ChartInternal.prototype.getToggle = function (that, d) {
    var $$ = this, toggle;
    if (that.nodeName === 'circle') {
        if ($$.isStepType(d)) {
            // circle is hidden in step chart, so treat as within the click area
            toggle = function () {}; // TODO: how to select step chart?
        } else {
            toggle = $$.togglePoint;
        }
    }
    else if (that.nodeName === 'path') {
        toggle = $$.togglePath;
    }
    return toggle;
};
ChartInternal.prototype.toggleShape = function (that, d, i) {
    var $$ = this, d3 = $$.d3, config = $$.config,
        shape = d3.select(that), isSelected = shape.classed(CLASS.SELECTED),
        toggle = $$.getToggle(that, d).bind($$);

    if (config.data_selection_enabled && config.data_selection_isselectable(d)) {
        if (!config.data_selection_multiple) {
            $$.main.selectAll('.' + CLASS.shapes + (config.data_selection_grouped ? $$.getTargetSelectorSuffix(d.id) : "")).selectAll('.' + CLASS.shape).each(function (d, i) {
                var shape = d3.select(this);
                if (shape.classed(CLASS.SELECTED)) { toggle(false, shape.classed(CLASS.SELECTED, false), d, i); }
            });
        }
        shape.classed(CLASS.SELECTED, !isSelected);
        toggle(!isSelected, shape, d, i);
    }
};
src/axis.js000064400000044245151701472650006656 0ustar00import CLASS from './class';
import {
    isValue,
    isFunction,
    isString,
    isEmpty
} from './util';
import {
    AxisInternal
} from './axis-internal';

export default 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(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) {
    var $$ = this.owner,
        config = $$.config,
        axisParams = {
            withOuterTick: withOuterTick,
            withoutTransition: withoutTransition,
            tickTextRotate: withoutRotateTickText ? 0 : config.axis_y_tick_rotate
        },
        axis = new this.internal(this, axisParams).axis.scale(scale).orient(orient).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" : config.axis_x_height ? config.axis_x_height - 10 : "3em";
    }
};
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,
        config = $$.config,
        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(scale, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues, false, true, true);
        } else if (id === 'y2') {
            scale = $$.y2.copy().domain($$.getYDomain(targetsToShow, 'y2'));
            axis = this.getYAxis(scale, $$.y2Orient, config.axis_y2_tick_format, $$.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 = this.getBoundingClientRect();
                    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);
};
src/data.js000064400000031640151701472650006616 0ustar00import CLASS from './class';
import {
    ChartInternal
} from './core';
import {
    isValue,
    isFunction,
    isArray,
    notEmpty,
    hasValue
} from './util';

ChartInternal.prototype.isX = function (key) {
    var $$ = this,
        config = $$.config;
    return (config.data_x && key === config.data_x) || (notEmpty(config.data_xs) && hasValue(config.data_xs, key));
};
ChartInternal.prototype.isNotX = function (key) {
    return !this.isX(key);
};
ChartInternal.prototype.getXKey = function (id) {
    var $$ = this,
        config = $$.config;
    return config.data_x ? config.data_x : notEmpty(config.data_xs) ? config.data_xs[id] : null;
};
ChartInternal.prototype.getXValuesOfXKey = function (key, targets) {
    var $$ = this,
        xValues, ids = targets && notEmpty(targets) ? $$.mapToIds(targets) : [];
    ids.forEach(function (id) {
        if ($$.getXKey(id) === key) {
            xValues = $$.data.xs[id];
        }
    });
    return xValues;
};
ChartInternal.prototype.getXValue = function (id, i) {
    var $$ = this;
    return id in $$.data.xs && $$.data.xs[id] && isValue($$.data.xs[id][i]) ? $$.data.xs[id][i] : i;
};
ChartInternal.prototype.getOtherTargetXs = function () {
    var $$ = this,
        idsForX = Object.keys($$.data.xs);
    return idsForX.length ? $$.data.xs[idsForX[0]] : null;
};
ChartInternal.prototype.getOtherTargetX = function (index) {
    var xs = this.getOtherTargetXs();
    return xs && index < xs.length ? xs[index] : null;
};
ChartInternal.prototype.addXs = function (xs) {
    var $$ = this;
    Object.keys(xs).forEach(function (id) {
        $$.config.data_xs[id] = xs[id];
    });
};
ChartInternal.prototype.addName = function (data) {
    var $$ = this,
        name;
    if (data) {
        name = $$.config.data_names[data.id];
        data.name = name !== undefined ? name : data.id;
    }
    return data;
};
ChartInternal.prototype.getValueOnIndex = function (values, index) {
    var valueOnIndex = values.filter(function (v) {
        return v.index === index;
    });
    return valueOnIndex.length ? valueOnIndex[0] : null;
};
ChartInternal.prototype.updateTargetX = function (targets, x) {
    var $$ = this;
    targets.forEach(function (t) {
        t.values.forEach(function (v, i) {
            v.x = $$.generateTargetX(x[i], t.id, i);
        });
        $$.data.xs[t.id] = x;
    });
};
ChartInternal.prototype.updateTargetXs = function (targets, xs) {
    var $$ = this;
    targets.forEach(function (t) {
        if (xs[t.id]) {
            $$.updateTargetX([t], xs[t.id]);
        }
    });
};
ChartInternal.prototype.generateTargetX = function (rawX, id, index) {
    var $$ = this,
        x;
    if ($$.isTimeSeries()) {
        x = rawX ? $$.parseDate(rawX) : $$.parseDate($$.getXValue(id, index));
    } else if ($$.isCustomX() && !$$.isCategorized()) {
        x = isValue(rawX) ? +rawX : $$.getXValue(id, index);
    } else {
        x = index;
    }
    return x;
};
ChartInternal.prototype.cloneTarget = function (target) {
    return {
        id: target.id,
        id_org: target.id_org,
        values: target.values.map(function (d) {
            return {
                x: d.x,
                value: d.value,
                id: d.id
            };
        })
    };
};
ChartInternal.prototype.getMaxDataCount = function () {
    var $$ = this;
    return $$.d3.max($$.data.targets, function (t) {
        return t.values.length;
    });
};
ChartInternal.prototype.mapToIds = function (targets) {
    return targets.map(function (d) {
        return d.id;
    });
};
ChartInternal.prototype.mapToTargetIds = function (ids) {
    var $$ = this;
    return ids ? [].concat(ids) : $$.mapToIds($$.data.targets);
};
ChartInternal.prototype.hasTarget = function (targets, id) {
    var ids = this.mapToIds(targets),
        i;
    for (i = 0; i < ids.length; i++) {
        if (ids[i] === id) {
            return true;
        }
    }
    return false;
};
ChartInternal.prototype.isTargetToShow = function (targetId) {
    return this.hiddenTargetIds.indexOf(targetId) < 0;
};
ChartInternal.prototype.isLegendToShow = function (targetId) {
    return this.hiddenLegendIds.indexOf(targetId) < 0;
};
ChartInternal.prototype.filterTargetsToShow = function (targets) {
    var $$ = this;
    return targets.filter(function (t) {
        return $$.isTargetToShow(t.id);
    });
};
ChartInternal.prototype.mapTargetsToUniqueXs = function (targets) {
    var $$ = this;
    var xs = $$.d3.set($$.d3.merge(targets.map(function (t) {
        return t.values.map(function (v) {
            return +v.x;
        });
    }))).values();
    xs = $$.isTimeSeries() ? xs.map(function (x) {
        return new Date(+x);
    }) : xs.map(function (x) {
        return +x;
    });
    return xs.sort(function (a, b) {
        return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
    });
};
ChartInternal.prototype.addHiddenTargetIds = function (targetIds) {
    targetIds = (targetIds instanceof Array) ? targetIds : new Array(targetIds);
    for (var i = 0; i < targetIds.length; i++) {
        if (this.hiddenTargetIds.indexOf(targetIds[i]) < 0) {
            this.hiddenTargetIds = this.hiddenTargetIds.concat(targetIds[i]);
        }
    }
};
ChartInternal.prototype.removeHiddenTargetIds = function (targetIds) {
    this.hiddenTargetIds = this.hiddenTargetIds.filter(function (id) {
        return targetIds.indexOf(id) < 0;
    });
};
ChartInternal.prototype.addHiddenLegendIds = function (targetIds) {
    targetIds = (targetIds instanceof Array) ? targetIds : new Array(targetIds);
    for (var i = 0; i < targetIds.length; i++) {
        if (this.hiddenLegendIds.indexOf(targetIds[i]) < 0) {
            this.hiddenLegendIds = this.hiddenLegendIds.concat(targetIds[i]);
        }
    }
};
ChartInternal.prototype.removeHiddenLegendIds = function (targetIds) {
    this.hiddenLegendIds = this.hiddenLegendIds.filter(function (id) {
        return targetIds.indexOf(id) < 0;
    });
};
ChartInternal.prototype.getValuesAsIdKeyed = function (targets) {
    var ys = {};
    targets.forEach(function (t) {
        ys[t.id] = [];
        t.values.forEach(function (v) {
            ys[t.id].push(v.value);
        });
    });
    return ys;
};
ChartInternal.prototype.checkValueInTargets = function (targets, checker) {
    var ids = Object.keys(targets),
        i, j, values;
    for (i = 0; i < ids.length; i++) {
        values = targets[ids[i]].values;
        for (j = 0; j < values.length; j++) {
            if (checker(values[j].value)) {
                return true;
            }
        }
    }
    return false;
};
ChartInternal.prototype.hasNegativeValueInTargets = function (targets) {
    return this.checkValueInTargets(targets, function (v) {
        return v < 0;
    });
};
ChartInternal.prototype.hasPositiveValueInTargets = function (targets) {
    return this.checkValueInTargets(targets, function (v) {
        return v > 0;
    });
};
ChartInternal.prototype.isOrderDesc = function () {
    var config = this.config;
    return typeof (config.data_order) === 'string' && config.data_order.toLowerCase() === 'desc';
};
ChartInternal.prototype.isOrderAsc = function () {
    var config = this.config;
    return typeof (config.data_order) === 'string' && config.data_order.toLowerCase() === 'asc';
};
ChartInternal.prototype.getOrderFunction = function () {
    var $$ = this,
        config = $$.config,
        orderAsc = $$.isOrderAsc(),
        orderDesc = $$.isOrderDesc();
    if (orderAsc || orderDesc) {
        var reducer = function (p, c) {
            return p + Math.abs(c.value);
        };
        return function (t1, t2) {
            var t1Sum = t1.values.reduce(reducer, 0),
                t2Sum = t2.values.reduce(reducer, 0);
            return orderAsc ? t2Sum - t1Sum : t1Sum - t2Sum;
        };
    } else if (isFunction(config.data_order)) {
        return config.data_order;
    } else if (isArray(config.data_order)) {
        var order = config.data_order;
        return function (t1, t2) {
            return order.indexOf(t1.id) - order.indexOf(t2.id);
        };
    }
};
ChartInternal.prototype.orderTargets = function (targets) {
    var fct = this.getOrderFunction();
    if (fct) {
        targets.sort(fct);
    }
    return targets;
};
ChartInternal.prototype.filterByX = function (targets, x) {
    return this.d3.merge(targets.map(function (t) {
        return t.values;
    })).filter(function (v) {
        return v.x - x === 0;
    });
};
ChartInternal.prototype.filterRemoveNull = function (data) {
    return data.filter(function (d) {
        return isValue(d.value);
    });
};
ChartInternal.prototype.filterByXDomain = function (targets, xDomain) {
    return targets.map(function (t) {
        return {
            id: t.id,
            id_org: t.id_org,
            values: t.values.filter(function (v) {
                return xDomain[0] <= v.x && v.x <= xDomain[1];
            })
        };
    });
};
ChartInternal.prototype.hasDataLabel = function () {
    var config = this.config;
    if (typeof config.data_labels === 'boolean' && config.data_labels) {
        return true;
    } else if (typeof config.data_labels === 'object' && notEmpty(config.data_labels)) {
        return true;
    }
    return false;
};
ChartInternal.prototype.getDataLabelLength = function (min, max, key) {
    var $$ = this,
        lengths = [0, 0],
        paddingCoef = 1.3;
    $$.selectChart.select('svg').selectAll('.dummy')
        .data([min, max])
        .enter().append('text')
        .text(function (d) {
            return $$.dataLabelFormat(d.id)(d);
        })
        .each(function (d, i) {
            lengths[i] = this.getBoundingClientRect()[key] * paddingCoef;
        })
        .remove();
    return lengths;
};
/**
 * Returns true if the given data point is not arc type, otherwise false.
 * @param {Object} d The data point
 * @return {boolean}
 */
ChartInternal.prototype.isNoneArc = function (d) {
    return this.hasTarget(this.data.targets, d.id);
};

/**
 * Returns true if the given data point is arc type, otherwise false.
 * @param {Object} d The data point
 * @return {boolean}
 */
ChartInternal.prototype.isArc = function (d) {
    return 'data' in d && this.hasTarget(this.data.targets, d.data.id);
};

ChartInternal.prototype.findClosestFromTargets = function (targets, pos) {
    var $$ = this,
        candidates;

    // map to array of closest points of each target
    candidates = targets.map(function (target) {
        return $$.findClosest(target.values, pos);
    });

    // decide closest point and return
    return $$.findClosest(candidates, pos);
};
ChartInternal.prototype.findClosest = function (values, pos) {
    var $$ = this,
        minDist = $$.config.point_sensitivity,
        closest;

    // find mouseovering bar
    values.filter(function (v) {
        return v && $$.isBarType(v.id);
    }).forEach(function (v) {
        var shape = $$.main.select('.' + CLASS.bars + $$.getTargetSelectorSuffix(v.id) + ' .' + CLASS.bar + '-' + v.index).node();
        if (!closest && $$.isWithinBar($$.d3.mouse(shape), shape)) {
            closest = v;
        }
    });

    // find closest point from non-bar
    values.filter(function (v) {
        return v && !$$.isBarType(v.id);
    }).forEach(function (v) {
        var d = $$.dist(v, pos);
        if (d < minDist) {
            minDist = d;
            closest = v;
        }
    });

    return closest;
};
ChartInternal.prototype.dist = function (data, pos) {
    var $$ = this,
        config = $$.config,
        xIndex = config.axis_rotated ? 1 : 0,
        yIndex = config.axis_rotated ? 0 : 1,
        y = $$.circleY(data, data.index),
        x = $$.x(data.x);
    return Math.sqrt(Math.pow(x - pos[xIndex], 2) + Math.pow(y - pos[yIndex], 2));
};
ChartInternal.prototype.convertValuesToStep = function (values) {
    var converted = [].concat(values),
        i;

    if (!this.isCategorized()) {
        return values;
    }

    for (i = values.length + 1; 0 < i; i--) {
        converted[i] = converted[i - 1];
    }

    converted[0] = {
        x: converted[0].x - 1,
        value: converted[0].value,
        id: converted[0].id
    };
    converted[values.length + 1] = {
        x: converted[values.length].x + 1,
        value: converted[values.length].value,
        id: converted[values.length].id
    };

    return converted;
};
ChartInternal.prototype.updateDataAttributes = function (name, attrs) {
    var $$ = this,
        config = $$.config,
        current = config['data_' + name];
    if (typeof attrs === 'undefined') {
        return current;
    }
    Object.keys(attrs).forEach(function (id) {
        current[id] = attrs[id];
    });
    $$.redraw({
        withLegend: true
    });
    return current;
};
src/core.js000064400000114431151701472650006635 0ustar00import {
    ChartInternal
} from './chart-internal';
import {
    Chart
} from './chart';
import {
    AxisInternal
} from './axis-internal';
import Axis from './axis';
import CLASS from './class';

import {
    asHalfPixel,
    getOption,
    getPathBox,
    isFunction,
    isValue,
    notEmpty
} from './util';

var c3 = {
    version: "0.6.8",
    chart: {
        fn: Chart.prototype,
        internal: {
            fn: ChartInternal.prototype,
            axis: {
                fn: Axis.prototype,
                internal: {
                    fn: AxisInternal.prototype
                }
            }
        }
    },
    generate: function(config) {
        return new Chart(config);
    }
};

export {
    c3
};

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()) + '-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 = false;
    $$.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);
    }

    // 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 ($$.initSubchart) {
        $$.initSubchart();
    }
    if ($$.initTooltip) {
        $$.initTooltip();
    }
    if ($$.initLegend) {
        $$.initLegend();
    }
    if ($$.initTitle) {
        $$.initTitle();
    }
    if ($$.initZoom) {
        $$.initZoom();
    }

    // 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 ($$.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();
    }

    // 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 resize event
    $$.bindResize();

    // export element of the chart
    $$.api.element = $$.selectChart.node();
};

ChartInternal.prototype.smoothLines = function(el, type) {
    var $$ = this;
    if (type === 'grid') {
        el.each(function() {
            var g = $$.d3.select(this),
                x1 = g.attr('x1'),
                x2 = g.attr('x2'),
                y1 = g.attr('y1'),
                y2 = g.attr('y2');
            g.attr({
                'x1': Math.ceil(x1),
                'x2': Math.ceil(x2),
                'y1': Math.ceil(y1),
                'y2': Math.ceil(y2)
            });
        });
    }
};

ChartInternal.prototype.updateSizes = function() {
    var $$ = this,
        config = $$.config;
    var legendHeight = $$.legend ? $$.getLegendHeight() : 0,
        legendWidth = $$.legend ? $$.getLegendWidth() : 0,
        legendHeightForBottom = $$.isLegendRight || $$.isLegendInset ? 0 : legendHeight,
        hasArc = $$.hasArcType(),
        xAxisHeight = config.axis_rotated || hasArc ? 0 : $$.getHorizontalAxisHeight('x'),
        subchartHeight = config.subchart_show && !hasArc ? (config.subchart_size_height + xAxisHeight) : 0;

    $$.currentWidth = $$.getCurrentWidth();
    $$.currentHeight = $$.getCurrentHeight();

    // for main
    $$.margin = config.axis_rotated ? {
        top: $$.getHorizontalAxisHeight('y2') + $$.getCurrentPaddingTop(),
        right: hasArc ? 0 : $$.getCurrentPaddingRight(),
        bottom: $$.getHorizontalAxisHeight('y') + legendHeightForBottom + $$.getCurrentPaddingBottom(),
        left: subchartHeight + (hasArc ? 0 : $$.getCurrentPaddingLeft())
    } : {
        top: 4 + $$.getCurrentPaddingTop(), // for top tick text
        right: hasArc ? 0 : $$.getCurrentPaddingRight(),
        bottom: xAxisHeight + subchartHeight + legendHeightForBottom + $$.getCurrentPaddingBottom(),
        left: hasArc ? 0 : $$.getCurrentPaddingLeft()
    };

    // for subchart
    $$.margin2 = config.axis_rotated ? {
        top: $$.margin.top,
        right: NaN,
        bottom: 20 + legendHeightForBottom,
        left: $$.rotated_padding_left
    } : {
        top: $$.currentHeight - subchartHeight - legendHeightForBottom,
        right: NaN,
        bottom: xAxisHeight + legendHeightForBottom,
        left: $$.margin.left
    };

    // for legend
    $$.margin3 = {
        top: 0,
        right: NaN,
        bottom: 0,
        left: 0
    };
    if ($$.updateSizeForLegend) {
        $$.updateSizeForLegend(legendHeight, legendWidth);
    }

    $$.width = $$.currentWidth - $$.margin.left - $$.margin.right;
    $$.height = $$.currentHeight - $$.margin.top - $$.margin.bottom;
    if ($$.width < 0) {
        $$.width = 0;
    }
    if ($$.height < 0) {
        $$.height = 0;
    }

    $$.width2 = config.axis_rotated ? $$.margin.left - $$.rotated_padding_left - $$.rotated_padding_right : $$.width;
    $$.height2 = config.axis_rotated ? $$.height : $$.currentHeight - $$.margin2.top - $$.margin2.bottom;
    if ($$.width2 < 0) {
        $$.width2 = 0;
    }
    if ($$.height2 < 0) {
        $$.height2 = 0;
    }

    // for arc
    $$.arcWidth = $$.width - ($$.isLegendRight ? legendWidth + 10 : 0);
    $$.arcHeight = $$.height - ($$.isLegendRight ? 0 : 10);
    if ($$.hasType('gauge') && !config.gauge_fullCircle) {
        $$.arcHeight += $$.height - $$.getGaugeLabelHeight();
    }
    if ($$.updateRadius) {
        $$.updateRadius();
    }

    if ($$.isLegendRight && hasArc) {
        $$.margin3.left = $$.arcWidth / 2 + $$.radiusExpanded * 1.1;
    }
};

ChartInternal.prototype.updateTargets = function(targets) {
    var $$ = this;

    /*-- Main --*/

    //-- Text --//
    $$.updateTargetsForText(targets);

    //-- Bar --//
    $$.updateTargetsForBar(targets);

    //-- Line --//
    $$.updateTargetsForLine(targets);

    //-- Arc --//
    if ($$.hasArcType() && $$.updateTargetsForArc) {
        $$.updateTargetsForArc(targets);
    }

    /*-- Sub --*/

    if ($$.updateTargetsForSubchart) {
        $$.updateTargetsForSubchart(targets);
    }

    // Fade-in each chart
    $$.showTargets();
};
ChartInternal.prototype.showTargets = function() {
    var $$ = this;
    $$.svg.selectAll('.' + CLASS.target).filter(function(d) {
            return $$.isTargetToShow(d.id);
        })
        .transition().duration($$.config.transition_duration)
        .style("opacity", 1);
};

ChartInternal.prototype.redraw = function(options, transitions) {
    var $$ = this,
        main = $$.main,
        d3 = $$.d3,
        config = $$.config;
    var areaIndices = $$.getShapeIndices($$.isAreaType),
        barIndices = $$.getShapeIndices($$.isBarType),
        lineIndices = $$.getShapeIndices($$.isLineType);
    var withY, withSubchart, withTransition, withTransitionForExit, withTransitionForAxis,
        withTransform, withUpdateXDomain, withUpdateOrgXDomain, withTrimXDomain, withLegend,
        withEventRect, withDimension, withUpdateXAxis;
    var hideAxis = $$.hasArcType();
    var drawArea, drawBar, drawLine, xForText, yForText;
    var duration, durationForExit, durationForAxis;
    var transitionsToWait, waitForDraw, flow, transition;
    var targetsToShow = $$.filterTargetsToShow($$.data.targets),
        tickValues, i, intervalForCulling, xDomainForZoom;
    var xv = $$.xv.bind($$),
        cx, cy;

    options = options || {};
    withY = getOption(options, "withY", true);
    withSubchart = getOption(options, "withSubchart", true);
    withTransition = getOption(options, "withTransition", true);
    withTransform = getOption(options, "withTransform", false);
    withUpdateXDomain = getOption(options, "withUpdateXDomain", false);
    withUpdateOrgXDomain = getOption(options, "withUpdateOrgXDomain", false);
    withTrimXDomain = getOption(options, "withTrimXDomain", true);
    withUpdateXAxis = getOption(options, "withUpdateXAxis", withUpdateXDomain);
    withLegend = getOption(options, "withLegend", false);
    withEventRect = getOption(options, "withEventRect", true);
    withDimension = getOption(options, "withDimension", true);
    withTransitionForExit = getOption(options, "withTransitionForExit", withTransition);
    withTransitionForAxis = getOption(options, "withTransitionForAxis", withTransition);

    duration = withTransition ? config.transition_duration : 0;
    durationForExit = withTransitionForExit ? duration : 0;
    durationForAxis = withTransitionForAxis ? duration : 0;

    transitions = transitions || $$.axis.generateTransitions(durationForAxis);

    // update legend and transform each g
    if (withLegend && config.legend_show) {
        $$.updateLegend($$.mapToIds($$.data.targets), options, transitions);
    } else if (withDimension) {
        // need to update dimension (e.g. axis.y.tick.values) because y tick values should change
        // no need to update axis in it because they will be updated in redraw()
        $$.updateDimension(true);
    }

    // MEMO: needed for grids calculation
    if ($$.isCategorized() && targetsToShow.length === 0) {
        $$.x.domain([0, $$.axes.x.selectAll('.tick').size()]);
    }

    if (targetsToShow.length) {
        $$.updateXDomain(targetsToShow, withUpdateXDomain, withUpdateOrgXDomain, withTrimXDomain);
        if (!config.axis_x_tick_values) {
            tickValues = $$.axis.updateXAxisTickValues(targetsToShow);
        }
    } else {
        $$.xAxis.tickValues([]);
        $$.subXAxis.tickValues([]);
    }

    if (config.zoom_rescale && !options.flow) {
        xDomainForZoom = $$.x.orgDomain();
    }

    $$.y.domain($$.getYDomain(targetsToShow, 'y', xDomainForZoom));
    $$.y2.domain($$.getYDomain(targetsToShow, 'y2', xDomainForZoom));

    if (!config.axis_y_tick_values && config.axis_y_tick_count) {
        $$.yAxis.tickValues($$.axis.generateTickValues($$.y.domain(), config.axis_y_tick_count));
    }
    if (!config.axis_y2_tick_values && config.axis_y2_tick_count) {
        $$.y2Axis.tickValues($$.axis.generateTickValues($$.y2.domain(), config.axis_y2_tick_count));
    }

    // axes
    $$.axis.redraw(durationForAxis, hideAxis);

    // Update axis label
    $$.axis.updateLabels(withTransition);

    // show/hide if manual culling needed
    if ((withUpdateXDomain || withUpdateXAxis) && targetsToShow.length) {
        if (config.axis_x_tick_culling && tickValues) {
            for (i = 1; i < tickValues.length; i++) {
                if (tickValues.length / i < config.axis_x_tick_culling_max) {
                    intervalForCulling = i;
                    break;
                }
            }
            $$.svg.selectAll('.' + CLASS.axisX + ' .tick text').each(function(e) {
                var index = tickValues.indexOf(e);
                if (index >= 0) {
                    d3.select(this).style('display', index % intervalForCulling ? 'none' : 'block');
                }
            });
        } else {
            $$.svg.selectAll('.' + CLASS.axisX + ' .tick text').style('display', 'block');
        }
    }

    // setup drawer - MEMO: these must be called after axis updated
    drawArea = $$.generateDrawArea ? $$.generateDrawArea(areaIndices, false) : undefined;
    drawBar = $$.generateDrawBar ? $$.generateDrawBar(barIndices) : undefined;
    drawLine = $$.generateDrawLine ? $$.generateDrawLine(lineIndices, false) : undefined;
    xForText = $$.generateXYForText(areaIndices, barIndices, lineIndices, true);
    yForText = $$.generateXYForText(areaIndices, barIndices, lineIndices, false);

    // update circleY based on updated parameters
    $$.updateCircleY();
    // generate circle x/y functions depending on updated params
    cx = ($$.config.axis_rotated ? $$.circleY : $$.circleX).bind($$);
    cy = ($$.config.axis_rotated ? $$.circleX : $$.circleY).bind($$);

    // Update sub domain
    if (withY) {
        $$.subY.domain($$.getYDomain(targetsToShow, 'y'));
        $$.subY2.domain($$.getYDomain(targetsToShow, 'y2'));
    }

    // xgrid focus
    $$.updateXgridFocus();

    // Data empty label positioning and text.
    main.select("text." + CLASS.text + '.' + CLASS.empty)
        .attr("x", $$.width / 2)
        .attr("y", $$.height / 2)
        .text(config.data_empty_label_text)
        .transition()
        .style('opacity', targetsToShow.length ? 0 : 1);

    // event rect
    if (withEventRect) {
        $$.redrawEventRect();
    }

    // grid
    $$.updateGrid(duration);

    // rect for regions
    $$.updateRegion(duration);

    // bars
    $$.updateBar(durationForExit);

    // lines, areas and cricles
    $$.updateLine(durationForExit);
    $$.updateArea(durationForExit);
    $$.updateCircle(cx, cy);

    // text
    if ($$.hasDataLabel()) {
        $$.updateText(xForText, yForText, durationForExit);
    }

    // title
    if ($$.redrawTitle) {
        $$.redrawTitle();
    }

    // arc
    if ($$.redrawArc) {
        $$.redrawArc(duration, durationForExit, withTransform);
    }

    // subchart
    if ($$.redrawSubchart) {
        $$.redrawSubchart(withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices);
    }

    // circles for select
    main.selectAll('.' + CLASS.selectedCircles)
        .filter($$.isBarType.bind($$))
        .selectAll('circle')
        .remove();

    if (options.flow) {
        flow = $$.generateFlow({
            targets: targetsToShow,
            flow: options.flow,
            duration: options.flow.duration,
            drawBar: drawBar,
            drawLine: drawLine,
            drawArea: drawArea,
            cx: cx,
            cy: cy,
            xv: xv,
            xForText: xForText,
            yForText: yForText
        });
    }

    if ($$.isTabVisible()) { // Only use transition if tab visible. See #938.
        if (duration) {
            // transition should be derived from one transition
            transition = d3.transition().duration(duration);
            transitionsToWait = [];
            [
                $$.redrawBar(drawBar, true, transition),
                $$.redrawLine(drawLine, true, transition),
                $$.redrawArea(drawArea, true, transition),
                $$.redrawCircle(cx, cy, true, transition),
                $$.redrawText(xForText, yForText, options.flow, true, transition),
                $$.redrawRegion(true, transition),
                $$.redrawGrid(true, transition),
            ].forEach(function(transitions) {
                transitions.forEach(function(transition) {
                    transitionsToWait.push(transition);
                });
            });
            // Wait for end of transitions to call flow and onrendered callback
            waitForDraw = $$.generateWait();
            transitionsToWait.forEach(function(t) {
                waitForDraw.add(t);
            });
            waitForDraw(function() {
                if (flow) {
                    flow();
                }
                if (config.onrendered) {
                    config.onrendered.call($$);
                }
            });
        } else {
            $$.redrawBar(drawBar);
            $$.redrawLine(drawLine);
            $$.redrawArea(drawArea);
            $$.redrawCircle(cx, cy);
            $$.redrawText(xForText, yForText, options.flow);
            $$.redrawRegion();
            $$.redrawGrid();
            if (flow) {
                flow();
            }
            if (config.onrendered) {
                config.onrendered.call($$);
            }
        }
    }

    // update fadein condition
    $$.mapToIds($$.data.targets).forEach(function(id) {
        $$.withoutFadeIn[id] = true;
    });
};

ChartInternal.prototype.updateAndRedraw = function(options) {
    var $$ = this,
        config = $$.config,
        transitions;
    options = options || {};
    // same with redraw
    options.withTransition = getOption(options, "withTransition", true);
    options.withTransform = getOption(options, "withTransform", false);
    options.withLegend = getOption(options, "withLegend", false);
    // NOT same with redraw
    options.withUpdateXDomain = getOption(options, "withUpdateXDomain", true);
    options.withUpdateOrgXDomain = getOption(options, "withUpdateOrgXDomain", true);
    options.withTransitionForExit = false;
    options.withTransitionForTransform = getOption(options, "withTransitionForTransform", options.withTransition);
    // MEMO: this needs to be called before updateLegend and it means this ALWAYS needs to be called)
    $$.updateSizes();
    // MEMO: called in updateLegend in redraw if withLegend
    if (!(options.withLegend && config.legend_show)) {
        transitions = $$.axis.generateTransitions(options.withTransitionForAxis ? config.transition_duration : 0);
        // Update scales
        $$.updateScales();
        $$.updateSvgSize();
        // Update g positions
        $$.transformAll(options.withTransitionForTransform, transitions);
    }
    // Draw with new sizes & scales
    $$.redraw(options, transitions);
};
ChartInternal.prototype.redrawWithoutRescale = function() {
    this.redraw({
        withY: false,
        withSubchart: false,
        withEventRect: false,
        withTransitionForAxis: false
    });
};

ChartInternal.prototype.isTimeSeries = function() {
    return this.config.axis_x_type === 'timeseries';
};
ChartInternal.prototype.isCategorized = function() {
    return this.config.axis_x_type.indexOf('categor') >= 0;
};
ChartInternal.prototype.isCustomX = function() {
    var $$ = this,
        config = $$.config;
    return !$$.isTimeSeries() && (config.data_x || notEmpty(config.data_xs));
};

ChartInternal.prototype.isTimeSeriesY = function() {
    return this.config.axis_y_type === 'timeseries';
};

ChartInternal.prototype.getTranslate = function(target) {
    var $$ = this,
        config = $$.config,
        x, y;
    if (target === 'main') {
        x = asHalfPixel($$.margin.left);
        y = asHalfPixel($$.margin.top);
    } else if (target === 'context') {
        x = asHalfPixel($$.margin2.left);
        y = asHalfPixel($$.margin2.top);
    } else if (target === 'legend') {
        x = $$.margin3.left;
        y = $$.margin3.top;
    } else if (target === 'x') {
        x = 0;
        y = config.axis_rotated ? 0 : $$.height;
    } else if (target === 'y') {
        x = 0;
        y = config.axis_rotated ? $$.height : 0;
    } else if (target === 'y2') {
        x = config.axis_rotated ? 0 : $$.width;
        y = config.axis_rotated ? 1 : 0;
    } else if (target === 'subx') {
        x = 0;
        y = config.axis_rotated ? 0 : $$.height2;
    } else if (target === 'arc') {
        x = $$.arcWidth / 2;
        y = $$.arcHeight / 2 - ($$.hasType('gauge') ? 6 : 0); // to prevent wrong display of min and max label
    }
    return "translate(" + x + "," + y + ")";
};
ChartInternal.prototype.initialOpacity = function(d) {
    return d.value !== null && this.withoutFadeIn[d.id] ? 1 : 0;
};
ChartInternal.prototype.initialOpacityForCircle = function(d) {
    return d.value !== null && this.withoutFadeIn[d.id] ? this.opacityForCircle(d) : 0;
};
ChartInternal.prototype.opacityForCircle = function(d) {
    var isPointShouldBeShown = isFunction(this.config.point_show) ? this.config.point_show(d) : this.config.point_show;
    var opacity = isPointShouldBeShown ? 1 : 0;
    return isValue(d.value) ? (this.isScatterType(d) ? 0.5 : opacity) : 0;
};
ChartInternal.prototype.opacityForText = function() {
    return this.hasDataLabel() ? 1 : 0;
};
ChartInternal.prototype.xx = function(d) {
    return d ? this.x(d.x) : null;
};
ChartInternal.prototype.xv = function(d) {
    var $$ = this,
        value = d.value;
    if ($$.isTimeSeries()) {
        value = $$.parseDate(d.value);
    } else if ($$.isCategorized() && typeof d.value === 'string') {
        value = $$.config.axis_x_categories.indexOf(d.value);
    }
    return Math.ceil($$.x(value));
};
ChartInternal.prototype.yv = function(d) {
    var $$ = this,
        yScale = d.axis && d.axis === 'y2' ? $$.y2 : $$.y;
    return Math.ceil(yScale(d.value));
};
ChartInternal.prototype.subxx = function(d) {
    return d ? this.subX(d.x) : null;
};

ChartInternal.prototype.transformMain = function(withTransition, transitions) {
    var $$ = this,
        xAxis, yAxis, y2Axis;
    if (transitions && transitions.axisX) {
        xAxis = transitions.axisX;
    } else {
        xAxis = $$.main.select('.' + CLASS.axisX);
        if (withTransition) {
            xAxis = xAxis.transition();
        }
    }
    if (transitions && transitions.axisY) {
        yAxis = transitions.axisY;
    } else {
        yAxis = $$.main.select('.' + CLASS.axisY);
        if (withTransition) {
            yAxis = yAxis.transition();
        }
    }
    if (transitions && transitions.axisY2) {
        y2Axis = transitions.axisY2;
    } else {
        y2Axis = $$.main.select('.' + CLASS.axisY2);
        if (withTransition) {
            y2Axis = y2Axis.transition();
        }
    }
    (withTransition ? $$.main.transition() : $$.main).attr("transform", $$.getTranslate('main'));
    xAxis.attr("transform", $$.getTranslate('x'));
    yAxis.attr("transform", $$.getTranslate('y'));
    y2Axis.attr("transform", $$.getTranslate('y2'));
    $$.main.select('.' + CLASS.chartArcs).attr("transform", $$.getTranslate('arc'));
};
ChartInternal.prototype.transformAll = function(withTransition, transitions) {
    var $$ = this;
    $$.transformMain(withTransition, transitions);
    if ($$.config.subchart_show) {
        $$.transformContext(withTransition, transitions);
    }
    if ($$.legend) {
        $$.transformLegend(withTransition);
    }
};

ChartInternal.prototype.updateSvgSize = function() {
    var $$ = this,
        brush = $$.svg.select(".c3-brush .overlay");
    $$.svg.attr('width', $$.currentWidth).attr('height', $$.currentHeight);
    $$.svg.selectAll(['#' + $$.clipId, '#' + $$.clipIdForGrid]).select('rect')
        .attr('width', $$.width)
        .attr('height', $$.height);
    $$.svg.select('#' + $$.clipIdForXAxis).select('rect')
        .attr('x', $$.getXAxisClipX.bind($$))
        .attr('y', $$.getXAxisClipY.bind($$))
        .attr('width', $$.getXAxisClipWidth.bind($$))
        .attr('height', $$.getXAxisClipHeight.bind($$));
    $$.svg.select('#' + $$.clipIdForYAxis).select('rect')
        .attr('x', $$.getYAxisClipX.bind($$))
        .attr('y', $$.getYAxisClipY.bind($$))
        .attr('width', $$.getYAxisClipWidth.bind($$))
        .attr('height', $$.getYAxisClipHeight.bind($$));
    $$.svg.select('#' + $$.clipIdForSubchart).select('rect')
        .attr('width', $$.width)
        .attr('height', brush.size() ? brush.attr('height') : 0);
    // MEMO: parent div's height will be bigger than svg when <!DOCTYPE html>
    $$.selectChart.style('max-height', $$.currentHeight + "px");
};

ChartInternal.prototype.updateDimension = function(withoutAxis) {
    var $$ = this;
    if (!withoutAxis) {
        if ($$.config.axis_rotated) {
            $$.axes.x.call($$.xAxis);
            $$.axes.subx.call($$.subXAxis);
        } else {
            $$.axes.y.call($$.yAxis);
            $$.axes.y2.call($$.y2Axis);
        }
    }
    $$.updateSizes();
    $$.updateScales();
    $$.updateSvgSize();
    $$.transformAll(false);
};

ChartInternal.prototype.observeInserted = function(selection) {
    var $$ = this,
        observer;
    if (typeof MutationObserver === 'undefined') {
        window.console.error("MutationObserver not defined.");
        return;
    }
    observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'childList' && mutation.previousSibling) {
                observer.disconnect();
                // need to wait for completion of load because size calculation requires the actual sizes determined after that completion
                $$.intervalForObserveInserted = window.setInterval(function() {
                    // parentNode will NOT be null when completed
                    if (selection.node().parentNode) {
                        window.clearInterval($$.intervalForObserveInserted);
                        $$.updateDimension();
                        if ($$.brush) {
                            $$.brush.update();
                        }
                        $$.config.oninit.call($$);
                        $$.redraw({
                            withTransform: true,
                            withUpdateXDomain: true,
                            withUpdateOrgXDomain: true,
                            withTransition: false,
                            withTransitionForTransform: false,
                            withLegend: true
                        });
                        selection.transition().style('opacity', 1);
                    }
                }, 10);
            }
        });
    });
    observer.observe(selection.node(), {
        attributes: true,
        childList: true,
        characterData: true
    });
};

ChartInternal.prototype.bindResize = function() {
    var $$ = this,
        config = $$.config;

    $$.resizeFunction = $$.generateResize(); // need to call .remove

    $$.resizeFunction.add(function() {
        config.onresize.call($$);
    });
    if (config.resize_auto) {
        $$.resizeFunction.add(function() {
            if ($$.resizeTimeout !== undefined) {
                window.clearTimeout($$.resizeTimeout);
            }
            $$.resizeTimeout = window.setTimeout(function() {
                delete $$.resizeTimeout;
                $$.updateAndRedraw({
                    withUpdateXDomain: false,
                    withUpdateOrgXDomain: false,
                    withTransition: false,
                    withTransitionForTransform: false,
                    withLegend: true,
                });
                if ($$.brush) {
                    $$.brush.update();
                }
            }, 100);
        });
    }
    $$.resizeFunction.add(function() {
        config.onresized.call($$);
    });

    $$.resizeIfElementDisplayed = function() {
        // if element not displayed skip it
        if ($$.api == null || !$$.api.element.offsetParent) {
            return;
        }

        $$.resizeFunction();
    };

    if (window.attachEvent) {
        window.attachEvent('onresize', $$.resizeIfElementDisplayed);
    } else if (window.addEventListener) {
        window.addEventListener('resize', $$.resizeIfElementDisplayed, false);
    } else {
        // fallback to this, if this is a very old browser
        var wrapper = window.onresize;
        if (!wrapper) {
            // create a wrapper that will call all charts
            wrapper = $$.generateResize();
        } else if (!wrapper.add || !wrapper.remove) {
            // there is already a handler registered, make sure we call it too
            wrapper = $$.generateResize();
            wrapper.add(window.onresize);
        }
        // add this graph to the wrapper, we will be removed if the user calls destroy
        wrapper.add($$.resizeFunction);
        window.onresize = function() {
            // if element not displayed skip it
            if (!$$.api.element.offsetParent) {
                return;
            }

            wrapper();
        };
    }
};

ChartInternal.prototype.generateResize = function() {
    var resizeFunctions = [];

    function callResizeFunctions() {
        resizeFunctions.forEach(function(f) {
            f();
        });
    }
    callResizeFunctions.add = function(f) {
        resizeFunctions.push(f);
    };
    callResizeFunctions.remove = function(f) {
        for (var i = 0; i < resizeFunctions.length; i++) {
            if (resizeFunctions[i] === f) {
                resizeFunctions.splice(i, 1);
                break;
            }
        }
    };
    return callResizeFunctions;
};

ChartInternal.prototype.endall = function(transition, callback) {
    var n = 0;
    transition
        .each(function() {
            ++n;
        })
        .on("end", function() {
            if (!--n) {
                callback.apply(this, arguments);
            }
        });
};
ChartInternal.prototype.generateWait = function() {
    var transitionsToWait = [],
        f = function(callback) {
            var timer = setInterval(function() {
                var done = 0;
                transitionsToWait.forEach(function(t) {
                    if (t.empty()) {
                        done += 1;
                        return;
                    }
                    try {
                        t.transition();
                    } catch (e) {
                        done += 1;
                    }
                });
                if (done === transitionsToWait.length) {
                    clearInterval(timer);
                    if (callback) {
                        callback();
                    }
                }
            }, 50);
        };
    f.add = function(transition) {
        transitionsToWait.push(transition);
    };
    return f;
};

ChartInternal.prototype.parseDate = function(date) {
    var $$ = this,
        parsedDate;
    if (date instanceof Date) {
        parsedDate = date;
    } else if (typeof date === 'string') {
        parsedDate = $$.dataTimeParse(date);
    } else if (typeof date === 'object') {
        parsedDate = new Date(+date);
    } else if (typeof date === 'number' && !isNaN(date)) {
        parsedDate = new Date(+date);
    }
    if (!parsedDate || isNaN(+parsedDate)) {
        window.console.error("Failed to parse x '" + date + "' to Date object");
    }
    return parsedDate;
};

ChartInternal.prototype.isTabVisible = function() {
    var hidden;
    if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
        hidden = "hidden";
    } else if (typeof document.mozHidden !== "undefined") {
        hidden = "mozHidden";
    } else if (typeof document.msHidden !== "undefined") {
        hidden = "msHidden";
    } else if (typeof document.webkitHidden !== "undefined") {
        hidden = "webkitHidden";
    }

    return document[hidden] ? false : true;
};

ChartInternal.prototype.getPathBox = getPathBox;
ChartInternal.prototype.CLASS = CLASS;

export {
    Chart
};
export {
    ChartInternal
};
src/type.js000064400000007007151701472650006666 0ustar00import { ChartInternal } from './core';
import { isString } from './util';

ChartInternal.prototype.setTargetType = function (targetIds, type) {
    var $$ = this, config = $$.config;
    $$.mapToTargetIds(targetIds).forEach(function (id) {
        $$.withoutFadeIn[id] = (type === config.data_types[id]);
        config.data_types[id] = type;
    });
    if (!targetIds) {
        config.data_type = type;
    }
};
ChartInternal.prototype.hasType = function (type, targets) {
    var $$ = this, types = $$.config.data_types, has = false;
    targets = targets || $$.data.targets;
    if (targets && targets.length) {
        targets.forEach(function (target) {
            var t = types[target.id];
            if ((t && t.indexOf(type) >= 0) || (!t && type === 'line')) {
                has = true;
            }
        });
    } else if (Object.keys(types).length) {
        Object.keys(types).forEach(function (id) {
            if (types[id] === type) { has = true; }
        });
    } else {
        has = $$.config.data_type === type;
    }
    return has;
};
ChartInternal.prototype.hasArcType = function (targets) {
    return this.hasType('pie', targets) || this.hasType('donut', targets) || this.hasType('gauge', targets);
};
ChartInternal.prototype.isLineType = function (d) {
    var config = this.config, id = isString(d) ? d : d.id;
    return !config.data_types[id] || ['line', 'spline', 'area', 'area-spline', 'step', 'area-step'].indexOf(config.data_types[id]) >= 0;
};
ChartInternal.prototype.isStepType = function (d) {
    var id = isString(d) ? d : d.id;
    return ['step', 'area-step'].indexOf(this.config.data_types[id]) >= 0;
};
ChartInternal.prototype.isSplineType = function (d) {
    var id = isString(d) ? d : d.id;
    return ['spline', 'area-spline'].indexOf(this.config.data_types[id]) >= 0;
};
ChartInternal.prototype.isAreaType = function (d) {
    var id = isString(d) ? d : d.id;
    return ['area', 'area-spline', 'area-step'].indexOf(this.config.data_types[id]) >= 0;
};
ChartInternal.prototype.isBarType = function (d) {
    var id = isString(d) ? d : d.id;
    return this.config.data_types[id] === 'bar';
};
ChartInternal.prototype.isScatterType = function (d) {
    var id = isString(d) ? d : d.id;
    return this.config.data_types[id] === 'scatter';
};
ChartInternal.prototype.isPieType = function (d) {
    var id = isString(d) ? d : d.id;
    return this.config.data_types[id] === 'pie';
};
ChartInternal.prototype.isGaugeType = function (d) {
    var id = isString(d) ? d : d.id;
    return this.config.data_types[id] === 'gauge';
};
ChartInternal.prototype.isDonutType = function (d) {
    var id = isString(d) ? d : d.id;
    return this.config.data_types[id] === 'donut';
};
ChartInternal.prototype.isArcType = function (d) {
    return this.isPieType(d) || this.isDonutType(d) || this.isGaugeType(d);
};
ChartInternal.prototype.lineData = function (d) {
    return this.isLineType(d) ? [d] : [];
};
ChartInternal.prototype.arcData = function (d) {
    return this.isArcType(d.data) ? [d] : [];
};
/* not used
 function scatterData(d) {
 return isScatterType(d) ? d.values : [];
 }
 */
ChartInternal.prototype.barData = function (d) {
    return this.isBarType(d) ? d.values : [];
};
ChartInternal.prototype.lineOrScatterData = function (d) {
    return this.isLineType(d) || this.isScatterType(d) ? d.values : [];
};
ChartInternal.prototype.barOrLineData = function (d) {
    return this.isBarType(d) || this.isLineType(d) ? d.values : [];
};
src/api.focus.js000064400000004110151701472650007564 0ustar00import CLASS from './class';
import { Chart } from './core';

Chart.prototype.focus = function (targetIds) {
    var $$ = this.internal, candidates;

    targetIds = $$.mapToTargetIds(targetIds);
    candidates = $$.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))),

    this.revert();
    this.defocus();
    candidates.classed(CLASS.focused, true).classed(CLASS.defocused, false);
    if ($$.hasArcType()) {
        $$.expandArc(targetIds);
    }
    $$.toggleFocusLegend(targetIds, true);

    $$.focusedTargetIds = targetIds;
    $$.defocusedTargetIds = $$.defocusedTargetIds.filter(function (id) {
        return targetIds.indexOf(id) < 0;
    });
};

Chart.prototype.defocus = function (targetIds) {
    var $$ = this.internal, candidates;

    targetIds = $$.mapToTargetIds(targetIds);
    candidates = $$.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))),

    candidates.classed(CLASS.focused, false).classed(CLASS.defocused, true);
    if ($$.hasArcType()) {
        $$.unexpandArc(targetIds);
    }
    $$.toggleFocusLegend(targetIds, false);

    $$.focusedTargetIds = $$.focusedTargetIds.filter(function (id) {
        return targetIds.indexOf(id) < 0;
    });
    $$.defocusedTargetIds = targetIds;
};

Chart.prototype.revert = function (targetIds) {
    var $$ = this.internal, candidates;

    targetIds = $$.mapToTargetIds(targetIds);
    candidates = $$.svg.selectAll($$.selectorTargets(targetIds)); // should be for all targets

    candidates.classed(CLASS.focused, false).classed(CLASS.defocused, false);
    if ($$.hasArcType()) {
        $$.unexpandArc(targetIds);
    }
    if ($$.config.legend_show) {
        $$.showLegend(targetIds.filter($$.isLegendToShow.bind($$)));
        $$.legend.selectAll($$.selectorLegends(targetIds))
            .filter(function () {
                return $$.d3.select(this).classed(CLASS.legendItemFocused);
            })
            .classed(CLASS.legendItemFocused, false);
    }

    $$.focusedTargetIds = [];
    $$.defocusedTargetIds = [];
};
package.json000064400000007470151701472650007052 0ustar00{
  "_args": [
    [
      "c3@0.6.8",
      "C:\\Users\\Ovi-PC\\Downloads\\themekit-master\\themekit"
    ]
  ],
  "_from": "c3@0.6.8",
  "_id": "c3@0.6.8",
  "_inBundle": false,
  "_integrity": "sha512-HI1cAalsnwy9FJk8cywJ9jD0eIo8lb+9Ms2btz0bHVDU4UuGRPQcTcso2tCVg+Zdh6fa5vGkHcq/rVcSPo8a9w==",
  "_location": "/c3",
  "_phantomChildren": {},
  "_requested": {
    "type": "version",
    "registry": true,
    "raw": "c3@0.6.8",
    "name": "c3",
    "escapedName": "c3",
    "rawSpec": "0.6.8",
    "saveSpec": null,
    "fetchSpec": "0.6.8"
  },
  "_requiredBy": [
    "/"
  ],
  "_resolved": "https://registry.npmjs.org/c3/-/c3-0.6.8.tgz",
  "_spec": "0.6.8",
  "_where": "C:\\Users\\Ovi-PC\\Downloads\\themekit-master\\themekit",
  "authors": [
    "Masayuki Tanaka",
    "Ændrew Rininsland",
    "Yoshiya Hinosawa"
  ],
  "bugs": {
    "url": "https://github.com/c3js/c3/issues"
  },
  "dependencies": {
    "d3": "^5.0.0"
  },
  "description": "D3-based reusable chart library",
  "devDependencies": {
    "@babel/core": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "babel-plugin-istanbul": "^5.0.1",
    "babelify": "^10.0.0",
    "browserify": "^16.1.1",
    "clean-css-cli": "^4.1.11",
    "codecov": "^3.0.4",
    "gh-pages": "^2.0.0",
    "jasmine-core": "^2.3.4",
    "jshint": "2.9.6",
    "jshint-stylish": "^2.1.0",
    "karma": "^3.0.0",
    "karma-browserify": "^5.3.0",
    "karma-chrome-launcher": "^2.1.1",
    "karma-coverage-istanbul-reporter": "^2.0.0",
    "karma-jasmine": "^1.1.0",
    "karma-spec-reporter": "0.0.32",
    "node-static": "^0.7.9",
    "nodemon": "^1.18.3",
    "npm-run-all": "^4.1.3",
    "rollup": "^0.66.0",
    "rollup-plugin-babel": "^4.0.3",
    "sass": "^1.10.3",
    "status-back": "^1.1.0",
    "uglify-js": "^3.3.17",
    "watchify": "^3.11.0"
  },
  "files": [
    "c3.js",
    "c3.min.js",
    "c3.css",
    "c3.min.css",
    "src"
  ],
  "gitHead": "84e03109d9a590f9c8ef687c03d751f666080c6f",
  "greenkeeper": {
    "ignore": [
      "d3"
    ]
  },
  "homepage": "https://github.com/c3js/c3#readme",
  "keywords": [
    "d3",
    "chart",
    "graph"
  ],
  "license": "MIT",
  "main": "c3.js",
  "name": "c3",
  "nyc": {
    "exclude": [
      "src/polyfill.js",
      "spec/"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/c3js/c3.git"
  },
  "scripts": {
    "build": "run-s build:js build:css",
    "build:css": "run-s build:css:sass build:css:min",
    "build:css:min": "cleancss -o htdocs/css/c3.min.css htdocs/css/c3.css",
    "build:css:sass": "sass src/scss/main.scss > htdocs/css/c3.css",
    "build:docs": "bundle exec middleman build",
    "build:js": "run-s build:js:rollup build:js:uglify",
    "build:js:rollup": "rollup -c",
    "build:js:uglify": "uglifyjs htdocs/js/c3.js --compress --mangle --comments -o htdocs/js/c3.min.js",
    "codecov": "codecov",
    "copy-to-docs": "cp htdocs/js/c3.* docs/js/ && cp htdocs/css/c3.* docs/css/",
    "copy-to-root": "cp htdocs/{css,js}/c3.* ./",
    "dist": "run-s build copy-to-root copy-to-docs",
    "docs": "bundle exec middleman",
    "karma": "karma start karma.conf.js",
    "lint": "jshint --reporter=node_modules/jshint-stylish src/ spec/",
    "publish-docs": "npm run build:docs && gh-pages -d build -m \"chore: update gh-pages [skip ci]\"",
    "serve-static": "static -p 8080 htdocs/",
    "start": "run-p serve-static watch",
    "test": "run-s build lint karma",
    "watch": "nodemon -e js,scss --watch src -x 'npm run build:js:rollup && npm run build:css:sass'",
    "watch:css": "nodemon -e scss --watch src -x 'npm run build:css:sass'",
    "watch:docs": "bundle exec middleman",
    "watch:js": "nodemon -e js --watch src --ignore src/scss -x 'npm run build:js:rollup'"
  },
  "version": "0.6.8"
}
c3.min.js000064400000565363151701472650006223 0ustar00/* @license C3.js v0.6.8 | (c) C3 Team and other contributors | http://c3js.org/ */
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.c3=e()}(this,function(){"use strict";function s(t){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function l(t){var e=this;e.d3=window.d3?window.d3:"undefined"!=typeof require?require("d3"):void 0,e.api=t,e.config=e.getDefaultConfig(),e.data={},e.cache={},e.axes={}}function n(t){var e=this.internal=new l(this);e.loadConfig(t),e.beforeInit(t),e.init(),e.afterInit(t),function e(i,n,r){Object.keys(i).forEach(function(t){n[t]=i[t].bind(r),0<Object.keys(i[t]).length&&e(i[t],n[t],r)})}(n.prototype,this,this)}function i(t,e){var i=this;i.component=t,i.params=e||{},i.d3=t.d3,i.scale=i.d3.scaleLinear(),i.range,i.orient="bottom",i.innerTickSize=6,i.outerTickSize=this.params.withOuterTick?6:0,i.tickPadding=3,i.tickValues=null,i.tickFormat,i.tickArguments,i.tickOffset=0,i.tickCulling=!0,i.tickCentered,i.tickTextCharSize,i.tickTextRotate=i.params.tickTextRotate,i.tickLength,i.axis=i.generateAxis()}i.prototype.axisX=function(t,e,i){t.attr("transform",function(t){return"translate("+Math.ceil(e(t)+i)+", 0)"})},i.prototype.axisY=function(t,e){t.attr("transform",function(t){return"translate(0,"+Math.ceil(e(t))+")"})},i.prototype.scaleExtent=function(t){var e=t[0],i=t[t.length-1];return e<i?[e,i]:[i,e]},i.prototype.generateTicks=function(t){var e,i,n=[];if(t.ticks)return t.ticks.apply(t,this.tickArguments);for(i=t.domain(),e=Math.ceil(i[0]);e<i[1];e++)n.push(e);return 0<n.length&&0<n[0]&&n.unshift(n[0]-(n[1]-n[0])),n},i.prototype.copyScale=function(){var t,e=this.scale.copy();return this.params.isCategory&&(t=this.scale.domain(),e.domain([t[0],t[1]-1])),e},i.prototype.textFormatted=function(t){var e=this.tickFormat?this.tickFormat(t):t;return void 0!==e?e:""},i.prototype.updateRange=function(){var t=this;return t.range=t.scale.rangeExtent?t.scale.rangeExtent():t.scaleExtent(t.scale.range()),t.range},i.prototype.updateTickTextCharSize=function(t){var a=this;if(a.tickTextCharSize)return a.tickTextCharSize;var o={h:11.5,w:5.5};return t.select("text").text(function(t){return a.textFormatted(t)}).each(function(t){var e=this.getBoundingClientRect(),i=a.textFormatted(t),n=e.height,r=i?e.width/i.length:void 0;n&&r&&(o.h=n,o.w=r)}).text(""),a.tickTextCharSize=o},i.prototype.isVertical=function(){return"left"===this.orient||"right"===this.orient},i.prototype.tspanData=function(t,e,i){var n=this,r=n.params.tickMultiline?n.splitTickText(t,i):[].concat(n.textFormatted(t));return n.params.tickMultiline&&0<n.params.tickMultilineMax&&(r=n.ellipsify(r,n.params.tickMultilineMax)),r.map(function(t){return{index:e,splitted:t,length:r.length}})},i.prototype.splitTickText=function(t,e){var r,a,o,s=this,i=s.textFormatted(t),c=s.params.tickWidth;if("[object Array]"===Object.prototype.toString.call(i))return i;return(!c||c<=0)&&(c=s.isVertical()?95:s.params.isCategory?Math.ceil(e(1)-e(0))-12:110),function t(e,i){a=void 0;for(var n=1;n<i.length;n++)if(" "===i.charAt(n)&&(a=n),r=i.substr(0,n+1),o=s.tickTextCharSize.w*r.length,c<o)return t(e.concat(i.substr(0,a||n)),i.slice(a?a+1:n));return e.concat(i)}([],i+"")},i.prototype.ellipsify=function(t,e){if(t.length<=e)return t;for(var i=t.slice(0,e),n=3,r=e-1;0<=r;r--){var a=i[r].length;if(i[r]=i[r].substr(0,a-n).padEnd(a,"."),(n-=a)<=0)break}return i},i.prototype.updateTickLength=function(){this.tickLength=Math.max(this.innerTickSize,0)+this.tickPadding},i.prototype.lineY2=function(t){var e=this,i=e.scale(t)+(e.tickCentered?0:e.tickOffset);return e.range[0]<i&&i<e.range[1]?e.innerTickSize:0},i.prototype.textY=function(){var t=this.tickTextRotate;return t?11.5-t/15*2.5*(0<t?1:-1):this.tickLength},i.prototype.textTransform=function(){var t=this.tickTextRotate;return t?"rotate("+t+")":""},i.prototype.textTextAnchor=function(){var t=this.tickTextRotate;return t?0<t?"start":"end":"middle"},i.prototype.tspanDx=function(){var t=this.tickTextRotate;return t?8*Math.sin(Math.PI*(t/180)):0},i.prototype.tspanDy=function(t,e){var i=this.tickTextCharSize.h;return 0===e&&(i=this.isVertical()?-((t.length-1)*(this.tickTextCharSize.h/2)-3):".71em"),i},i.prototype.generateAxis=function(){var w=this,v=w.d3,b=w.params;function A(t,m){var S;return t.each(function(){var t,e,i,n=A.g=v.select(this),r=this.__chart__||w.scale,a=this.__chart__=w.copyScale(),o=w.tickValues?w.tickValues:w.generateTicks(a),s=n.selectAll(".tick").data(o,a),c=s.enter().insert("g",".domain").attr("class","tick").style("opacity",1e-6),d=s.exit().remove(),l=s.merge(c);b.isCategory?(w.tickOffset=Math.ceil((a(1)-a(0))/2),e=w.tickCentered?0:w.tickOffset,i=w.tickCentered?w.tickOffset:0):w.tickOffset=e=0,w.updateRange(),w.updateTickLength(),w.updateTickTextCharSize(n.select(".tick"));var u=l.select("line").merge(c.append("line")),h=l.select("text").merge(c.append("text")),g=l.selectAll("text").selectAll("tspan").data(function(t,e){return w.tspanData(t,e,a)}),p=g.enter().append("tspan").merge(g).text(function(t){return t.splitted});g.exit().remove();var f=n.selectAll(".domain").data([0]),_=f.enter().append("path").merge(f).attr("class","domain");switch(w.orient){case"bottom":t=w.axisX,u.attr("x1",e).attr("x2",e).attr("y2",function(t,e){return w.lineY2(t,e)}),h.attr("x",0).attr("y",function(t,e){return w.textY(t,e)}).attr("transform",function(t,e){return w.textTransform(t,e)}).style("text-anchor",function(t,e){return w.textTextAnchor(t,e)}),p.attr("x",0).attr("dy",function(t,e){return w.tspanDy(t,e)}).attr("dx",function(t,e){return w.tspanDx(t,e)}),_.attr("d","M"+w.range[0]+","+w.outerTickSize+"V0H"+w.range[1]+"V"+w.outerTickSize);break;case"top":t=w.axisX,u.attr("x1",e).attr("x2",e).attr("y2",function(t,e){return-1*w.lineY2(t,e)}),h.attr("x",0).attr("y",function(t,e){return-1*w.textY(t,e)-(b.isCategory?2:w.tickLength-2)}).attr("transform",function(t,e){return w.textTransform(t,e)}).style("text-anchor",function(t,e){return w.textTextAnchor(t,e)}),p.attr("x",0).attr("dy",function(t,e){return w.tspanDy(t,e)}).attr("dx",function(t,e){return w.tspanDx(t,e)}),_.attr("d","M"+w.range[0]+","+-w.outerTickSize+"V0H"+w.range[1]+"V"+-w.outerTickSize);break;case"left":t=w.axisY,u.attr("x2",-w.innerTickSize).attr("y1",i).attr("y2",i),h.attr("x",-w.tickLength).attr("y",w.tickOffset).style("text-anchor","end"),p.attr("x",-w.tickLength).attr("dy",function(t,e){return w.tspanDy(t,e)}),_.attr("d","M"+-w.outerTickSize+","+w.range[0]+"H0V"+w.range[1]+"H"+-w.outerTickSize);break;case"right":t=w.axisY,u.attr("x2",w.innerTickSize).attr("y1",i).attr("y2",i),h.attr("x",w.tickLength).attr("y",w.tickOffset).style("text-anchor","start"),p.attr("x",w.tickLength).attr("dy",function(t,e){return w.tspanDy(t,e)}),_.attr("d","M"+w.outerTickSize+","+w.range[0]+"H0V"+w.range[1]+"H"+w.outerTickSize)}if(a.rangeBand){var x=a,y=x.rangeBand()/2;r=a=function(t){return x(t)+y}}else r.rangeBand?r=a:d.call(t,a,w.tickOffset);c.call(t,r,w.tickOffset),S=(m?l.transition(m):l).style("opacity",1).call(t,a,w.tickOffset)}),S}return A.scale=function(t){return arguments.length?(w.scale=t,A):w.scale},A.orient=function(t){return arguments.length?(w.orient=t in{top:1,right:1,bottom:1,left:1}?t+"":"bottom",A):w.orient},A.tickFormat=function(t){return arguments.length?(w.tickFormat=t,A):w.tickFormat},A.tickCentered=function(t){return arguments.length?(w.tickCentered=t,A):w.tickCentered},A.tickOffset=function(){return w.tickOffset},A.tickInterval=function(){var t;return(t=b.isCategory?2*w.tickOffset:(A.g.select("path.domain").node().getTotalLength()-2*w.outerTickSize)/A.g.selectAll("line").size())===1/0?0:t},A.ticks=function(){return arguments.length?(w.tickArguments=arguments,A):w.tickArguments},A.tickCulling=function(t){return arguments.length?(w.tickCulling=t,A):w.tickCulling},A.tickValues=function(t){if("function"==typeof t)w.tickValues=function(){return t(w.scale.domain())};else{if(!arguments.length)return w.tickValues;w.tickValues=t}return A},A};var Y={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",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_"},a=function(t){return Math.ceil(t)+.5},r=function(t){return 10*Math.ceil(t/10)},R=function(t){return t[1]-t[0]},N=function(t,e,i){return k(t[e])?t[e]:i},y=function(t){var e=t.getBoundingClientRect(),i=[t.pathSegList.getItem(0),t.pathSegList.getItem(1)];return{x:i[0].x,y:Math.min(i[0].y,i[1].y),width:e.width,height:e.height}},o=function(t){return Array.isArray(t)},k=function(t){return void 0!==t},u=function(t){return null==t||c(t)&&0===t.length||"object"===s(t)&&0===Object.keys(t).length},h=function(t){return"function"==typeof t},c=function(t){return"string"==typeof t},v=function(t){return void 0===t},P=function(t){return t||0===t},C=function(t){return!u(t)},_=function(t){return"string"==typeof t?t.replace(/</g,"&lt;").replace(/>/g,"&gt;"):t},d=function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.owner=e,this.d3=e.d3,this.internal=i};d.prototype.init=function(){var t=this.owner,e=t.config,i=t.main;t.axes.x=i.append("g").attr("class",Y.axis+" "+Y.axisX).attr("clip-path",e.axis_x_inner?"":t.clipPathForXAxis).attr("transform",t.getTranslate("x")).style("visibility",e.axis_x_show?"visible":"hidden"),t.axes.x.append("text").attr("class",Y.axisXLabel).attr("transform",e.axis_rotated?"rotate(-90)":"").style("text-anchor",this.textAnchorForXAxisLabel.bind(this)),t.axes.y=i.append("g").attr("class",Y.axis+" "+Y.axisY).attr("clip-path",e.axis_y_inner?"":t.clipPathForYAxis).attr("transform",t.getTranslate("y")).style("visibility",e.axis_y_show?"visible":"hidden"),t.axes.y.append("text").attr("class",Y.axisYLabel).attr("transform",e.axis_rotated?"":"rotate(-90)").style("text-anchor",this.textAnchorForYAxisLabel.bind(this)),t.axes.y2=i.append("g").attr("class",Y.axis+" "+Y.axisY2).attr("transform",t.getTranslate("y2")).style("visibility",e.axis_y2_show?"visible":"hidden"),t.axes.y2.append("text").attr("class",Y.axisY2Label).attr("transform",e.axis_rotated?"":"rotate(-90)").style("text-anchor",this.textAnchorForY2AxisLabel.bind(this))},d.prototype.getXAxis=function(t,e,i,n,r,a,o){var s=this.owner,c=s.config,d={isCategory:s.isCategorized(),withOuterTick:r,tickMultiline:c.axis_x_tick_multiline,tickMultilineMax:c.axis_x_tick_multiline?Number(c.axis_x_tick_multilineMax):0,tickWidth:c.axis_x_tick_width,tickTextRotate:o?0:c.axis_x_tick_rotate,withoutTransition:a},l=new this.internal(this,d).axis.scale(t).orient(e);return s.isTimeSeries()&&n&&"function"!=typeof n&&(n=n.map(function(t){return s.parseDate(t)})),l.tickFormat(i).tickValues(n),s.isCategorized()&&(l.tickCentered(c.axis_x_tick_centered),u(c.axis_x_tick_culling)&&(c.axis_x_tick_culling=!1)),l},d.prototype.updateXAxisTickValues=function(t,e){var i,n=this.owner,r=n.config;return(r.axis_x_tick_fit||r.axis_x_tick_count)&&(i=this.generateTickValues(n.mapTargetsToUniqueXs(t),r.axis_x_tick_count,n.isTimeSeries())),e?e.tickValues(i):(n.xAxis.tickValues(i),n.subXAxis.tickValues(i)),i},d.prototype.getYAxis=function(t,e,i,n,r,a,o){var s=this.owner,c=s.config,d={withOuterTick:r,withoutTransition:a,tickTextRotate:o?0:c.axis_y_tick_rotate},l=new this.internal(this,d).axis.scale(t).orient(e).tickFormat(i);return s.isTimeSeriesY()?l.ticks(c.axis_y_tick_time_type,c.axis_y_tick_time_interval):l.tickValues(n),l},d.prototype.getId=function(t){var e=this.owner.config;return t in e.data_axes?e.data_axes[t]:"y"},d.prototype.getXAxisTickFormat=function(){var e=this.owner,i=e.config,n=e.isTimeSeries()?e.defaultAxisTimeFormat:e.isCategorized()?e.categoryName:function(t){return t};return i.axis_x_tick_format&&(h(i.axis_x_tick_format)?n=i.axis_x_tick_format:e.isTimeSeries()&&(n=function(t){return t?e.axisTimeFormat(i.axis_x_tick_format)(t):""})),h(n)?function(t){return n.call(e,t)}:n},d.prototype.getTickValues=function(t,e){return t||(e?e.tickValues():void 0)},d.prototype.getXAxisTickValues=function(){return this.getTickValues(this.owner.config.axis_x_tick_values,this.owner.xAxis)},d.prototype.getYAxisTickValues=function(){return this.getTickValues(this.owner.config.axis_y_tick_values,this.owner.yAxis)},d.prototype.getY2AxisTickValues=function(){return this.getTickValues(this.owner.config.axis_y2_tick_values,this.owner.y2Axis)},d.prototype.getLabelOptionByAxisId=function(t){var e,i=this.owner.config;return"y"===t?e=i.axis_y_label:"y2"===t?e=i.axis_y2_label:"x"===t&&(e=i.axis_x_label),e},d.prototype.getLabelText=function(t){var e=this.getLabelOptionByAxisId(t);return c(e)?e:e?e.text:null},d.prototype.setLabelText=function(t,e){var i=this.owner.config,n=this.getLabelOptionByAxisId(t);c(n)?"y"===t?i.axis_y_label=e:"y2"===t?i.axis_y2_label=e:"x"===t&&(i.axis_x_label=e):n&&(n.text=e)},d.prototype.getLabelPosition=function(t,e){var i=this.getLabelOptionByAxisId(t),n=i&&"object"===s(i)&&i.position?i.position:e;return{isInner:0<=n.indexOf("inner"),isOuter:0<=n.indexOf("outer"),isLeft:0<=n.indexOf("left"),isCenter:0<=n.indexOf("center"),isRight:0<=n.indexOf("right"),isTop:0<=n.indexOf("top"),isMiddle:0<=n.indexOf("middle"),isBottom:0<=n.indexOf("bottom")}},d.prototype.getXAxisLabelPosition=function(){return this.getLabelPosition("x",this.owner.config.axis_rotated?"inner-top":"inner-right")},d.prototype.getYAxisLabelPosition=function(){return this.getLabelPosition("y",this.owner.config.axis_rotated?"inner-right":"inner-top")},d.prototype.getY2AxisLabelPosition=function(){return this.getLabelPosition("y2",this.owner.config.axis_rotated?"inner-right":"inner-top")},d.prototype.getLabelPositionById=function(t){return"y2"===t?this.getY2AxisLabelPosition():"y"===t?this.getYAxisLabelPosition():this.getXAxisLabelPosition()},d.prototype.textForXAxisLabel=function(){return this.getLabelText("x")},d.prototype.textForYAxisLabel=function(){return this.getLabelText("y")},d.prototype.textForY2AxisLabel=function(){return this.getLabelText("y2")},d.prototype.xForAxisLabel=function(t,e){var i=this.owner;return t?e.isLeft?0:e.isCenter?i.width/2:i.width:e.isBottom?-i.height:e.isMiddle?-i.height/2:0},d.prototype.dxForAxisLabel=function(t,e){return t?e.isLeft?"0.5em":e.isRight?"-0.5em":"0":e.isTop?"-0.5em":e.isBottom?"0.5em":"0"},d.prototype.textAnchorForAxisLabel=function(t,e){return t?e.isLeft?"start":e.isCenter?"middle":"end":e.isBottom?"start":e.isMiddle?"middle":"end"},d.prototype.xForXAxisLabel=function(){return this.xForAxisLabel(!this.owner.config.axis_rotated,this.getXAxisLabelPosition())},d.prototype.xForYAxisLabel=function(){return this.xForAxisLabel(this.owner.config.axis_rotated,this.getYAxisLabelPosition())},d.prototype.xForY2AxisLabel=function(){return this.xForAxisLabel(this.owner.config.axis_rotated,this.getY2AxisLabelPosition())},d.prototype.dxForXAxisLabel=function(){return this.dxForAxisLabel(!this.owner.config.axis_rotated,this.getXAxisLabelPosition())},d.prototype.dxForYAxisLabel=function(){return this.dxForAxisLabel(this.owner.config.axis_rotated,this.getYAxisLabelPosition())},d.prototype.dxForY2AxisLabel=function(){return this.dxForAxisLabel(this.owner.config.axis_rotated,this.getY2AxisLabelPosition())},d.prototype.dyForXAxisLabel=function(){var t=this.owner,e=t.config,i=this.getXAxisLabelPosition();return e.axis_rotated?i.isInner?"1.2em":-25-(t.config.axis_x_inner?0:this.getMaxTickWidth("x")):i.isInner?"-0.5em":e.axis_x_height?e.axis_x_height-10:"3em"},d.prototype.dyForYAxisLabel=function(){var t=this.owner,e=this.getYAxisLabelPosition();return t.config.axis_rotated?e.isInner?"-0.5em":"3em":e.isInner?"1.2em":-10-(t.config.axis_y_inner?0:this.getMaxTickWidth("y")+10)},d.prototype.dyForY2AxisLabel=function(){var t=this.owner,e=this.getY2AxisLabelPosition();return t.config.axis_rotated?e.isInner?"1.2em":"-2.2em":e.isInner?"-0.5em":15+(t.config.axis_y2_inner?0:this.getMaxTickWidth("y2")+15)},d.prototype.textAnchorForXAxisLabel=function(){var t=this.owner;return this.textAnchorForAxisLabel(!t.config.axis_rotated,this.getXAxisLabelPosition())},d.prototype.textAnchorForYAxisLabel=function(){var t=this.owner;return this.textAnchorForAxisLabel(t.config.axis_rotated,this.getYAxisLabelPosition())},d.prototype.textAnchorForY2AxisLabel=function(){var t=this.owner;return this.textAnchorForAxisLabel(t.config.axis_rotated,this.getY2AxisLabelPosition())},d.prototype.getMaxTickWidth=function(t,e){var i,n,r,a,o=this.owner,s=o.config,c=0;return e&&o.currentMaxTickWidths[t]||(o.svg&&(i=o.filterTargetsToShow(o.data.targets),"y"===t?(n=o.y.copy().domain(o.getYDomain(i,"y")),r=this.getYAxis(n,o.yOrient,s.axis_y_tick_format,o.yAxisTickValues,!1,!0,!0)):"y2"===t?(n=o.y2.copy().domain(o.getYDomain(i,"y2")),r=this.getYAxis(n,o.y2Orient,s.axis_y2_tick_format,o.y2AxisTickValues,!1,!0,!0)):(n=o.x.copy().domain(o.getXDomain(i)),r=this.getXAxis(n,o.xOrient,o.xAxisTickFormat,o.xAxisTickValues,!1,!0,!0),this.updateXAxisTickValues(i,r)),(a=o.d3.select("body").append("div").classed("c3",!0)).append("svg").style("visibility","hidden").style("position","fixed").style("top",0).style("left",0).append("g").call(r).each(function(){o.d3.select(this).selectAll("text").each(function(){var t=this.getBoundingClientRect();c<t.width&&(c=t.width)}),a.remove()})),o.currentMaxTickWidths[t]=c<=0?o.currentMaxTickWidths[t]:c),o.currentMaxTickWidths[t]},d.prototype.updateLabels=function(t){var e=this.owner,i=e.main.select("."+Y.axisX+" ."+Y.axisXLabel),n=e.main.select("."+Y.axisY+" ."+Y.axisYLabel),r=e.main.select("."+Y.axisY2+" ."+Y.axisY2Label);(t?i.transition():i).attr("x",this.xForXAxisLabel.bind(this)).attr("dx",this.dxForXAxisLabel.bind(this)).attr("dy",this.dyForXAxisLabel.bind(this)).text(this.textForXAxisLabel.bind(this)),(t?n.transition():n).attr("x",this.xForYAxisLabel.bind(this)).attr("dx",this.dxForYAxisLabel.bind(this)).attr("dy",this.dyForYAxisLabel.bind(this)).text(this.textForYAxisLabel.bind(this)),(t?r.transition():r).attr("x",this.xForY2AxisLabel.bind(this)).attr("dx",this.dxForY2AxisLabel.bind(this)).attr("dy",this.dyForY2AxisLabel.bind(this)).text(this.textForY2AxisLabel.bind(this))},d.prototype.getPadding=function(t,e,i,n){var r="number"==typeof t?t:t[e];return P(r)?"ratio"===t.unit?t[e]*n:this.convertPixelsToAxisPadding(r,n):i},d.prototype.convertPixelsToAxisPadding=function(t,e){var i=this.owner;return e*(t/(i.config.axis_rotated?i.width:i.height))},d.prototype.generateTickValues=function(t,e,i){var n,r,a,o,s,c,d,l=t;if(e)if(1===(n=h(e)?e():e))l=[t[0]];else if(2===n)l=[t[0],t[t.length-1]];else if(2<n){for(o=n-2,r=t[0],s=((a=t[t.length-1])-r)/(o+1),l=[r],c=0;c<o;c++)d=+r+s*(c+1),l.push(i?new Date(d):d);l.push(a)}return i||(l=l.sort(function(t,e){return t-e})),l},d.prototype.generateTransitions=function(t){var e=this.owner.axes;return{axisX:t?e.x.transition().duration(t):e.x,axisY:t?e.y.transition().duration(t):e.y,axisY2:t?e.y2.transition().duration(t):e.y2,axisSubX:t?e.subx.transition().duration(t):e.subx}},d.prototype.redraw=function(t,e){var i=this.owner,n=t?i.d3.transition().duration(t):null;i.axes.x.style("opacity",e?0:1).call(i.xAxis,n),i.axes.y.style("opacity",e?0:1).call(i.yAxis,n),i.axes.y2.style("opacity",e?0:1).call(i.y2Axis,n),i.axes.subx.style("opacity",e?0:1).call(i.subXAxis,n)};var t={version:"0.6.8",chart:{fn:n.prototype,internal:{fn:l.prototype,axis:{fn:d.prototype,internal:{fn:i.prototype}}}},generate:function(t){return new n(t)}};return l.prototype.beforeInit=function(){},l.prototype.afterInit=function(){},l.prototype.init=function(){var t=this,e=t.config;if(t.initParams(),e.data_url)t.convertUrlToData(e.data_url,e.data_mimeType,e.data_headers,e.data_keys,t.initWithData);else if(e.data_json)t.initWithData(t.convertJsonToData(e.data_json,e.data_keys));else if(e.data_rows)t.initWithData(t.convertRowsToData(e.data_rows));else{if(!e.data_columns)throw Error("url or json or rows or columns is required.");t.initWithData(t.convertColumnsToData(e.data_columns))}},l.prototype.initParams=function(){var t=this,e=t.d3,i=t.config;t.clipId="c3-"+ +new Date+"-clip",t.clipIdForXAxis=t.clipId+"-xaxis",t.clipIdForYAxis=t.clipId+"-yaxis",t.clipIdForGrid=t.clipId+"-grid",t.clipIdForSubchart=t.clipId+"-subchart",t.clipPath=t.getClipPath(t.clipId),t.clipPathForXAxis=t.getClipPath(t.clipIdForXAxis),t.clipPathForYAxis=t.getClipPath(t.clipIdForYAxis),t.clipPathForGrid=t.getClipPath(t.clipIdForGrid),t.clipPathForSubchart=t.getClipPath(t.clipIdForSubchart),t.dragStart=null,t.dragging=!1,t.flowing=!1,t.cancelClick=!1,t.mouseover=!1,t.transiting=!1,t.color=t.generateColor(),t.levelColor=t.generateLevelColor(),t.dataTimeParse=(i.data_xLocaltime?e.timeParse:e.utcParse)(t.config.data_xFormat),t.axisTimeFormat=i.axis_x_localtime?e.timeFormat:e.utcFormat,t.defaultAxisTimeFormat=function(t){return t.getMilliseconds()?e.timeFormat(".%L")(t):t.getSeconds()?e.timeFormat(":%S")(t):t.getMinutes()?e.timeFormat("%I:%M")(t):t.getHours()?e.timeFormat("%I %p")(t):t.getDay()&&1!==t.getDate()?e.timeFormat("%-m/%-d")(t):1!==t.getDate()?e.timeFormat("%-m/%-d")(t):t.getMonth()?e.timeFormat("%-m/%-d")(t):e.timeFormat("%Y/%-m/%-d")(t)},t.hiddenTargetIds=[],t.hiddenLegendIds=[],t.focusedTargetIds=[],t.defocusedTargetIds=[],t.xOrient=i.axis_rotated?i.axis_x_inner?"right":"left":i.axis_x_inner?"top":"bottom",t.yOrient=i.axis_rotated?i.axis_y_inner?"top":"bottom":i.axis_y_inner?"right":"left",t.y2Orient=i.axis_rotated?i.axis_y2_inner?"bottom":"top":i.axis_y2_inner?"left":"right",t.subXOrient=i.axis_rotated?"left":"bottom",t.isLegendRight="right"===i.legend_position,t.isLegendInset="inset"===i.legend_position,t.isLegendTop="top-left"===i.legend_inset_anchor||"top-right"===i.legend_inset_anchor,t.isLegendLeft="top-left"===i.legend_inset_anchor||"bottom-left"===i.legend_inset_anchor,t.legendStep=0,t.legendItemWidth=0,t.legendItemHeight=0,t.currentMaxTickWidths={x:0,y:0,y2:0},t.rotated_padding_left=30,t.rotated_padding_right=i.axis_rotated&&!i.axis_x_show?0:30,t.rotated_padding_top=5,t.withoutFadeIn={},t.intervalForObserveInserted=void 0,t.axes.subx=e.selectAll([])},l.prototype.initChartElements=function(){this.initBar&&this.initBar(),this.initLine&&this.initLine(),this.initArc&&this.initArc(),this.initGauge&&this.initGauge(),this.initText&&this.initText()},l.prototype.initWithData=function(t){var e,i,n=this,r=n.d3,a=n.config,o=!0;n.axis=new d(n),a.bindto?"function"==typeof a.bindto.node?n.selectChart=a.bindto:n.selectChart=r.select(a.bindto):n.selectChart=r.selectAll([]),n.selectChart.empty()&&(n.selectChart=r.select(document.createElement("div")).style("opacity",0),n.observeInserted(n.selectChart),o=!1),n.selectChart.html("").classed("c3",!0),n.data.xs={},n.data.targets=n.convertDataToTargets(t),a.data_filter&&(n.data.targets=n.data.targets.filter(a.data_filter)),a.data_hide&&n.addHiddenTargetIds(!0===a.data_hide?n.mapToIds(n.data.targets):a.data_hide),a.legend_hide&&n.addHiddenLegendIds(!0===a.legend_hide?n.mapToIds(n.data.targets):a.legend_hide),n.updateSizes(),n.updateScales(),n.x.domain(r.extent(n.getXDomain(n.data.targets))),n.y.domain(n.getYDomain(n.data.targets,"y")),n.y2.domain(n.getYDomain(n.data.targets,"y2")),n.subX.domain(n.x.domain()),n.subY.domain(n.y.domain()),n.subY2.domain(n.y2.domain()),n.orgXDomain=n.x.domain(),n.svg=n.selectChart.append("svg").style("overflow","hidden").on("mouseenter",function(){return a.onmouseover.call(n)}).on("mouseleave",function(){return a.onmouseout.call(n)}),n.config.svg_classname&&n.svg.attr("class",n.config.svg_classname),e=n.svg.append("defs"),n.clipChart=n.appendClip(e,n.clipId),n.clipXAxis=n.appendClip(e,n.clipIdForXAxis),n.clipYAxis=n.appendClip(e,n.clipIdForYAxis),n.clipGrid=n.appendClip(e,n.clipIdForGrid),n.clipSubchart=n.appendClip(e,n.clipIdForSubchart),n.updateSvgSize(),i=n.main=n.svg.append("g").attr("transform",n.getTranslate("main")),n.initPie&&n.initPie(),n.initDragZoom&&n.initDragZoom(),n.initSubchart&&n.initSubchart(),n.initTooltip&&n.initTooltip(),n.initLegend&&n.initLegend(),n.initTitle&&n.initTitle(),n.initZoom&&n.initZoom(),n.initSubchartBrush&&n.initSubchartBrush(),i.append("text").attr("class",Y.text+" "+Y.empty).attr("text-anchor","middle").attr("dominant-baseline","middle"),n.initRegion(),n.initGrid(),i.append("g").attr("clip-path",n.clipPath).attr("class",Y.chart),a.grid_lines_front&&n.initGridLines(),n.initEventRect(),n.initChartElements(),n.axis.init(),n.updateTargets(n.data.targets),a.axis_x_selection&&n.brush.selectionAsValue(n.getDefaultSelection()),o&&(n.updateDimension(),n.config.oninit.call(n),n.redraw({withTransition:!1,withTransform:!0,withUpdateXDomain:!0,withUpdateOrgXDomain:!0,withTransitionForAxis:!1})),n.bindResize(),n.api.element=n.selectChart.node()},l.prototype.smoothLines=function(t,e){var a=this;"grid"===e&&t.each(function(){var t=a.d3.select(this),e=t.attr("x1"),i=t.attr("x2"),n=t.attr("y1"),r=t.attr("y2");t.attr({x1:Math.ceil(e),x2:Math.ceil(i),y1:Math.ceil(n),y2:Math.ceil(r)})})},l.prototype.updateSizes=function(){var t=this,e=t.config,i=t.legend?t.getLegendHeight():0,n=t.legend?t.getLegendWidth():0,r=t.isLegendRight||t.isLegendInset?0:i,a=t.hasArcType(),o=e.axis_rotated||a?0:t.getHorizontalAxisHeight("x"),s=e.subchart_show&&!a?e.subchart_size_height+o:0;t.currentWidth=t.getCurrentWidth(),t.currentHeight=t.getCurrentHeight(),t.margin=e.axis_rotated?{top:t.getHorizontalAxisHeight("y2")+t.getCurrentPaddingTop(),right:a?0:t.getCurrentPaddingRight(),bottom:t.getHorizontalAxisHeight("y")+r+t.getCurrentPaddingBottom(),left:s+(a?0:t.getCurrentPaddingLeft())}:{top:4+t.getCurrentPaddingTop(),right:a?0:t.getCurrentPaddingRight(),bottom:o+s+r+t.getCurrentPaddingBottom(),left:a?0:t.getCurrentPaddingLeft()},t.margin2=e.axis_rotated?{top:t.margin.top,right:NaN,bottom:20+r,left:t.rotated_padding_left}:{top:t.currentHeight-s-r,right:NaN,bottom:o+r,left:t.margin.left},t.margin3={top:0,right:NaN,bottom:0,left:0},t.updateSizeForLegend&&t.updateSizeForLegend(i,n),t.width=t.currentWidth-t.margin.left-t.margin.right,t.height=t.currentHeight-t.margin.top-t.margin.bottom,t.width<0&&(t.width=0),t.height<0&&(t.height=0),t.width2=e.axis_rotated?t.margin.left-t.rotated_padding_left-t.rotated_padding_right:t.width,t.height2=e.axis_rotated?t.height:t.currentHeight-t.margin2.top-t.margin2.bottom,t.width2<0&&(t.width2=0),t.height2<0&&(t.height2=0),t.arcWidth=t.width-(t.isLegendRight?n+10:0),t.arcHeight=t.height-(t.isLegendRight?0:10),t.hasType("gauge")&&!e.gauge_fullCircle&&(t.arcHeight+=t.height-t.getGaugeLabelHeight()),t.updateRadius&&t.updateRadius(),t.isLegendRight&&a&&(t.margin3.left=t.arcWidth/2+1.1*t.radiusExpanded)},l.prototype.updateTargets=function(t){var e=this;e.updateTargetsForText(t),e.updateTargetsForBar(t),e.updateTargetsForLine(t),e.hasArcType()&&e.updateTargetsForArc&&e.updateTargetsForArc(t),e.updateTargetsForSubchart&&e.updateTargetsForSubchart(t),e.showTargets()},l.prototype.showTargets=function(){var e=this;e.svg.selectAll("."+Y.target).filter(function(t){return e.isTargetToShow(t.id)}).transition().duration(e.config.transition_duration).style("opacity",1)},l.prototype.redraw=function(t,e){var i,n,r,a,o,s,c,d,l,u,h,g,p,f,_,x,y,m,S,w,v,b,A,T,P,C,L,V,G,E,I,O=this,R=O.main,k=O.d3,D=O.config,F=O.getShapeIndices(O.isAreaType),X=O.getShapeIndices(O.isBarType),M=O.getShapeIndices(O.isLineType),z=O.hasArcType(),H=O.filterTargetsToShow(O.data.targets),B=O.xv.bind(O);if(i=N(t=t||{},"withY",!0),n=N(t,"withSubchart",!0),r=N(t,"withTransition",!0),s=N(t,"withTransform",!1),c=N(t,"withUpdateXDomain",!1),d=N(t,"withUpdateOrgXDomain",!1),l=N(t,"withTrimXDomain",!0),p=N(t,"withUpdateXAxis",c),u=N(t,"withLegend",!1),h=N(t,"withEventRect",!0),g=N(t,"withDimension",!0),a=N(t,"withTransitionForExit",r),o=N(t,"withTransitionForAxis",r),S=r?D.transition_duration:0,w=a?S:0,v=o?S:0,e=e||O.axis.generateTransitions(v),u&&D.legend_show?O.updateLegend(O.mapToIds(O.data.targets),t,e):g&&O.updateDimension(!0),O.isCategorized()&&0===H.length&&O.x.domain([0,O.axes.x.selectAll(".tick").size()]),H.length?(O.updateXDomain(H,c,d,l),D.axis_x_tick_values||(C=O.axis.updateXAxisTickValues(H))):(O.xAxis.tickValues([]),O.subXAxis.tickValues([])),D.zoom_rescale&&!t.flow&&(G=O.x.orgDomain()),O.y.domain(O.getYDomain(H,"y",G)),O.y2.domain(O.getYDomain(H,"y2",G)),!D.axis_y_tick_values&&D.axis_y_tick_count&&O.yAxis.tickValues(O.axis.generateTickValues(O.y.domain(),D.axis_y_tick_count)),!D.axis_y2_tick_values&&D.axis_y2_tick_count&&O.y2Axis.tickValues(O.axis.generateTickValues(O.y2.domain(),D.axis_y2_tick_count)),O.axis.redraw(v,z),O.axis.updateLabels(r),(c||p)&&H.length)if(D.axis_x_tick_culling&&C){for(L=1;L<C.length;L++)if(C.length/L<D.axis_x_tick_culling_max){V=L;break}O.svg.selectAll("."+Y.axisX+" .tick text").each(function(t){var e=C.indexOf(t);0<=e&&k.select(this).style("display",e%V?"none":"block")})}else O.svg.selectAll("."+Y.axisX+" .tick text").style("display","block");f=O.generateDrawArea?O.generateDrawArea(F,!1):void 0,_=O.generateDrawBar?O.generateDrawBar(X):void 0,x=O.generateDrawLine?O.generateDrawLine(M,!1):void 0,y=O.generateXYForText(F,X,M,!0),m=O.generateXYForText(F,X,M,!1),O.updateCircleY(),E=(O.config.axis_rotated?O.circleY:O.circleX).bind(O),I=(O.config.axis_rotated?O.circleX:O.circleY).bind(O),i&&(O.subY.domain(O.getYDomain(H,"y")),O.subY2.domain(O.getYDomain(H,"y2"))),O.updateXgridFocus(),R.select("text."+Y.text+"."+Y.empty).attr("x",O.width/2).attr("y",O.height/2).text(D.data_empty_label_text).transition().style("opacity",H.length?0:1),h&&O.redrawEventRect(),O.updateGrid(S),O.updateRegion(S),O.updateBar(w),O.updateLine(w),O.updateArea(w),O.updateCircle(E,I),O.hasDataLabel()&&O.updateText(y,m,w),O.redrawTitle&&O.redrawTitle(),O.redrawArc&&O.redrawArc(S,w,s),O.redrawSubchart&&O.redrawSubchart(n,e,S,w,F,X,M),R.selectAll("."+Y.selectedCircles).filter(O.isBarType.bind(O)).selectAll("circle").remove(),t.flow&&(T=O.generateFlow({targets:H,flow:t.flow,duration:t.flow.duration,drawBar:_,drawLine:x,drawArea:f,cx:E,cy:I,xv:B,xForText:y,yForText:m})),O.isTabVisible()&&(S?(P=k.transition().duration(S),b=[],[O.redrawBar(_,!0,P),O.redrawLine(x,!0,P),O.redrawArea(f,!0,P),O.redrawCircle(E,I,!0,P),O.redrawText(y,m,t.flow,!0,P),O.redrawRegion(!0,P),O.redrawGrid(!0,P)].forEach(function(t){t.forEach(function(t){b.push(t)})}),A=O.generateWait(),b.forEach(function(t){A.add(t)}),A(function(){T&&T(),D.onrendered&&D.onrendered.call(O)})):(O.redrawBar(_),O.redrawLine(x),O.redrawArea(f),O.redrawCircle(E,I),O.redrawText(y,m,t.flow),O.redrawRegion(),O.redrawGrid(),T&&T(),D.onrendered&&D.onrendered.call(O))),O.mapToIds(O.data.targets).forEach(function(t){O.withoutFadeIn[t]=!0})},l.prototype.updateAndRedraw=function(t){var e,i=this,n=i.config;(t=t||{}).withTransition=N(t,"withTransition",!0),t.withTransform=N(t,"withTransform",!1),t.withLegend=N(t,"withLegend",!1),t.withUpdateXDomain=N(t,"withUpdateXDomain",!0),t.withUpdateOrgXDomain=N(t,"withUpdateOrgXDomain",!0),t.withTransitionForExit=!1,t.withTransitionForTransform=N(t,"withTransitionForTransform",t.withTransition),i.updateSizes(),t.withLegend&&n.legend_show||(e=i.axis.generateTransitions(t.withTransitionForAxis?n.transition_duration:0),i.updateScales(),i.updateSvgSize(),i.transformAll(t.withTransitionForTransform,e)),i.redraw(t,e)},l.prototype.redrawWithoutRescale=function(){this.redraw({withY:!1,withSubchart:!1,withEventRect:!1,withTransitionForAxis:!1})},l.prototype.isTimeSeries=function(){return"timeseries"===this.config.axis_x_type},l.prototype.isCategorized=function(){return 0<=this.config.axis_x_type.indexOf("categor")},l.prototype.isCustomX=function(){var t=this.config;return!this.isTimeSeries()&&(t.data_x||C(t.data_xs))},l.prototype.isTimeSeriesY=function(){return"timeseries"===this.config.axis_y_type},l.prototype.getTranslate=function(t){var e,i,n=this,r=n.config;return"main"===t?(e=a(n.margin.left),i=a(n.margin.top)):"context"===t?(e=a(n.margin2.left),i=a(n.margin2.top)):"legend"===t?(e=n.margin3.left,i=n.margin3.top):"x"===t?(e=0,i=r.axis_rotated?0:n.height):"y"===t?(e=0,i=r.axis_rotated?n.height:0):"y2"===t?(e=r.axis_rotated?0:n.width,i=r.axis_rotated?1:0):"subx"===t?(e=0,i=r.axis_rotated?0:n.height2):"arc"===t&&(e=n.arcWidth/2,i=n.arcHeight/2-(n.hasType("gauge")?6:0)),"translate("+e+","+i+")"},l.prototype.initialOpacity=function(t){return null!==t.value&&this.withoutFadeIn[t.id]?1:0},l.prototype.initialOpacityForCircle=function(t){return null!==t.value&&this.withoutFadeIn[t.id]?this.opacityForCircle(t):0},l.prototype.opacityForCircle=function(t){var e=(h(this.config.point_show)?this.config.point_show(t):this.config.point_show)?1:0;return P(t.value)?this.isScatterType(t)?.5:e:0},l.prototype.opacityForText=function(){return this.hasDataLabel()?1:0},l.prototype.xx=function(t){return t?this.x(t.x):null},l.prototype.xv=function(t){var e=this,i=t.value;return e.isTimeSeries()?i=e.parseDate(t.value):e.isCategorized()&&"string"==typeof t.value&&(i=e.config.axis_x_categories.indexOf(t.value)),Math.ceil(e.x(i))},l.prototype.yv=function(t){var e=t.axis&&"y2"===t.axis?this.y2:this.y;return Math.ceil(e(t.value))},l.prototype.subxx=function(t){return t?this.subX(t.x):null},l.prototype.transformMain=function(t,e){var i,n,r,a=this;e&&e.axisX?i=e.axisX:(i=a.main.select("."+Y.axisX),t&&(i=i.transition())),e&&e.axisY?n=e.axisY:(n=a.main.select("."+Y.axisY),t&&(n=n.transition())),e&&e.axisY2?r=e.axisY2:(r=a.main.select("."+Y.axisY2),t&&(r=r.transition())),(t?a.main.transition():a.main).attr("transform",a.getTranslate("main")),i.attr("transform",a.getTranslate("x")),n.attr("transform",a.getTranslate("y")),r.attr("transform",a.getTranslate("y2")),a.main.select("."+Y.chartArcs).attr("transform",a.getTranslate("arc"))},l.prototype.transformAll=function(t,e){var i=this;i.transformMain(t,e),i.config.subchart_show&&i.transformContext(t,e),i.legend&&i.transformLegend(t)},l.prototype.updateSvgSize=function(){var t=this,e=t.svg.select(".c3-brush .overlay");t.svg.attr("width",t.currentWidth).attr("height",t.currentHeight),t.svg.selectAll(["#"+t.clipId,"#"+t.clipIdForGrid]).select("rect").attr("width",t.width).attr("height",t.height),t.svg.select("#"+t.clipIdForXAxis).select("rect").attr("x",t.getXAxisClipX.bind(t)).attr("y",t.getXAxisClipY.bind(t)).attr("width",t.getXAxisClipWidth.bind(t)).attr("height",t.getXAxisClipHeight.bind(t)),t.svg.select("#"+t.clipIdForYAxis).select("rect").attr("x",t.getYAxisClipX.bind(t)).attr("y",t.getYAxisClipY.bind(t)).attr("width",t.getYAxisClipWidth.bind(t)).attr("height",t.getYAxisClipHeight.bind(t)),t.svg.select("#"+t.clipIdForSubchart).select("rect").attr("width",t.width).attr("height",e.size()?e.attr("height"):0),t.selectChart.style("max-height",t.currentHeight+"px")},l.prototype.updateDimension=function(t){var e=this;t||(e.config.axis_rotated?(e.axes.x.call(e.xAxis),e.axes.subx.call(e.subXAxis)):(e.axes.y.call(e.yAxis),e.axes.y2.call(e.y2Axis))),e.updateSizes(),e.updateScales(),e.updateSvgSize(),e.transformAll(!1)},l.prototype.observeInserted=function(e){var i,n=this;"undefined"!=typeof MutationObserver?(i=new MutationObserver(function(t){t.forEach(function(t){"childList"===t.type&&t.previousSibling&&(i.disconnect(),n.intervalForObserveInserted=window.setInterval(function(){e.node().parentNode&&(window.clearInterval(n.intervalForObserveInserted),n.updateDimension(),n.brush&&n.brush.update(),n.config.oninit.call(n),n.redraw({withTransform:!0,withUpdateXDomain:!0,withUpdateOrgXDomain:!0,withTransition:!1,withTransitionForTransform:!1,withLegend:!0}),e.transition().style("opacity",1))},10))})})).observe(e.node(),{attributes:!0,childList:!0,characterData:!0}):window.console.error("MutationObserver not defined.")},l.prototype.bindResize=function(){var t=this,e=t.config;if(t.resizeFunction=t.generateResize(),t.resizeFunction.add(function(){e.onresize.call(t)}),e.resize_auto&&t.resizeFunction.add(function(){void 0!==t.resizeTimeout&&window.clearTimeout(t.resizeTimeout),t.resizeTimeout=window.setTimeout(function(){delete t.resizeTimeout,t.updateAndRedraw({withUpdateXDomain:!1,withUpdateOrgXDomain:!1,withTransition:!1,withTransitionForTransform:!1,withLegend:!0}),t.brush&&t.brush.update()},100)}),t.resizeFunction.add(function(){e.onresized.call(t)}),t.resizeIfElementDisplayed=function(){null!=t.api&&t.api.element.offsetParent&&t.resizeFunction()},window.attachEvent)window.attachEvent("onresize",t.resizeIfElementDisplayed);else if(window.addEventListener)window.addEventListener("resize",t.resizeIfElementDisplayed,!1);else{var i=window.onresize;i?i.add&&i.remove||(i=t.generateResize()).add(window.onresize):i=t.generateResize(),i.add(t.resizeFunction),window.onresize=function(){t.api.element.offsetParent&&i()}}},l.prototype.generateResize=function(){var i=[];function t(){i.forEach(function(t){t()})}return t.add=function(t){i.push(t)},t.remove=function(t){for(var e=0;e<i.length;e++)if(i[e]===t){i.splice(e,1);break}},t},l.prototype.endall=function(t,e){var i=0;t.each(function(){++i}).on("end",function(){--i||e.apply(this,arguments)})},l.prototype.generateWait=function(){var n=[],t=function(t){var i=setInterval(function(){var e=0;n.forEach(function(t){if(t.empty())e+=1;else try{t.transition()}catch(t){e+=1}}),e===n.length&&(clearInterval(i),t&&t())},50)};return t.add=function(t){n.push(t)},t},l.prototype.parseDate=function(t){var e;return t instanceof Date?e=t:"string"==typeof t?e=this.dataTimeParse(t):"object"===s(t)?e=new Date(+t):"number"!=typeof t||isNaN(t)||(e=new Date(+t)),e&&!isNaN(+e)||window.console.error("Failed to parse x '"+t+"' to Date object"),e},l.prototype.isTabVisible=function(){var t;return void 0!==document.hidden?t="hidden":void 0!==document.mozHidden?t="mozHidden":void 0!==document.msHidden?t="msHidden":void 0!==document.webkitHidden&&(t="webkitHidden"),!document[t]},l.prototype.getPathBox=y,l.prototype.CLASS=Y,"SVGPathSeg"in window||(window.SVGPathSeg=function(t,e,i){this.pathSegType=t,this.pathSegTypeAsLetter=e,this._owningPathSegList=i},window.SVGPathSeg.prototype.classname="SVGPathSeg",window.SVGPathSeg.PATHSEG_UNKNOWN=0,window.SVGPathSeg.PATHSEG_CLOSEPATH=1,window.SVGPathSeg.PATHSEG_MOVETO_ABS=2,window.SVGPathSeg.PATHSEG_MOVETO_REL=3,window.SVGPathSeg.PATHSEG_LINETO_ABS=4,window.SVGPathSeg.PATHSEG_LINETO_REL=5,window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS=6,window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL=7,window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS=8,window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL=9,window.SVGPathSeg.PATHSEG_ARC_ABS=10,window.SVGPathSeg.PATHSEG_ARC_REL=11,window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS=12,window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL=13,window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS=14,window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL=15,window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS=16,window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL=17,window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS=18,window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL=19,window.SVGPathSeg.prototype._segmentChanged=function(){this._owningPathSegList&&this._owningPathSegList.segmentChanged(this)},window.SVGPathSegClosePath=function(t){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_CLOSEPATH,"z",t)},window.SVGPathSegClosePath.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegClosePath.prototype.toString=function(){return"[object SVGPathSegClosePath]"},window.SVGPathSegClosePath.prototype._asPathString=function(){return this.pathSegTypeAsLetter},window.SVGPathSegClosePath.prototype.clone=function(){return new window.SVGPathSegClosePath(void 0)},window.SVGPathSegMovetoAbs=function(t,e,i){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_MOVETO_ABS,"M",t),this._x=e,this._y=i},window.SVGPathSegMovetoAbs.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegMovetoAbs.prototype.toString=function(){return"[object SVGPathSegMovetoAbs]"},window.SVGPathSegMovetoAbs.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x+" "+this._y},window.SVGPathSegMovetoAbs.prototype.clone=function(){return new window.SVGPathSegMovetoAbs(void 0,this._x,this._y)},Object.defineProperty(window.SVGPathSegMovetoAbs.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegMovetoAbs.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegMovetoRel=function(t,e,i){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_MOVETO_REL,"m",t),this._x=e,this._y=i},window.SVGPathSegMovetoRel.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegMovetoRel.prototype.toString=function(){return"[object SVGPathSegMovetoRel]"},window.SVGPathSegMovetoRel.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x+" "+this._y},window.SVGPathSegMovetoRel.prototype.clone=function(){return new window.SVGPathSegMovetoRel(void 0,this._x,this._y)},Object.defineProperty(window.SVGPathSegMovetoRel.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegMovetoRel.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegLinetoAbs=function(t,e,i){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_LINETO_ABS,"L",t),this._x=e,this._y=i},window.SVGPathSegLinetoAbs.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegLinetoAbs.prototype.toString=function(){return"[object SVGPathSegLinetoAbs]"},window.SVGPathSegLinetoAbs.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x+" "+this._y},window.SVGPathSegLinetoAbs.prototype.clone=function(){return new window.SVGPathSegLinetoAbs(void 0,this._x,this._y)},Object.defineProperty(window.SVGPathSegLinetoAbs.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegLinetoAbs.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegLinetoRel=function(t,e,i){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_LINETO_REL,"l",t),this._x=e,this._y=i},window.SVGPathSegLinetoRel.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegLinetoRel.prototype.toString=function(){return"[object SVGPathSegLinetoRel]"},window.SVGPathSegLinetoRel.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x+" "+this._y},window.SVGPathSegLinetoRel.prototype.clone=function(){return new window.SVGPathSegLinetoRel(void 0,this._x,this._y)},Object.defineProperty(window.SVGPathSegLinetoRel.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegLinetoRel.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegCurvetoCubicAbs=function(t,e,i,n,r,a,o){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS,"C",t),this._x=e,this._y=i,this._x1=n,this._y1=r,this._x2=a,this._y2=o},window.SVGPathSegCurvetoCubicAbs.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegCurvetoCubicAbs.prototype.toString=function(){return"[object SVGPathSegCurvetoCubicAbs]"},window.SVGPathSegCurvetoCubicAbs.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x1+" "+this._y1+" "+this._x2+" "+this._y2+" "+this._x+" "+this._y},window.SVGPathSegCurvetoCubicAbs.prototype.clone=function(){return new window.SVGPathSegCurvetoCubicAbs(void 0,this._x,this._y,this._x1,this._y1,this._x2,this._y2)},Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype,"x1",{get:function(){return this._x1},set:function(t){this._x1=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype,"y1",{get:function(){return this._y1},set:function(t){this._y1=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype,"x2",{get:function(){return this._x2},set:function(t){this._x2=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype,"y2",{get:function(){return this._y2},set:function(t){this._y2=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegCurvetoCubicRel=function(t,e,i,n,r,a,o){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL,"c",t),this._x=e,this._y=i,this._x1=n,this._y1=r,this._x2=a,this._y2=o},window.SVGPathSegCurvetoCubicRel.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegCurvetoCubicRel.prototype.toString=function(){return"[object SVGPathSegCurvetoCubicRel]"},window.SVGPathSegCurvetoCubicRel.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x1+" "+this._y1+" "+this._x2+" "+this._y2+" "+this._x+" "+this._y},window.SVGPathSegCurvetoCubicRel.prototype.clone=function(){return new window.SVGPathSegCurvetoCubicRel(void 0,this._x,this._y,this._x1,this._y1,this._x2,this._y2)},Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype,"x1",{get:function(){return this._x1},set:function(t){this._x1=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype,"y1",{get:function(){return this._y1},set:function(t){this._y1=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype,"x2",{get:function(){return this._x2},set:function(t){this._x2=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype,"y2",{get:function(){return this._y2},set:function(t){this._y2=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegCurvetoQuadraticAbs=function(t,e,i,n,r){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS,"Q",t),this._x=e,this._y=i,this._x1=n,this._y1=r},window.SVGPathSegCurvetoQuadraticAbs.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegCurvetoQuadraticAbs.prototype.toString=function(){return"[object SVGPathSegCurvetoQuadraticAbs]"},window.SVGPathSegCurvetoQuadraticAbs.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x1+" "+this._y1+" "+this._x+" "+this._y},window.SVGPathSegCurvetoQuadraticAbs.prototype.clone=function(){return new window.SVGPathSegCurvetoQuadraticAbs(void 0,this._x,this._y,this._x1,this._y1)},Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype,"x1",{get:function(){return this._x1},set:function(t){this._x1=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype,"y1",{get:function(){return this._y1},set:function(t){this._y1=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegCurvetoQuadraticRel=function(t,e,i,n,r){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL,"q",t),this._x=e,this._y=i,this._x1=n,this._y1=r},window.SVGPathSegCurvetoQuadraticRel.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegCurvetoQuadraticRel.prototype.toString=function(){return"[object SVGPathSegCurvetoQuadraticRel]"},window.SVGPathSegCurvetoQuadraticRel.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x1+" "+this._y1+" "+this._x+" "+this._y},window.SVGPathSegCurvetoQuadraticRel.prototype.clone=function(){return new window.SVGPathSegCurvetoQuadraticRel(void 0,this._x,this._y,this._x1,this._y1)},Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype,"x1",{get:function(){return this._x1},set:function(t){this._x1=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype,"y1",{get:function(){return this._y1},set:function(t){this._y1=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegArcAbs=function(t,e,i,n,r,a,o,s){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_ARC_ABS,"A",t),this._x=e,this._y=i,this._r1=n,this._r2=r,this._angle=a,this._largeArcFlag=o,this._sweepFlag=s},window.SVGPathSegArcAbs.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegArcAbs.prototype.toString=function(){return"[object SVGPathSegArcAbs]"},window.SVGPathSegArcAbs.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._r1+" "+this._r2+" "+this._angle+" "+(this._largeArcFlag?"1":"0")+" "+(this._sweepFlag?"1":"0")+" "+this._x+" "+this._y},window.SVGPathSegArcAbs.prototype.clone=function(){return new window.SVGPathSegArcAbs(void 0,this._x,this._y,this._r1,this._r2,this._angle,this._largeArcFlag,this._sweepFlag)},Object.defineProperty(window.SVGPathSegArcAbs.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegArcAbs.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegArcAbs.prototype,"r1",{get:function(){return this._r1},set:function(t){this._r1=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegArcAbs.prototype,"r2",{get:function(){return this._r2},set:function(t){this._r2=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegArcAbs.prototype,"angle",{get:function(){return this._angle},set:function(t){this._angle=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegArcAbs.prototype,"largeArcFlag",{get:function(){return this._largeArcFlag},set:function(t){this._largeArcFlag=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegArcAbs.prototype,"sweepFlag",{get:function(){return this._sweepFlag},set:function(t){this._sweepFlag=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegArcRel=function(t,e,i,n,r,a,o,s){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_ARC_REL,"a",t),this._x=e,this._y=i,this._r1=n,this._r2=r,this._angle=a,this._largeArcFlag=o,this._sweepFlag=s},window.SVGPathSegArcRel.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegArcRel.prototype.toString=function(){return"[object SVGPathSegArcRel]"},window.SVGPathSegArcRel.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._r1+" "+this._r2+" "+this._angle+" "+(this._largeArcFlag?"1":"0")+" "+(this._sweepFlag?"1":"0")+" "+this._x+" "+this._y},window.SVGPathSegArcRel.prototype.clone=function(){return new window.SVGPathSegArcRel(void 0,this._x,this._y,this._r1,this._r2,this._angle,this._largeArcFlag,this._sweepFlag)},Object.defineProperty(window.SVGPathSegArcRel.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegArcRel.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegArcRel.prototype,"r1",{get:function(){return this._r1},set:function(t){this._r1=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegArcRel.prototype,"r2",{get:function(){return this._r2},set:function(t){this._r2=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegArcRel.prototype,"angle",{get:function(){return this._angle},set:function(t){this._angle=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegArcRel.prototype,"largeArcFlag",{get:function(){return this._largeArcFlag},set:function(t){this._largeArcFlag=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegArcRel.prototype,"sweepFlag",{get:function(){return this._sweepFlag},set:function(t){this._sweepFlag=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegLinetoHorizontalAbs=function(t,e){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS,"H",t),this._x=e},window.SVGPathSegLinetoHorizontalAbs.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegLinetoHorizontalAbs.prototype.toString=function(){return"[object SVGPathSegLinetoHorizontalAbs]"},window.SVGPathSegLinetoHorizontalAbs.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x},window.SVGPathSegLinetoHorizontalAbs.prototype.clone=function(){return new window.SVGPathSegLinetoHorizontalAbs(void 0,this._x)},Object.defineProperty(window.SVGPathSegLinetoHorizontalAbs.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegLinetoHorizontalRel=function(t,e){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL,"h",t),this._x=e},window.SVGPathSegLinetoHorizontalRel.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegLinetoHorizontalRel.prototype.toString=function(){return"[object SVGPathSegLinetoHorizontalRel]"},window.SVGPathSegLinetoHorizontalRel.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x},window.SVGPathSegLinetoHorizontalRel.prototype.clone=function(){return new window.SVGPathSegLinetoHorizontalRel(void 0,this._x)},Object.defineProperty(window.SVGPathSegLinetoHorizontalRel.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegLinetoVerticalAbs=function(t,e){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS,"V",t),this._y=e},window.SVGPathSegLinetoVerticalAbs.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegLinetoVerticalAbs.prototype.toString=function(){return"[object SVGPathSegLinetoVerticalAbs]"},window.SVGPathSegLinetoVerticalAbs.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._y},window.SVGPathSegLinetoVerticalAbs.prototype.clone=function(){return new window.SVGPathSegLinetoVerticalAbs(void 0,this._y)},Object.defineProperty(window.SVGPathSegLinetoVerticalAbs.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegLinetoVerticalRel=function(t,e){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL,"v",t),this._y=e},window.SVGPathSegLinetoVerticalRel.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegLinetoVerticalRel.prototype.toString=function(){return"[object SVGPathSegLinetoVerticalRel]"},window.SVGPathSegLinetoVerticalRel.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._y},window.SVGPathSegLinetoVerticalRel.prototype.clone=function(){return new window.SVGPathSegLinetoVerticalRel(void 0,this._y)},Object.defineProperty(window.SVGPathSegLinetoVerticalRel.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegCurvetoCubicSmoothAbs=function(t,e,i,n,r){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS,"S",t),this._x=e,this._y=i,this._x2=n,this._y2=r},window.SVGPathSegCurvetoCubicSmoothAbs.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegCurvetoCubicSmoothAbs.prototype.toString=function(){return"[object SVGPathSegCurvetoCubicSmoothAbs]"},window.SVGPathSegCurvetoCubicSmoothAbs.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x2+" "+this._y2+" "+this._x+" "+this._y},window.SVGPathSegCurvetoCubicSmoothAbs.prototype.clone=function(){return new window.SVGPathSegCurvetoCubicSmoothAbs(void 0,this._x,this._y,this._x2,this._y2)},Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothAbs.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothAbs.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothAbs.prototype,"x2",{get:function(){return this._x2},set:function(t){this._x2=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothAbs.prototype,"y2",{get:function(){return this._y2},set:function(t){this._y2=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegCurvetoCubicSmoothRel=function(t,e,i,n,r){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL,"s",t),this._x=e,this._y=i,this._x2=n,this._y2=r},window.SVGPathSegCurvetoCubicSmoothRel.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegCurvetoCubicSmoothRel.prototype.toString=function(){return"[object SVGPathSegCurvetoCubicSmoothRel]"},window.SVGPathSegCurvetoCubicSmoothRel.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x2+" "+this._y2+" "+this._x+" "+this._y},window.SVGPathSegCurvetoCubicSmoothRel.prototype.clone=function(){return new window.SVGPathSegCurvetoCubicSmoothRel(void 0,this._x,this._y,this._x2,this._y2)},Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothRel.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothRel.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothRel.prototype,"x2",{get:function(){return this._x2},set:function(t){this._x2=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothRel.prototype,"y2",{get:function(){return this._y2},set:function(t){this._y2=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegCurvetoQuadraticSmoothAbs=function(t,e,i){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS,"T",t),this._x=e,this._y=i},window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype.toString=function(){return"[object SVGPathSegCurvetoQuadraticSmoothAbs]"},window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x+" "+this._y},window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype.clone=function(){return new window.SVGPathSegCurvetoQuadraticSmoothAbs(void 0,this._x,this._y)},Object.defineProperty(window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),window.SVGPathSegCurvetoQuadraticSmoothRel=function(t,e,i){window.SVGPathSeg.call(this,window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL,"t",t),this._x=e,this._y=i},window.SVGPathSegCurvetoQuadraticSmoothRel.prototype=Object.create(window.SVGPathSeg.prototype),window.SVGPathSegCurvetoQuadraticSmoothRel.prototype.toString=function(){return"[object SVGPathSegCurvetoQuadraticSmoothRel]"},window.SVGPathSegCurvetoQuadraticSmoothRel.prototype._asPathString=function(){return this.pathSegTypeAsLetter+" "+this._x+" "+this._y},window.SVGPathSegCurvetoQuadraticSmoothRel.prototype.clone=function(){return new window.SVGPathSegCurvetoQuadraticSmoothRel(void 0,this._x,this._y)},Object.defineProperty(window.SVGPathSegCurvetoQuadraticSmoothRel.prototype,"x",{get:function(){return this._x},set:function(t){this._x=t,this._segmentChanged()},enumerable:!0}),Object.defineProperty(window.SVGPathSegCurvetoQuadraticSmoothRel.prototype,"y",{get:function(){return this._y},set:function(t){this._y=t,this._segmentChanged()},enumerable:!0}),window.SVGPathElement.prototype.createSVGPathSegClosePath=function(){return new window.SVGPathSegClosePath(void 0)},window.SVGPathElement.prototype.createSVGPathSegMovetoAbs=function(t,e){return new window.SVGPathSegMovetoAbs(void 0,t,e)},window.SVGPathElement.prototype.createSVGPathSegMovetoRel=function(t,e){return new window.SVGPathSegMovetoRel(void 0,t,e)},window.SVGPathElement.prototype.createSVGPathSegLinetoAbs=function(t,e){return new window.SVGPathSegLinetoAbs(void 0,t,e)},window.SVGPathElement.prototype.createSVGPathSegLinetoRel=function(t,e){return new window.SVGPathSegLinetoRel(void 0,t,e)},window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicAbs=function(t,e,i,n,r,a){return new window.SVGPathSegCurvetoCubicAbs(void 0,t,e,i,n,r,a)},window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicRel=function(t,e,i,n,r,a){return new window.SVGPathSegCurvetoCubicRel(void 0,t,e,i,n,r,a)},window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticAbs=function(t,e,i,n){return new window.SVGPathSegCurvetoQuadraticAbs(void 0,t,e,i,n)},window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticRel=function(t,e,i,n){return new window.SVGPathSegCurvetoQuadraticRel(void 0,t,e,i,n)},window.SVGPathElement.prototype.createSVGPathSegArcAbs=function(t,e,i,n,r,a,o){return new window.SVGPathSegArcAbs(void 0,t,e,i,n,r,a,o)},window.SVGPathElement.prototype.createSVGPathSegArcRel=function(t,e,i,n,r,a,o){return new window.SVGPathSegArcRel(void 0,t,e,i,n,r,a,o)},window.SVGPathElement.prototype.createSVGPathSegLinetoHorizontalAbs=function(t){return new window.SVGPathSegLinetoHorizontalAbs(void 0,t)},window.SVGPathElement.prototype.createSVGPathSegLinetoHorizontalRel=function(t){return new window.SVGPathSegLinetoHorizontalRel(void 0,t)},window.SVGPathElement.prototype.createSVGPathSegLinetoVerticalAbs=function(t){return new window.SVGPathSegLinetoVerticalAbs(void 0,t)},window.SVGPathElement.prototype.createSVGPathSegLinetoVerticalRel=function(t){return new window.SVGPathSegLinetoVerticalRel(void 0,t)},window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothAbs=function(t,e,i,n){return new window.SVGPathSegCurvetoCubicSmoothAbs(void 0,t,e,i,n)},window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothRel=function(t,e,i,n){return new window.SVGPathSegCurvetoCubicSmoothRel(void 0,t,e,i,n)},window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothAbs=function(t,e){return new window.SVGPathSegCurvetoQuadraticSmoothAbs(void 0,t,e)},window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothRel=function(t,e){return new window.SVGPathSegCurvetoQuadraticSmoothRel(void 0,t,e)},"getPathSegAtLength"in window.SVGPathElement.prototype||(window.SVGPathElement.prototype.getPathSegAtLength=function(t){if(void 0===t||!isFinite(t))throw"Invalid arguments.";var e=document.createElementNS("http://www.w3.org/2000/svg","path");e.setAttribute("d",this.getAttribute("d"));var i=e.pathSegList.numberOfItems-1;if(i<=0)return 0;do{if(e.pathSegList.removeItem(i),t>e.getTotalLength())break;i--}while(0<i);return i})),"SVGPathSegList"in window||(window.SVGPathSegList=function(t){this._pathElement=t,this._list=this._parsePath(this._pathElement.getAttribute("d")),this._mutationObserverConfig={attributes:!0,attributeFilter:["d"]},this._pathElementMutationObserver=new MutationObserver(this._updateListFromPathMutations.bind(this)),this._pathElementMutationObserver.observe(this._pathElement,this._mutationObserverConfig)},window.SVGPathSegList.prototype.classname="SVGPathSegList",Object.defineProperty(window.SVGPathSegList.prototype,"numberOfItems",{get:function(){return this._checkPathSynchronizedToList(),this._list.length},enumerable:!0}),Object.defineProperty(window.SVGPathElement.prototype,"pathSegList",{get:function(){return this._pathSegList||(this._pathSegList=new window.SVGPathSegList(this)),this._pathSegList},enumerable:!0}),Object.defineProperty(window.SVGPathElement.prototype,"normalizedPathSegList",{get:function(){return this.pathSegList},enumerable:!0}),Object.defineProperty(window.SVGPathElement.prototype,"animatedPathSegList",{get:function(){return this.pathSegList},enumerable:!0}),Object.defineProperty(window.SVGPathElement.prototype,"animatedNormalizedPathSegList",{get:function(){return this.pathSegList},enumerable:!0}),window.SVGPathSegList.prototype._checkPathSynchronizedToList=function(){this._updateListFromPathMutations(this._pathElementMutationObserver.takeRecords())},window.SVGPathSegList.prototype._updateListFromPathMutations=function(t){if(this._pathElement){var e=!1;t.forEach(function(t){"d"==t.attributeName&&(e=!0)}),e&&(this._list=this._parsePath(this._pathElement.getAttribute("d")))}},window.SVGPathSegList.prototype._writeListToPath=function(){this._pathElementMutationObserver.disconnect(),this._pathElement.setAttribute("d",window.SVGPathSegList._pathSegArrayAsString(this._list)),this._pathElementMutationObserver.observe(this._pathElement,this._mutationObserverConfig)},window.SVGPathSegList.prototype.segmentChanged=function(t){this._writeListToPath()},window.SVGPathSegList.prototype.clear=function(){this._checkPathSynchronizedToList(),this._list.forEach(function(t){t._owningPathSegList=null}),this._list=[],this._writeListToPath()},window.SVGPathSegList.prototype.initialize=function(t){return this._checkPathSynchronizedToList(),this._list=[t],(t._owningPathSegList=this)._writeListToPath(),t},window.SVGPathSegList.prototype._checkValidIndex=function(t){if(isNaN(t)||t<0||t>=this.numberOfItems)throw"INDEX_SIZE_ERR"},window.SVGPathSegList.prototype.getItem=function(t){return this._checkPathSynchronizedToList(),this._checkValidIndex(t),this._list[t]},window.SVGPathSegList.prototype.insertItemBefore=function(t,e){return this._checkPathSynchronizedToList(),e>this.numberOfItems&&(e=this.numberOfItems),t._owningPathSegList&&(t=t.clone()),this._list.splice(e,0,t),(t._owningPathSegList=this)._writeListToPath(),t},window.SVGPathSegList.prototype.replaceItem=function(t,e){return this._checkPathSynchronizedToList(),t._owningPathSegList&&(t=t.clone()),this._checkValidIndex(e),((this._list[e]=t)._owningPathSegList=this)._writeListToPath(),t},window.SVGPathSegList.prototype.removeItem=function(t){this._checkPathSynchronizedToList(),this._checkValidIndex(t);var e=this._list[t];return this._list.splice(t,1),this._writeListToPath(),e},window.SVGPathSegList.prototype.appendItem=function(t){return this._checkPathSynchronizedToList(),t._owningPathSegList&&(t=t.clone()),this._list.push(t),(t._owningPathSegList=this)._writeListToPath(),t},window.SVGPathSegList._pathSegArrayAsString=function(t){var e="",i=!0;return t.forEach(function(t){i?(i=!1,e+=t._asPathString()):e+=" "+t._asPathString()}),e},window.SVGPathSegList.prototype._parsePath=function(t){if(!t||0==t.length)return[];var n=this,e=function(){this.pathSegList=[]};e.prototype.appendSegment=function(t){this.pathSegList.push(t)};var i=function(t){this._string=t,this._currentIndex=0,this._endIndex=this._string.length,this._previousCommand=window.SVGPathSeg.PATHSEG_UNKNOWN,this._skipOptionalSpaces()};i.prototype._isCurrentSpace=function(){var t=this._string[this._currentIndex];return t<=" "&&(" "==t||"\n"==t||"\t"==t||"\r"==t||"\f"==t)},i.prototype._skipOptionalSpaces=function(){for(;this._currentIndex<this._endIndex&&this._isCurrentSpace();)this._currentIndex++;return this._currentIndex<this._endIndex},i.prototype._skipOptionalSpacesOrDelimiter=function(){return!(this._currentIndex<this._endIndex&&!this._isCurrentSpace()&&","!=this._string.charAt(this._currentIndex))&&(this._skipOptionalSpaces()&&this._currentIndex<this._endIndex&&","==this._string.charAt(this._currentIndex)&&(this._currentIndex++,this._skipOptionalSpaces()),this._currentIndex<this._endIndex)},i.prototype.hasMoreData=function(){return this._currentIndex<this._endIndex},i.prototype.peekSegmentType=function(){var t=this._string[this._currentIndex];return this._pathSegTypeFromChar(t)},i.prototype._pathSegTypeFromChar=function(t){switch(t){case"Z":case"z":return window.SVGPathSeg.PATHSEG_CLOSEPATH;case"M":return window.SVGPathSeg.PATHSEG_MOVETO_ABS;case"m":return window.SVGPathSeg.PATHSEG_MOVETO_REL;case"L":return window.SVGPathSeg.PATHSEG_LINETO_ABS;case"l":return window.SVGPathSeg.PATHSEG_LINETO_REL;case"C":return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS;case"c":return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL;case"Q":return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS;case"q":return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL;case"A":return window.SVGPathSeg.PATHSEG_ARC_ABS;case"a":return window.SVGPathSeg.PATHSEG_ARC_REL;case"H":return window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS;case"h":return window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL;case"V":return window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS;case"v":return window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL;case"S":return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS;case"s":return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL;case"T":return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS;case"t":return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL;default:return window.SVGPathSeg.PATHSEG_UNKNOWN}},i.prototype._nextCommandHelper=function(t,e){return("+"==t||"-"==t||"."==t||"0"<=t&&t<="9")&&e!=window.SVGPathSeg.PATHSEG_CLOSEPATH?e==window.SVGPathSeg.PATHSEG_MOVETO_ABS?window.SVGPathSeg.PATHSEG_LINETO_ABS:e==window.SVGPathSeg.PATHSEG_MOVETO_REL?window.SVGPathSeg.PATHSEG_LINETO_REL:e:window.SVGPathSeg.PATHSEG_UNKNOWN},i.prototype.initialCommandIsMoveTo=function(){if(!this.hasMoreData())return!0;var t=this.peekSegmentType();return t==window.SVGPathSeg.PATHSEG_MOVETO_ABS||t==window.SVGPathSeg.PATHSEG_MOVETO_REL},i.prototype._parseNumber=function(){var t=0,e=0,i=1,n=0,r=1,a=1,o=this._currentIndex;if(this._skipOptionalSpaces(),this._currentIndex<this._endIndex&&"+"==this._string.charAt(this._currentIndex)?this._currentIndex++:this._currentIndex<this._endIndex&&"-"==this._string.charAt(this._currentIndex)&&(this._currentIndex++,r=-1),!(this._currentIndex==this._endIndex||(this._string.charAt(this._currentIndex)<"0"||"9"<this._string.charAt(this._currentIndex))&&"."!=this._string.charAt(this._currentIndex))){for(var s=this._currentIndex;this._currentIndex<this._endIndex&&"0"<=this._string.charAt(this._currentIndex)&&this._string.charAt(this._currentIndex)<="9";)this._currentIndex++;if(this._currentIndex!=s)for(var c=this._currentIndex-1,d=1;s<=c;)e+=d*(this._string.charAt(c--)-"0"),d*=10;if(this._currentIndex<this._endIndex&&"."==this._string.charAt(this._currentIndex)){if(this._currentIndex++,this._currentIndex>=this._endIndex||this._string.charAt(this._currentIndex)<"0"||"9"<this._string.charAt(this._currentIndex))return;for(;this._currentIndex<this._endIndex&&"0"<=this._string.charAt(this._currentIndex)&&this._string.charAt(this._currentIndex)<="9";)i*=10,n+=(this._string.charAt(this._currentIndex)-"0")/i,this._currentIndex+=1}if(this._currentIndex!=o&&this._currentIndex+1<this._endIndex&&("e"==this._string.charAt(this._currentIndex)||"E"==this._string.charAt(this._currentIndex))&&"x"!=this._string.charAt(this._currentIndex+1)&&"m"!=this._string.charAt(this._currentIndex+1)){if(this._currentIndex++,"+"==this._string.charAt(this._currentIndex)?this._currentIndex++:"-"==this._string.charAt(this._currentIndex)&&(this._currentIndex++,a=-1),this._currentIndex>=this._endIndex||this._string.charAt(this._currentIndex)<"0"||"9"<this._string.charAt(this._currentIndex))return;for(;this._currentIndex<this._endIndex&&"0"<=this._string.charAt(this._currentIndex)&&this._string.charAt(this._currentIndex)<="9";)t*=10,t+=this._string.charAt(this._currentIndex)-"0",this._currentIndex++}var l=e+n;if(l*=r,t&&(l*=Math.pow(10,a*t)),o!=this._currentIndex)return this._skipOptionalSpacesOrDelimiter(),l}},i.prototype._parseArcFlag=function(){if(!(this._currentIndex>=this._endIndex)){var t=!1,e=this._string.charAt(this._currentIndex++);if("0"==e)t=!1;else{if("1"!=e)return;t=!0}return this._skipOptionalSpacesOrDelimiter(),t}},i.prototype.parseSegment=function(){var t=this._string[this._currentIndex],e=this._pathSegTypeFromChar(t);if(e==window.SVGPathSeg.PATHSEG_UNKNOWN){if(this._previousCommand==window.SVGPathSeg.PATHSEG_UNKNOWN)return null;if((e=this._nextCommandHelper(t,this._previousCommand))==window.SVGPathSeg.PATHSEG_UNKNOWN)return null}else this._currentIndex++;switch(this._previousCommand=e){case window.SVGPathSeg.PATHSEG_MOVETO_REL:return new window.SVGPathSegMovetoRel(n,this._parseNumber(),this._parseNumber());case window.SVGPathSeg.PATHSEG_MOVETO_ABS:return new window.SVGPathSegMovetoAbs(n,this._parseNumber(),this._parseNumber());case window.SVGPathSeg.PATHSEG_LINETO_REL:return new window.SVGPathSegLinetoRel(n,this._parseNumber(),this._parseNumber());case window.SVGPathSeg.PATHSEG_LINETO_ABS:return new window.SVGPathSegLinetoAbs(n,this._parseNumber(),this._parseNumber());case window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL:return new window.SVGPathSegLinetoHorizontalRel(n,this._parseNumber());case window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS:return new window.SVGPathSegLinetoHorizontalAbs(n,this._parseNumber());case window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL:return new window.SVGPathSegLinetoVerticalRel(n,this._parseNumber());case window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS:return new window.SVGPathSegLinetoVerticalAbs(n,this._parseNumber());case window.SVGPathSeg.PATHSEG_CLOSEPATH:return this._skipOptionalSpaces(),new window.SVGPathSegClosePath(n);case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL:var i={x1:this._parseNumber(),y1:this._parseNumber(),x2:this._parseNumber(),y2:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new window.SVGPathSegCurvetoCubicRel(n,i.x,i.y,i.x1,i.y1,i.x2,i.y2);case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS:return i={x1:this._parseNumber(),y1:this._parseNumber(),x2:this._parseNumber(),y2:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()},new window.SVGPathSegCurvetoCubicAbs(n,i.x,i.y,i.x1,i.y1,i.x2,i.y2);case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL:return i={x2:this._parseNumber(),y2:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()},new window.SVGPathSegCurvetoCubicSmoothRel(n,i.x,i.y,i.x2,i.y2);case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS:return i={x2:this._parseNumber(),y2:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()},new window.SVGPathSegCurvetoCubicSmoothAbs(n,i.x,i.y,i.x2,i.y2);case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL:return i={x1:this._parseNumber(),y1:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()},new window.SVGPathSegCurvetoQuadraticRel(n,i.x,i.y,i.x1,i.y1);case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS:return i={x1:this._parseNumber(),y1:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()},new window.SVGPathSegCurvetoQuadraticAbs(n,i.x,i.y,i.x1,i.y1);case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL:return new window.SVGPathSegCurvetoQuadraticSmoothRel(n,this._parseNumber(),this._parseNumber());case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS:return new window.SVGPathSegCurvetoQuadraticSmoothAbs(n,this._parseNumber(),this._parseNumber());case window.SVGPathSeg.PATHSEG_ARC_REL:return i={x1:this._parseNumber(),y1:this._parseNumber(),arcAngle:this._parseNumber(),arcLarge:this._parseArcFlag(),arcSweep:this._parseArcFlag(),x:this._parseNumber(),y:this._parseNumber()},new window.SVGPathSegArcRel(n,i.x,i.y,i.x1,i.y1,i.arcAngle,i.arcLarge,i.arcSweep);case window.SVGPathSeg.PATHSEG_ARC_ABS:return i={x1:this._parseNumber(),y1:this._parseNumber(),arcAngle:this._parseNumber(),arcLarge:this._parseArcFlag(),arcSweep:this._parseArcFlag(),x:this._parseNumber(),y:this._parseNumber()},new window.SVGPathSegArcAbs(n,i.x,i.y,i.x1,i.y1,i.arcAngle,i.arcLarge,i.arcSweep);default:throw"Unknown path seg type."}};var r=new e,a=new i(t);if(!a.initialCommandIsMoveTo())return[];for(;a.hasMoreData();){var o=a.parseSegment();if(!o)return[];r.appendSegment(o)}return r.pathSegList}),String.prototype.padEnd||(String.prototype.padEnd=function(t,e){return t>>=0,e=String(void 0!==e?e:" "),this.length>t?String(this):((t-=this.length)>e.length&&(e+=e.repeat(t/e.length)),String(this)+e.slice(0,t))}),(n.prototype.axis=function(){}).labels=function(e){var i=this.internal;arguments.length&&(Object.keys(e).forEach(function(t){i.axis.setLabelText(t,e[t])}),i.axis.updateLabels())},n.prototype.axis.max=function(t){var e=this.internal,i=e.config;if(!arguments.length)return{x:i.axis_x_max,y:i.axis_y_max,y2:i.axis_y2_max};"object"===s(t)?(P(t.x)&&(i.axis_x_max=t.x),P(t.y)&&(i.axis_y_max=t.y),P(t.y2)&&(i.axis_y2_max=t.y2)):i.axis_y_max=i.axis_y2_max=t,e.redraw({withUpdateOrgXDomain:!0,withUpdateXDomain:!0})},n.prototype.axis.min=function(t){var e=this.internal,i=e.config;if(!arguments.length)return{x:i.axis_x_min,y:i.axis_y_min,y2:i.axis_y2_min};"object"===s(t)?(P(t.x)&&(i.axis_x_min=t.x),P(t.y)&&(i.axis_y_min=t.y),P(t.y2)&&(i.axis_y2_min=t.y2)):i.axis_y_min=i.axis_y2_min=t,e.redraw({withUpdateOrgXDomain:!0,withUpdateXDomain:!0})},n.prototype.axis.range=function(t){if(!arguments.length)return{max:this.axis.max(),min:this.axis.min()};k(t.max)&&this.axis.max(t.max),k(t.min)&&this.axis.min(t.min)},n.prototype.category=function(t,e){var i=this.internal,n=i.config;return 1<arguments.length&&(n.axis_x_categories[t]=e,i.redraw()),n.axis_x_categories[t]},n.prototype.categories=function(t){var e=this.internal,i=e.config;return arguments.length&&(i.axis_x_categories=t,e.redraw()),i.axis_x_categories},n.prototype.resize=function(t){var e=this.internal.config;e.size_width=t?t.width:null,e.size_height=t?t.height:null,this.flush()},n.prototype.flush=function(){this.internal.updateAndRedraw({withLegend:!0,withTransition:!1,withTransitionForTransform:!1})},n.prototype.destroy=function(){var e=this.internal;if(window.clearInterval(e.intervalForObserveInserted),void 0!==e.resizeTimeout&&window.clearTimeout(e.resizeTimeout),window.detachEvent)window.detachEvent("onresize",e.resizeIfElementDisplayed);else if(window.removeEventListener)window.removeEventListener("resize",e.resizeIfElementDisplayed);else{var t=window.onresize;t&&t.add&&t.remove&&t.remove(e.resizeFunction)}return e.resizeFunction.remove(),e.selectChart.classed("c3",!1).html(""),Object.keys(e).forEach(function(t){e[t]=null}),null},n.prototype.color=function(t){return this.internal.color(t)},(n.prototype.data=function(e){var t=this.internal.data.targets;return void 0===e?t:t.filter(function(t){return 0<=[].concat(e).indexOf(t.id)})}).shown=function(t){return this.internal.filterTargetsToShow(this.data(t))},n.prototype.data.values=function(t){var e,i=null;return t&&(i=(e=this.data(t))[0]?e[0].values.map(function(t){return t.value}):null),i},n.prototype.data.names=function(t){return this.internal.clearLegendItemTextBoxCache(),this.internal.updateDataAttributes("names",t)},n.prototype.data.colors=function(t){return this.internal.updateDataAttributes("colors",t)},n.prototype.data.axes=function(t){return this.internal.updateDataAttributes("axes",t)},n.prototype.flow=function(t){var r,e,i,n,a,o,s,c=this.internal,d=[],l=c.getMaxDataCount(),u=0,h=0;if(t.json)e=c.convertJsonToData(t.json,t.keys);else if(t.rows)e=c.convertRowsToData(t.rows);else{if(!t.columns)return;e=c.convertColumnsToData(t.columns)}r=c.convertDataToTargets(e,!0),c.data.targets.forEach(function(t){var e,i,n=!1;for(e=0;e<r.length;e++)if(t.id===r[e].id){for(n=!0,t.values[t.values.length-1]&&(h=t.values[t.values.length-1].index+1),u=r[e].values.length,i=0;i<u;i++)r[e].values[i].index=h+i,c.isTimeSeries()||(r[e].values[i].x=h+i);t.values=t.values.concat(r[e].values),r.splice(e,1);break}n||d.push(t.id)}),c.data.targets.forEach(function(t){var e,i;for(e=0;e<d.length;e++)if(t.id===d[e])for(h=t.values[t.values.length-1].index+1,i=0;i<u;i++)t.values.push({id:t.id,index:h+i,x:c.isTimeSeries()?c.getOtherTargetX(h+i):h+i,value:null})}),c.data.targets.length&&r.forEach(function(t){var e,i=[];for(e=c.data.targets[0].values[0].index;e<h;e++)i.push({id:t.id,index:e,x:c.isTimeSeries()?c.getOtherTargetX(e):e,value:null});t.values.forEach(function(t){t.index+=h,c.isTimeSeries()||(t.x+=h)}),t.values=i.concat(t.values)}),c.data.targets=c.data.targets.concat(r),c.getMaxDataCount(),a=(n=c.data.targets[0]).values[0],k(t.to)?(u=0,s=c.isTimeSeries()?c.parseDate(t.to):t.to,n.values.forEach(function(t){t.x<s&&u++})):k(t.length)&&(u=t.length),l?1===l&&c.isTimeSeries()&&(o=(n.values[n.values.length-1].x-a.x)/2,i=[new Date(+a.x-o),new Date(+a.x+o)],c.updateXDomain(null,!0,!0,!1,i)):(o=c.isTimeSeries()?1<n.values.length?n.values[n.values.length-1].x-a.x:a.x-c.getXDomain(c.data.targets)[0]:1,i=[a.x-o,a.x],c.updateXDomain(null,!0,!0,!1,i)),c.updateTargets(c.data.targets),c.redraw({flow:{index:a.index,length:u,duration:P(t.duration)?t.duration:c.config.transition_duration,done:t.done,orgDataCount:l},withLegend:!0,withTransition:1<l,withTrimXDomain:!1,withUpdateXAxis:!0})},l.prototype.generateFlow=function(G){var E=this,I=E.config,O=E.d3;return function(){var t,e,n,r,a,o,s,c,d,l,i=G.targets,u=G.flow,h=G.drawBar,g=G.drawLine,p=G.drawArea,f=G.cx,_=G.cy,x=G.xv,y=G.xForText,m=G.yForText,S=G.duration,w=u.index,v=u.length,b=E.getValueOnIndex(E.data.targets[0].values,w),A=E.getValueOnIndex(E.data.targets[0].values,w+v),T=E.x.domain(),P=u.duration||S,C=u.done||function(){},L=E.generateWait();E.flowing=!0,E.data.targets.forEach(function(t){t.values.splice(0,v)}),e=E.updateXDomain(i,!0,!0),E.updateXGrid&&E.updateXGrid(!0),n=E.xgrid||O.selectAll([]),r=E.xgridLines||O.selectAll([]),a=E.mainRegion||O.selectAll([]),o=E.mainText||O.selectAll([]),s=E.mainBar||O.selectAll([]),c=E.mainLine||O.selectAll([]),d=E.mainArea||O.selectAll([]),l=E.mainCircle||O.selectAll([]),t="translate("+(u.orgDataCount?1===u.orgDataCount||(b&&b.x)===(A&&A.x)?E.x(T[0])-E.x(e[0]):E.isTimeSeries()?E.x(T[0])-E.x(e[0]):E.x(b.x)-E.x(A.x):1!==E.data.targets[0].values.length?E.x(T[0])-E.x(e[0]):E.isTimeSeries()?(b=E.getValueOnIndex(E.data.targets[0].values,0),A=E.getValueOnIndex(E.data.targets[0].values,E.data.targets[0].values.length-1),E.x(b.x)-E.x(A.x)):R(e)/2)+",0) scale("+R(T)/R(e)+",1)",E.hideXGridFocus();var V=O.transition().ease(O.easeLinear).duration(P);L.add(E.xAxis(E.axes.x,V)),L.add(s.transition(V).attr("transform",t)),L.add(c.transition(V).attr("transform",t)),L.add(d.transition(V).attr("transform",t)),L.add(l.transition(V).attr("transform",t)),L.add(o.transition(V).attr("transform",t)),L.add(a.filter(E.isRegionOnX).transition(V).attr("transform",t)),L.add(n.transition(V).attr("transform",t)),L.add(r.transition(V).attr("transform",t)),L(function(){var t,e=[],i=[];if(v){for(t=0;t<v;t++)e.push("."+Y.shape+"-"+(w+t)),i.push("."+Y.text+"-"+(w+t));E.svg.selectAll("."+Y.shapes).selectAll(e).remove(),E.svg.selectAll("."+Y.texts).selectAll(i).remove(),E.svg.select("."+Y.xgrid).remove()}n.attr("transform",null).attr("x1",E.xgridAttr.x1).attr("x2",E.xgridAttr.x2).attr("y1",E.xgridAttr.y1).attr("y2",E.xgridAttr.y2).style("opacity",E.xgridAttr.opacity),r.attr("transform",null),r.select("line").attr("x1",I.axis_rotated?0:x).attr("x2",I.axis_rotated?E.width:x),r.select("text").attr("x",I.axis_rotated?E.width:0).attr("y",x),s.attr("transform",null).attr("d",h),c.attr("transform",null).attr("d",g),d.attr("transform",null).attr("d",p),l.attr("transform",null).attr("cx",f).attr("cy",_),o.attr("transform",null).attr("x",y).attr("y",m).style("fill-opacity",E.opacityForText.bind(E)),a.attr("transform",null),a.filter(E.isRegionOnX).attr("x",E.regionX.bind(E)).attr("width",E.regionWidth.bind(E)),C(),E.flowing=!1})}},n.prototype.focus=function(e){var t,i=this.internal;e=i.mapToTargetIds(e),t=i.svg.selectAll(i.selectorTargets(e.filter(i.isTargetToShow,i))),this.revert(),this.defocus(),t.classed(Y.focused,!0).classed(Y.defocused,!1),i.hasArcType()&&i.expandArc(e),i.toggleFocusLegend(e,!0),i.focusedTargetIds=e,i.defocusedTargetIds=i.defocusedTargetIds.filter(function(t){return e.indexOf(t)<0})},n.prototype.defocus=function(e){var t=this.internal;e=t.mapToTargetIds(e),t.svg.selectAll(t.selectorTargets(e.filter(t.isTargetToShow,t))).classed(Y.focused,!1).classed(Y.defocused,!0),t.hasArcType()&&t.unexpandArc(e),t.toggleFocusLegend(e,!1),t.focusedTargetIds=t.focusedTargetIds.filter(function(t){return e.indexOf(t)<0}),t.defocusedTargetIds=e},n.prototype.revert=function(t){var e=this.internal;t=e.mapToTargetIds(t),e.svg.selectAll(e.selectorTargets(t)).classed(Y.focused,!1).classed(Y.defocused,!1),e.hasArcType()&&e.unexpandArc(t),e.config.legend_show&&(e.showLegend(t.filter(e.isLegendToShow.bind(e))),e.legend.selectAll(e.selectorLegends(t)).filter(function(){return e.d3.select(this).classed(Y.legendItemFocused)}).classed(Y.legendItemFocused,!1)),e.focusedTargetIds=[],e.defocusedTargetIds=[]},(n.prototype.xgrids=function(t){var e=this.internal,i=e.config;return t&&(i.grid_x_lines=t,e.redrawWithoutRescale()),i.grid_x_lines}).add=function(t){var e=this.internal;return this.xgrids(e.config.grid_x_lines.concat(t||[]))},n.prototype.xgrids.remove=function(t){this.internal.removeGridLines(t,!0)},(n.prototype.ygrids=function(t){var e=this.internal,i=e.config;return t&&(i.grid_y_lines=t,e.redrawWithoutRescale()),i.grid_y_lines}).add=function(t){var e=this.internal;return this.ygrids(e.config.grid_y_lines.concat(t||[]))},n.prototype.ygrids.remove=function(t){this.internal.removeGridLines(t,!1)},n.prototype.groups=function(t){var e=this.internal,i=e.config;return v(t)||(i.data_groups=t,e.redraw()),i.data_groups},(n.prototype.legend=function(){}).show=function(t){var e=this.internal;e.showLegend(e.mapToTargetIds(t)),e.updateAndRedraw({withLegend:!0})},n.prototype.legend.hide=function(t){var e=this.internal;e.hideLegend(e.mapToTargetIds(t)),e.updateAndRedraw({withLegend:!1})},n.prototype.load=function(e){var t=this.internal,i=t.config;e.xs&&t.addXs(e.xs),"names"in e&&n.prototype.data.names.bind(this)(e.names),"classes"in e&&Object.keys(e.classes).forEach(function(t){i.data_classes[t]=e.classes[t]}),"categories"in e&&t.isCategorized()&&(i.axis_x_categories=e.categories),"axes"in e&&Object.keys(e.axes).forEach(function(t){i.data_axes[t]=e.axes[t]}),"colors"in e&&Object.keys(e.colors).forEach(function(t){i.data_colors[t]=e.colors[t]}),"cacheIds"in e&&t.hasCaches(e.cacheIds)?t.load(t.getCaches(e.cacheIds),e.done):"unload"in e?t.unload(t.mapToTargetIds("boolean"==typeof e.unload&&e.unload?null:e.unload),function(){t.loadFromArgs(e)}):t.loadFromArgs(e)},n.prototype.unload=function(t){var e=this.internal;(t=t||{})instanceof Array?t={ids:t}:"string"==typeof t&&(t={ids:[t]}),e.unload(e.mapToTargetIds(t.ids),function(){e.redraw({withUpdateOrgXDomain:!0,withUpdateXDomain:!0,withLegend:!0}),t.done&&t.done()})},(n.prototype.regions=function(t){var e=this.internal,i=e.config;return t&&(i.regions=t,e.redrawWithoutRescale()),i.regions}).add=function(t){var e=this.internal,i=e.config;return t&&(i.regions=i.regions.concat(t),e.redrawWithoutRescale()),i.regions},n.prototype.regions.remove=function(t){var e,i,n,r=this.internal,a=r.config;return t=t||{},e=r.getOption(t,"duration",a.transition_duration),i=r.getOption(t,"classes",[Y.region]),n=r.main.select("."+Y.regions).selectAll(i.map(function(t){return"."+t})),(e?n.transition().duration(e):n).style("opacity",0).remove(),a.regions=a.regions.filter(function(t){var e=!1;return!t.class||(t.class.split(" ").forEach(function(t){0<=i.indexOf(t)&&(e=!0)}),!e)}),a.regions},n.prototype.selected=function(t){var e=this.internal,i=e.d3;return i.merge(e.main.selectAll("."+Y.shapes+e.getTargetSelectorSuffix(t)).selectAll("."+Y.shape).filter(function(){return i.select(this).classed(Y.SELECTED)}).map(function(t){return t.map(function(t){var e=t.__data__;return e.data?e.data:e})}))},n.prototype.select=function(c,d,l){var u=this.internal,h=u.d3,g=u.config;g.data_selection_enabled&&u.main.selectAll("."+Y.shapes).selectAll("."+Y.shape).each(function(t,e){var i=h.select(this),n=t.data?t.data.id:t.id,r=u.getToggle(this,t).bind(u),a=g.data_selection_grouped||!c||0<=c.indexOf(n),o=!d||0<=d.indexOf(e),s=i.classed(Y.SELECTED);i.classed(Y.line)||i.classed(Y.area)||(a&&o?g.data_selection_isselectable(t)&&!s&&r(!0,i.classed(Y.SELECTED,!0),t,e):k(l)&&l&&s&&r(!1,i.classed(Y.SELECTED,!1),t,e))})},n.prototype.unselect=function(c,d){var l=this.internal,u=l.d3,h=l.config;h.data_selection_enabled&&l.main.selectAll("."+Y.shapes).selectAll("."+Y.shape).each(function(t,e){var i=u.select(this),n=t.data?t.data.id:t.id,r=l.getToggle(this,t).bind(l),a=h.data_selection_grouped||!c||0<=c.indexOf(n),o=!d||0<=d.indexOf(e),s=i.classed(Y.SELECTED);i.classed(Y.line)||i.classed(Y.area)||a&&o&&h.data_selection_isselectable(t)&&s&&r(!1,i.classed(Y.SELECTED,!1),t,e)})},n.prototype.show=function(t,e){var i,n=this.internal;t=n.mapToTargetIds(t),e=e||{},n.removeHiddenTargetIds(t),(i=n.svg.selectAll(n.selectorTargets(t))).transition().style("display","initial","important").style("opacity",1,"important").call(n.endall,function(){i.style("opacity",null).style("opacity",1)}),e.withLegend&&n.showLegend(t),n.redraw({withUpdateOrgXDomain:!0,withUpdateXDomain:!0,withLegend:!0})},n.prototype.hide=function(t,e){var i,n=this.internal;t=n.mapToTargetIds(t),e=e||{},n.addHiddenTargetIds(t),(i=n.svg.selectAll(n.selectorTargets(t))).transition().style("opacity",0,"important").call(n.endall,function(){i.style("opacity",null).style("opacity",0),i.style("display","none")}),e.withLegend&&n.hideLegend(t),n.redraw({withUpdateOrgXDomain:!0,withUpdateXDomain:!0,withLegend:!0})},n.prototype.toggle=function(t,e){var i=this,n=this.internal;n.mapToTargetIds(t).forEach(function(t){n.isTargetToShow(t)?i.hide(t,e):i.show(t,e)})},(n.prototype.tooltip=function(){}).show=function(e){var t,i,n=this.internal,r={};r=e.mouse?e.mouse:(e.data?i=e.data:void 0!==e.x&&(t=e.id?n.data.targets.filter(function(t){return t.id===e.id}):n.data.targets,i=n.filterByX(t,e.x).slice(0,1)[0]),i?n.getMousePosition(i):null),n.dispatchEvent("mousemove",r),n.config.tooltip_onshow.call(n,i)},n.prototype.tooltip.hide=function(){this.internal.dispatchEvent("mouseout",0),this.internal.config.tooltip_onhide.call(this)},n.prototype.transform=function(t,e){var i=this.internal,n=0<=["pie","donut"].indexOf(t)?{withTransform:!0}:null;i.transformTo(e,t,n)},l.prototype.transformTo=function(t,e,i){var n=this,r=!n.hasArcType(),a=i||{withTransitionForAxis:r};a.withTransitionForTransform=!1,n.transiting=!1,n.setTargetType(t,e),n.updateTargets(n.data.targets),n.updateAndRedraw(a)},n.prototype.x=function(t){var e=this.internal;return arguments.length&&(e.updateTargetX(e.data.targets,t),e.redraw({withUpdateOrgXDomain:!0,withUpdateXDomain:!0})),e.data.xs},n.prototype.xs=function(t){var e=this.internal;return arguments.length&&(e.updateTargetXs(e.data.targets,t),e.redraw({withUpdateOrgXDomain:!0,withUpdateXDomain:!0})),e.data.xs},(n.prototype.zoom=function(t){var e=this.internal;return t?(e.isTimeSeries()&&(t=t.map(function(t){return e.parseDate(t)})),e.config.subchart_show?e.brush.selectionAsValue(t,!0):(e.updateXDomain(null,!0,!1,!1,t),e.redraw({withY:e.config.zoom_rescale,withSubchart:!1})),e.config.zoom_onzoom.call(this,e.x.orgDomain()),t):e.x.domain()}).enable=function(t){var e=this.internal;e.config.zoom_enabled=t,e.updateAndRedraw()},n.prototype.unzoom=function(){var t=this.internal;t.config.subchart_show?t.brush.clear():(t.updateXDomain(null,!0,!1,!1,t.subX.domain()),t.redraw({withY:t.config.zoom_rescale,withSubchart:!1}))},n.prototype.zoom.max=function(t){var e=this.internal,i=e.config,n=e.d3;if(0!==t&&!t)return i.zoom_x_max;i.zoom_x_max=n.max([e.orgXDomain[1],t])},n.prototype.zoom.min=function(t){var e=this.internal,i=e.config,n=e.d3;if(0!==t&&!t)return i.zoom_x_min;i.zoom_x_min=n.min([e.orgXDomain[0],t])},n.prototype.zoom.range=function(t){if(!arguments.length)return{max:this.domain.max(),min:this.domain.min()};k(t.max)&&this.domain.max(t.max),k(t.min)&&this.domain.min(t.min)},l.prototype.initPie=function(){var t=this,e=t.d3;t.pie=e.pie().value(function(t){return t.values.reduce(function(t,e){return t+e.value},0)});var i=t.getOrderFunction();if(i&&(t.isOrderAsc()||t.isOrderDesc())){var n=i;i=function(t,e){return-1*n(t,e)}}t.pie.sort(i||null)},l.prototype.updateRadius=function(){var t=this,e=t.config,i=e.gauge_width||e.donut_width,n=t.filterTargetsToShow(t.data.targets).length*t.config.gauge_arcs_minWidth;t.radiusExpanded=Math.min(t.arcWidth,t.arcHeight)/2*(t.hasType("gauge")?.85:1),t.radius=.95*t.radiusExpanded,t.innerRadiusRatio=i?(t.radius-i)/t.radius:.6,t.innerRadius=t.hasType("donut")||t.hasType("gauge")?t.radius*t.innerRadiusRatio:0,t.gaugeArcWidth=i||(n<=t.radius-t.innerRadius?t.radius-t.innerRadius:n<=t.radius?n:t.radius)},l.prototype.updateArc=function(){var t=this;t.svgArc=t.getSvgArc(),t.svgArcExpanded=t.getSvgArcExpanded(),t.svgArcExpandedSub=t.getSvgArcExpanded(.98)},l.prototype.updateAngle=function(e){var t,i,n,r,a=this,o=a.config,s=!1,c=0;return o?(a.pie(a.filterTargetsToShow(a.data.targets)).forEach(function(t){s||t.data.id!==e.data.id||(s=!0,(e=t).index=c),c++}),isNaN(e.startAngle)&&(e.startAngle=0),isNaN(e.endAngle)&&(e.endAngle=e.startAngle),a.isGaugeType(e.data)&&(t=o.gauge_min,i=o.gauge_max,n=Math.PI*(o.gauge_fullCircle?2:1)/(i-t),r=e.value<t?0:e.value<i?e.value-t:i-t,e.startAngle=o.gauge_startingAngle,e.endAngle=e.startAngle+n*r),s?e:null):null},l.prototype.getSvgArc=function(){var n=this,e=n.hasType("gauge"),i=n.gaugeArcWidth/n.filterTargetsToShow(n.data.targets).length,r=n.d3.arc().outerRadius(function(t){return e?n.radius-i*t.index:n.radius}).innerRadius(function(t){return e?n.radius-i*(t.index+1):n.innerRadius}),t=function(t,e){var i;return e?r(t):(i=n.updateAngle(t))?r(i):"M 0 0"};return t.centroid=r.centroid,t},l.prototype.getSvgArcExpanded=function(e){e=e||1;var i=this,n=i.hasType("gauge"),r=i.gaugeArcWidth/i.filterTargetsToShow(i.data.targets).length,a=Math.min(i.radiusExpanded*e-i.radius,.8*r-100*(1-e)),o=i.d3.arc().outerRadius(function(t){return n?i.radius-r*t.index+a:i.radiusExpanded*e}).innerRadius(function(t){return n?i.radius-r*(t.index+1):i.innerRadius});return function(t){var e=i.updateAngle(t);return e?o(e):"M 0 0"}},l.prototype.getArc=function(t,e,i){return i||this.isArcType(t.data)?this.svgArc(t,e):"M 0 0"},l.prototype.transformForArcLabel=function(t){var e,i,n,r,a,o=this,s=o.config,c=o.updateAngle(t),d="",l=o.hasType("gauge");if(c&&!l)e=this.svgArc.centroid(c),i=isNaN(e[0])?0:e[0],n=isNaN(e[1])?0:e[1],r=Math.sqrt(i*i+n*n),d="translate("+i*(a=o.hasType("donut")&&s.donut_label_ratio?h(s.donut_label_ratio)?s.donut_label_ratio(t,o.radius,r):s.donut_label_ratio:o.hasType("pie")&&s.pie_label_ratio?h(s.pie_label_ratio)?s.pie_label_ratio(t,o.radius,r):s.pie_label_ratio:o.radius&&r?(.375<36/o.radius?1.175-36/o.radius:.8)*o.radius/r:0)+","+n*a+")";else if(c&&l&&1<o.filterTargetsToShow(o.data.targets).length){var u=Math.sin(c.endAngle-Math.PI/2);d="translate("+(i=Math.cos(c.endAngle-Math.PI/2)*(o.radiusExpanded+25))+","+(n=u*(o.radiusExpanded+15-Math.abs(10*u))+3)+")"}return d},l.prototype.getArcRatio=function(t){var e=this.config,i=Math.PI*(this.hasType("gauge")&&!e.gauge_fullCircle?1:2);return t?(t.endAngle-t.startAngle)/i:null},l.prototype.convertToArcData=function(t){return this.addName({id:t.data.id,value:t.value,ratio:this.getArcRatio(t),index:t.index})},l.prototype.textForArcLabel=function(t){var e,i,n,r,a,o=this;return o.shouldShowArcLabel()?(i=(e=o.updateAngle(t))?e.value:null,n=o.getArcRatio(e),r=t.data.id,o.hasType("gauge")||o.meetsArcLabelThreshold(n)?(a=o.getArcLabelFormat())?a(i,n,r):o.defaultArcValueFormat(i,n):""):""},l.prototype.textForGaugeMinMax=function(t,e){var i=this.getGaugeLabelExtents();return i?i(t,e):t},l.prototype.expandArc=function(t){var e,i=this;i.transiting?e=window.setInterval(function(){i.transiting||(window.clearInterval(e),0<i.legend.selectAll(".c3-legend-item-focused").size()&&i.expandArc(t))},10):(t=i.mapToTargetIds(t),i.svg.selectAll(i.selectorTargets(t,"."+Y.chartArc)).each(function(t){i.shouldExpand(t.data.id)&&i.d3.select(this).selectAll("path").transition().duration(i.expandDuration(t.data.id)).attr("d",i.svgArcExpanded).transition().duration(2*i.expandDuration(t.data.id)).attr("d",i.svgArcExpandedSub).each(function(t){i.isDonutType(t.data)})}))},l.prototype.unexpandArc=function(t){var e=this;e.transiting||(t=e.mapToTargetIds(t),e.svg.selectAll(e.selectorTargets(t,"."+Y.chartArc)).selectAll("path").transition().duration(function(t){return e.expandDuration(t.data.id)}).attr("d",e.svgArc),e.svg.selectAll("."+Y.arc))},l.prototype.expandDuration=function(t){var e=this.config;return this.isDonutType(t)?e.donut_expand_duration:this.isGaugeType(t)?e.gauge_expand_duration:this.isPieType(t)?e.pie_expand_duration:50},l.prototype.shouldExpand=function(t){var e=this.config;return this.isDonutType(t)&&e.donut_expand||this.isGaugeType(t)&&e.gauge_expand||this.isPieType(t)&&e.pie_expand},l.prototype.shouldShowArcLabel=function(){var t=this.config,e=!0;return this.hasType("donut")?e=t.donut_label_show:this.hasType("pie")&&(e=t.pie_label_show),e},l.prototype.meetsArcLabelThreshold=function(t){var e=this.config;return(this.hasType("donut")?e.donut_label_threshold:e.pie_label_threshold)<=t},l.prototype.getArcLabelFormat=function(){var t=this.config,e=t.pie_label_format;return this.hasType("gauge")?e=t.gauge_label_format:this.hasType("donut")&&(e=t.donut_label_format),e},l.prototype.getGaugeLabelExtents=function(){return this.config.gauge_label_extents},l.prototype.getArcTitle=function(){return this.hasType("donut")?this.config.donut_title:""},l.prototype.updateTargetsForArc=function(t){var e,i=this,n=i.main,r=i.classChartArc.bind(i),a=i.classArcs.bind(i),o=i.classFocus.bind(i);(e=n.select("."+Y.chartArcs).selectAll("."+Y.chartArc).data(i.pie(t)).attr("class",function(t){return r(t)+o(t.data)}).enter().append("g").attr("class",r)).append("g").attr("class",a),e.append("text").attr("dy",i.hasType("gauge")?"-.1em":".35em").style("opacity",0).style("text-anchor","middle").style("pointer-events","none")},l.prototype.initArc=function(){var t=this;t.arcs=t.main.select("."+Y.chart).append("g").attr("class",Y.chartArcs).attr("transform",t.getTranslate("arc")),t.arcs.append("text").attr("class",Y.chartArcsTitle).style("text-anchor","middle").text(t.getArcTitle())},l.prototype.redrawArc=function(t,e,i){var n,r,a,o,l=this,u=l.d3,s=l.config,c=l.main,d=l.hasType("gauge");if(r=(n=c.selectAll("."+Y.arcs).selectAll("."+Y.arc).data(l.arcData.bind(l))).enter().append("path").attr("class",l.classArc.bind(l)).style("fill",function(t){return l.color(t.data)}).style("cursor",function(t){return s.interaction_enabled&&s.data_selection_isselectable(t)?"pointer":null}).each(function(t){l.isGaugeType(t.data)&&(t.startAngle=t.endAngle=s.gauge_startingAngle),this._current=t}).merge(n),d&&(o=(a=c.selectAll("."+Y.arcs).selectAll("."+Y.arcLabelLine).data(l.arcData.bind(l))).enter().append("rect").attr("class",function(t){return Y.arcLabelLine+" "+Y.target+" "+Y.target+"-"+t.data.id}).merge(a),1===l.filterTargetsToShow(l.data.targets).length?o.style("display","none"):o.style("fill",function(t){return 0<s.color_pattern.length?l.levelColor(t.data.values[0].value):l.color(t.data)}).style("display",s.gauge_labelLine_show?"":"none").each(function(t){var e=0,i=0,n=0,r="";if(l.hiddenTargetIds.indexOf(t.data.id)<0){var a=l.updateAngle(t),o=l.gaugeArcWidth/l.filterTargetsToShow(l.data.targets).length*(a.index+1),s=a.endAngle-Math.PI/2,c=l.radius-o,d=s-(0===c?0:1/c);e=l.radiusExpanded-l.radius+o,i=Math.cos(d)*c,n=Math.sin(d)*c,r="rotate("+180*s/Math.PI+", "+i+", "+n+")"}u.select(this).attr("x",i).attr("y",n).attr("width",e).attr("height",2).attr("transform",r).style("stroke-dasharray","0, "+(e+2)+", 0")})),r.attr("transform",function(t){return!l.isGaugeType(t.data)&&i?"scale(0)":""}).on("mouseover",s.interaction_enabled?function(t){var e,i;l.transiting||(e=l.updateAngle(t))&&(i=l.convertToArcData(e),l.expandArc(e.data.id),l.api.focus(e.data.id),l.toggleFocusLegend(e.data.id,!0),l.config.data_onmouseover(i,this))}:null).on("mousemove",s.interaction_enabled?function(t){var e,i=l.updateAngle(t);i&&(e=[l.convertToArcData(i)],l.showTooltip(e,this))}:null).on("mouseout",s.interaction_enabled?function(t){var e,i;l.transiting||(e=l.updateAngle(t))&&(i=l.convertToArcData(e),l.unexpandArc(e.data.id),l.api.revert(),l.revertLegend(),l.hideTooltip(),l.config.data_onmouseout(i,this))}:null).on("click",s.interaction_enabled?function(t,e){var i,n=l.updateAngle(t);n&&(i=l.convertToArcData(n),l.toggleShape&&l.toggleShape(this,i,e),l.config.data_onclick.call(l.api,i,this))}:null).each(function(){l.transiting=!0}).transition().duration(t).attrTween("d",function(i){var n,t=l.updateAngle(i);return t?(isNaN(this._current.startAngle)&&(this._current.startAngle=0),isNaN(this._current.endAngle)&&(this._current.endAngle=this._current.startAngle),n=u.interpolate(this._current,t),this._current=n(0),function(t){var e=n(t);return e.data=i.data,l.getArc(e,!0)}):function(){return"M 0 0"}}).attr("transform",i?"scale(1)":"").style("fill",function(t){return l.levelColor?l.levelColor(t.data.values[0].value):l.color(t.data.id)}).call(l.endall,function(){l.transiting=!1}),n.exit().transition().duration(e).style("opacity",0).remove(),c.selectAll("."+Y.chartArc).select("text").style("opacity",0).attr("class",function(t){return l.isGaugeType(t.data)?Y.gaugeValue:""}).text(l.textForArcLabel.bind(l)).attr("transform",l.transformForArcLabel.bind(l)).style("font-size",function(t){return l.isGaugeType(t.data)&&1===l.filterTargetsToShow(l.data.targets).length?Math.round(l.radius/5)+"px":""}).transition().duration(t).style("opacity",function(t){return l.isTargetToShow(t.data.id)&&l.isArcType(t.data)?1:0}),c.select("."+Y.chartArcsTitle).style("opacity",l.hasType("donut")||d?1:0),d){var h=0,g=l.arcs.select("g."+Y.chartArcsBackground).selectAll("path."+Y.chartArcsBackground).data(l.data.targets);g.enter().append("path").attr("class",function(t,e){return Y.chartArcsBackground+" "+Y.chartArcsBackground+"-"+e}).merge(g).attr("d",function(t){if(0<=l.hiddenTargetIds.indexOf(t.id))return"M 0 0";var e={data:[{value:s.gauge_max}],startAngle:s.gauge_startingAngle,endAngle:-1*s.gauge_startingAngle*(s.gauge_fullCircle?Math.PI:1),index:h++};return l.getArc(e,!0,!0)}),g.exit().remove(),l.arcs.select("."+Y.chartArcsGaugeUnit).attr("dy",".75em").text(s.gauge_label_show?s.gauge_units:""),l.arcs.select("."+Y.chartArcsGaugeMin).attr("dx",-1*(l.innerRadius+(l.radius-l.innerRadius)/(s.gauge_fullCircle?1:2))+"px").attr("dy","1.2em").text(s.gauge_label_show?l.textForGaugeMinMax(s.gauge_min,!1):""),l.arcs.select("."+Y.chartArcsGaugeMax).attr("dx",l.innerRadius+(l.radius-l.innerRadius)/(s.gauge_fullCircle?1:2)+"px").attr("dy","1.2em").text(s.gauge_label_show?l.textForGaugeMinMax(s.gauge_max,!0):"")}},l.prototype.initGauge=function(){var t=this.arcs;this.hasType("gauge")&&(t.append("g").attr("class",Y.chartArcsBackground),t.append("text").attr("class",Y.chartArcsGaugeUnit).style("text-anchor","middle").style("pointer-events","none"),t.append("text").attr("class",Y.chartArcsGaugeMin).style("text-anchor","middle").style("pointer-events","none"),t.append("text").attr("class",Y.chartArcsGaugeMax).style("text-anchor","middle").style("pointer-events","none"))},l.prototype.getGaugeLabelHeight=function(){return this.config.gauge_label_show?20:0},l.prototype.hasCaches=function(t){for(var e=0;e<t.length;e++)if(!(t[e]in this.cache))return!1;return!0},l.prototype.addCache=function(t,e){this.cache[t]=this.cloneTarget(e)},l.prototype.getCaches=function(t){var e,i=[];for(e=0;e<t.length;e++)t[e]in this.cache&&i.push(this.cloneTarget(this.cache[t[e]]));return i},l.prototype.categoryName=function(t){var e=this.config;return t<e.axis_x_categories.length?e.axis_x_categories[t]:t},l.prototype.generateTargetClass=function(t){return t||0===t?("-"+t).replace(/\s/g,"-"):""},l.prototype.generateClass=function(t,e){return" "+t+" "+t+this.generateTargetClass(e)},l.prototype.classText=function(t){return this.generateClass(Y.text,t.index)},l.prototype.classTexts=function(t){return this.generateClass(Y.texts,t.id)},l.prototype.classShape=function(t){return this.generateClass(Y.shape,t.index)},l.prototype.classShapes=function(t){return this.generateClass(Y.shapes,t.id)},l.prototype.classLine=function(t){return this.classShape(t)+this.generateClass(Y.line,t.id)},l.prototype.classLines=function(t){return this.classShapes(t)+this.generateClass(Y.lines,t.id)},l.prototype.classCircle=function(t){return this.classShape(t)+this.generateClass(Y.circle,t.index)},l.prototype.classCircles=function(t){return this.classShapes(t)+this.generateClass(Y.circles,t.id)},l.prototype.classBar=function(t){return this.classShape(t)+this.generateClass(Y.bar,t.index)},l.prototype.classBars=function(t){return this.classShapes(t)+this.generateClass(Y.bars,t.id)},l.prototype.classArc=function(t){return this.classShape(t.data)+this.generateClass(Y.arc,t.data.id)},l.prototype.classArcs=function(t){return this.classShapes(t.data)+this.generateClass(Y.arcs,t.data.id)},l.prototype.classArea=function(t){return this.classShape(t)+this.generateClass(Y.area,t.id)},l.prototype.classAreas=function(t){return this.classShapes(t)+this.generateClass(Y.areas,t.id)},l.prototype.classRegion=function(t,e){return this.generateClass(Y.region,e)+" "+("class"in t?t.class:"")},l.prototype.classEvent=function(t){return this.generateClass(Y.eventRect,t.index)},l.prototype.classTarget=function(t){var e=this.config.data_classes[t],i="";return e&&(i=" "+Y.target+"-"+e),this.generateClass(Y.target,t)+i},l.prototype.classFocus=function(t){return this.classFocused(t)+this.classDefocused(t)},l.prototype.classFocused=function(t){return" "+(0<=this.focusedTargetIds.indexOf(t.id)?Y.focused:"")},l.prototype.classDefocused=function(t){return" "+(0<=this.defocusedTargetIds.indexOf(t.id)?Y.defocused:"")},l.prototype.classChartText=function(t){return Y.chartText+this.classTarget(t.id)},l.prototype.classChartLine=function(t){return Y.chartLine+this.classTarget(t.id)},l.prototype.classChartBar=function(t){return Y.chartBar+this.classTarget(t.id)},l.prototype.classChartArc=function(t){return Y.chartArc+this.classTarget(t.data.id)},l.prototype.getTargetSelectorSuffix=function(t){return this.generateTargetClass(t).replace(/([?!@#$%^&*()_=+,.<>'":;\[\]\/|~`{}\\])/g,"\\$1")},l.prototype.selectorTarget=function(t,e){return(e||"")+"."+Y.target+this.getTargetSelectorSuffix(t)},l.prototype.selectorTargets=function(t,e){var i=this;return(t=t||[]).length?t.map(function(t){return i.selectorTarget(t,e)}):null},l.prototype.selectorLegend=function(t){return"."+Y.legendItem+this.getTargetSelectorSuffix(t)},l.prototype.selectorLegends=function(t){var e=this;return t&&t.length?t.map(function(t){return e.selectorLegend(t)}):null},l.prototype.getClipPath=function(t){return"url("+(0<=window.navigator.appVersion.toLowerCase().indexOf("msie 9.")?"":document.URL.split("#")[0])+"#"+t+")"},l.prototype.appendClip=function(t,e){return t.append("clipPath").attr("id",e).append("rect")},l.prototype.getAxisClipX=function(t){var e=Math.max(30,this.margin.left);return t?-(1+e):-(e-1)},l.prototype.getAxisClipY=function(t){return t?-20:-this.margin.top},l.prototype.getXAxisClipX=function(){return this.getAxisClipX(!this.config.axis_rotated)},l.prototype.getXAxisClipY=function(){return this.getAxisClipY(!this.config.axis_rotated)},l.prototype.getYAxisClipX=function(){return this.config.axis_y_inner?-1:this.getAxisClipX(this.config.axis_rotated)},l.prototype.getYAxisClipY=function(){return this.getAxisClipY(this.config.axis_rotated)},l.prototype.getAxisClipWidth=function(t){var e=Math.max(30,this.margin.left),i=Math.max(30,this.margin.right);return t?this.width+2+e+i:this.margin.left+20},l.prototype.getAxisClipHeight=function(t){return(t?this.margin.bottom:this.margin.top+this.height)+20},l.prototype.getXAxisClipWidth=function(){return this.getAxisClipWidth(!this.config.axis_rotated)},l.prototype.getXAxisClipHeight=function(){return this.getAxisClipHeight(!this.config.axis_rotated)},l.prototype.getYAxisClipWidth=function(){return this.getAxisClipWidth(this.config.axis_rotated)+(this.config.axis_y_inner?20:0)},l.prototype.getYAxisClipHeight=function(){return this.getAxisClipHeight(this.config.axis_rotated)},l.prototype.generateColor=function(){var t=this.config,e=this.d3,n=t.data_colors,r=C(t.color_pattern)?t.color_pattern:e.schemeCategory10,a=t.data_color,o=[];return function(t){var e,i=t.id||t.data&&t.data.id||t;return n[i]instanceof Function?e=n[i](t):n[i]?e=n[i]:(o.indexOf(i)<0&&o.push(i),e=r[o.indexOf(i)%r.length],n[i]=e),a instanceof Function?a(e,t):e}},l.prototype.generateLevelColor=function(){var t=this.config,n=t.color_pattern,e=t.color_threshold,r="value"===e.unit,a=e.values&&e.values.length?e.values:[],o=e.max||100;return C(t.color_threshold)?function(t){var e,i=n[n.length-1];for(e=0;e<a.length;e++)if((r?t:100*t/o)<a[e]){i=n[e];break}return i}:null},l.prototype.getDefaultConfig=function(){var e={bindto:"#chart",svg_classname:void 0,size_width:void 0,size_height:void 0,padding_left:void 0,padding_right:void 0,padding_top:void 0,padding_bottom:void 0,resize_auto:!0,zoom_enabled:!1,zoom_initialRange:void 0,zoom_type:"scroll",zoom_disableDefaultBehavior:!1,zoom_privileged:!1,zoom_rescale:!1,zoom_onzoom:function(){},zoom_onzoomstart:function(){},zoom_onzoomend:function(){},zoom_x_min:void 0,zoom_x_max:void 0,interaction_brighten:!0,interaction_enabled:!0,onmouseover:function(){},onmouseout:function(){},onresize:function(){},onresized:function(){},oninit:function(){},onrendered:function(){},transition_duration:350,data_x:void 0,data_xs:{},data_xFormat:"%Y-%m-%d",data_xLocaltime:!0,data_xSort:!0,data_idConverter:function(t){return t},data_names:{},data_classes:{},data_groups:[],data_axes:{},data_type:void 0,data_types:{},data_labels:{},data_order:"desc",data_regions:{},data_color:void 0,data_colors:{},data_hide:!1,data_filter:void 0,data_selection_enabled:!1,data_selection_grouped:!1,data_selection_isselectable:function(){return!0},data_selection_multiple:!0,data_selection_draggable:!1,data_onclick:function(){},data_onmouseover:function(){},data_onmouseout:function(){},data_onselected:function(){},data_onunselected:function(){},data_url:void 0,data_headers:void 0,data_json:void 0,data_rows:void 0,data_columns:void 0,data_mimeType:void 0,data_keys:void 0,data_empty_label_text:"",subchart_show:!1,subchart_size_height:60,subchart_axis_x_show:!0,subchart_onbrush:function(){},color_pattern:[],color_threshold:{},legend_show:!0,legend_hide:!1,legend_position:"bottom",legend_inset_anchor:"top-left",legend_inset_x:10,legend_inset_y:0,legend_inset_step:void 0,legend_item_onclick:void 0,legend_item_onmouseover:void 0,legend_item_onmouseout:void 0,legend_equally:!1,legend_padding:0,legend_item_tile_width:10,legend_item_tile_height:10,axis_rotated:!1,axis_x_show:!0,axis_x_type:"indexed",axis_x_localtime:!0,axis_x_categories:[],axis_x_tick_centered:!1,axis_x_tick_format:void 0,axis_x_tick_culling:{},axis_x_tick_culling_max:10,axis_x_tick_count:void 0,axis_x_tick_fit:!0,axis_x_tick_values:null,axis_x_tick_rotate:0,axis_x_tick_outer:!0,axis_x_tick_multiline:!0,axis_x_tick_multilineMax:0,axis_x_tick_width:null,axis_x_max:void 0,axis_x_min:void 0,axis_x_padding:{},axis_x_height:void 0,axis_x_selection:void 0,axis_x_label:{},axis_x_inner:void 0,axis_y_show:!0,axis_y_type:void 0,axis_y_max:void 0,axis_y_min:void 0,axis_y_inverted:!1,axis_y_center:void 0,axis_y_inner:void 0,axis_y_label:{},axis_y_tick_format:void 0,axis_y_tick_outer:!0,axis_y_tick_values:null,axis_y_tick_rotate:0,axis_y_tick_count:void 0,axis_y_tick_time_type:void 0,axis_y_tick_time_interval:void 0,axis_y_padding:{},axis_y_default:void 0,axis_y2_show:!1,axis_y2_max:void 0,axis_y2_min:void 0,axis_y2_inverted:!1,axis_y2_center:void 0,axis_y2_inner:void 0,axis_y2_label:{},axis_y2_tick_format:void 0,axis_y2_tick_outer:!0,axis_y2_tick_values:null,axis_y2_tick_count:void 0,axis_y2_padding:{},axis_y2_default:void 0,grid_x_show:!1,grid_x_type:"tick",grid_x_lines:[],grid_y_show:!1,grid_y_lines:[],grid_y_ticks:10,grid_focus_show:!0,grid_lines_front:!0,point_show:!0,point_r:2.5,point_sensitivity:10,point_focus_expand_enabled:!0,point_focus_expand_r:void 0,point_select_r:void 0,line_connectNull:!1,line_step_type:"step",bar_width:void 0,bar_width_ratio:.6,bar_width_max:void 0,bar_zerobased:!0,bar_space:0,area_zerobased:!0,area_above:!1,pie_label_show:!0,pie_label_format:void 0,pie_label_threshold:.05,pie_label_ratio:void 0,pie_expand:{},pie_expand_duration:50,gauge_fullCircle:!1,gauge_label_show:!0,gauge_labelLine_show:!0,gauge_label_format:void 0,gauge_min:0,gauge_max:100,gauge_startingAngle:-1*Math.PI/2,gauge_label_extents:void 0,gauge_units:void 0,gauge_width:void 0,gauge_arcs_minWidth:5,gauge_expand:{},gauge_expand_duration:50,donut_label_show:!0,donut_label_format:void 0,donut_label_threshold:.05,donut_label_ratio:void 0,donut_width:void 0,donut_title:"",donut_expand:{},donut_expand_duration:50,spline_interpolation_type:"cardinal",regions:[],tooltip_show:!0,tooltip_grouped:!0,tooltip_order:void 0,tooltip_format_title:void 0,tooltip_format_name:void 0,tooltip_format_value:void 0,tooltip_position:void 0,tooltip_contents:function(t,e,i,n){return this.getTooltipContent?this.getTooltipContent(t,e,i,n):""},tooltip_init_show:!1,tooltip_init_x:0,tooltip_init_position:{top:"0px",left:"50px"},tooltip_onshow:function(){},tooltip_onhide:function(){},title_text:void 0,title_padding:{top:0,right:0,bottom:0,left:0},title_position:"top-center"};return Object.keys(this.additionalConfig).forEach(function(t){e[t]=this.additionalConfig[t]},this),e},l.prototype.additionalConfig={},l.prototype.loadConfig=function(e){var i,n,r,a=this.config;Object.keys(a).forEach(function(t){i=e,n=t.split("_"),r=function t(){var e=n.shift();return e&&i&&"object"===s(i)&&e in i?(i=i[e],t()):e?void 0:i}(),k(r)&&(a[t]=r)})},l.prototype.convertUrlToData=function(t,e,i,n,r){var a,o,s=this,c=e||"csv";o="json"===c?(a=s.d3.json,s.convertJsonToData):(a="tsv"===c?s.d3.tsv:s.d3.csv,s.convertXsvToData),a(t,i).then(function(t){r.call(s,o.call(s,t,n))}).catch(function(t){throw t})},l.prototype.convertXsvToData=function(t){var e=t.columns;return 0===t.length?{keys:e,rows:[e.reduce(function(t,e){return Object.assign(t,(r=null,(n=e)in(i={})?Object.defineProperty(i,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):i[n]=r,i));var i,n,r},{})]}:{keys:e,rows:[].concat(t)}},l.prototype.convertJsonToData=function(e,t){var r,a=this,o=[];return t?(t.x?(r=t.value.concat(t.x),a.config.data_x=t.x):r=t.value,o.push(r),e.forEach(function(i){var n=[];r.forEach(function(t){var e=a.findValueInJson(i,t);v(e)&&(e=null),n.push(e)}),o.push(n)}),a.convertRowsToData(o)):(Object.keys(e).forEach(function(t){o.push([t].concat(e[t]))}),a.convertColumnsToData(o))},l.prototype.findValueInJson=function(t,e){for(var i=(e=(e=e.replace(/\[(\w+)\]/g,".$1")).replace(/^\./,"")).split("."),n=0;n<i.length;++n){var r=i[n];if(!(r in t))return;t=t[r]}return t},l.prototype.convertRowsToData=function(t){for(var e=[],i=t[0],n=1;n<t.length;n++){for(var r={},a=0;a<t[n].length;a++){if(v(t[n][a]))throw new Error("Source data is missing a component at ("+n+","+a+")!");r[i[a]]=t[n][a]}e.push(r)}return{keys:i,rows:e}},l.prototype.convertColumnsToData=function(t){for(var e=[],i=[],n=0;n<t.length;n++){for(var r=t[n][0],a=1;a<t[n].length;a++){if(v(e[a-1])&&(e[a-1]={}),v(t[n][a]))throw new Error("Source data is missing a component at ("+n+","+a+")!");e[a-1][r]=t[n][a]}i.push(r)}return{keys:i,rows:e}},l.prototype.convertDataToTargets=function(t,n){var e,i,r,a,c=this,d=c.config;return o(t)?a=Object.keys(t[0]):(a=t.keys,t=t.rows),i=a.filter(c.isNotX,c),r=a.filter(c.isX,c),i.forEach(function(i){var e=c.getXKey(i);c.isCustomX()||c.isTimeSeries()?0<=r.indexOf(e)?c.data.xs[i]=(n&&c.data.xs[i]?c.data.xs[i]:[]).concat(t.map(function(t){return t[e]}).filter(P).map(function(t,e){return c.generateTargetX(t,i,e)})):d.data_x?c.data.xs[i]=c.getOtherTargetXs():C(d.data_xs)&&(c.data.xs[i]=c.getXValuesOfXKey(e,c.data.targets)):c.data.xs[i]=t.map(function(t,e){return e})}),i.forEach(function(t){if(!c.data.xs[t])throw new Error('x is not defined for id = "'+t+'".')}),(e=i.map(function(a,o){var s=d.data_idConverter(a);return{id:s,id_org:a,values:t.map(function(t,e){var i,n=t[c.getXKey(a)],r=null===t[a]||isNaN(t[a])?null:+t[a];return c.isCustomX()&&c.isCategorized()&&!v(n)?(0===o&&0===e&&(d.axis_x_categories=[]),-1===(i=d.axis_x_categories.indexOf(n))&&(i=d.axis_x_categories.length,d.axis_x_categories.push(n))):i=c.generateTargetX(n,a,e),(v(t[a])||c.data.xs[a].length<=e)&&(i=void 0),{x:i,value:r,id:s}}).filter(function(t){return k(t.x)})}})).forEach(function(t){var e;d.data_xSort&&(t.values=t.values.sort(function(t,e){return(t.x||0===t.x?t.x:1/0)-(e.x||0===e.x?e.x:1/0)})),e=0,t.values.forEach(function(t){t.index=e++}),c.data.xs[t.id].sort(function(t,e){return t-e})}),c.hasNegativeValue=c.hasNegativeValueInTargets(e),c.hasPositiveValue=c.hasPositiveValueInTargets(e),d.data_type&&c.setTargetType(c.mapToIds(e).filter(function(t){return!(t in d.data_types)}),d.data_type),e.forEach(function(t){c.addCache(t.id_org,t)}),e},l.prototype.isX=function(t){var e,i,n,r=this.config;return r.data_x&&t===r.data_x||C(r.data_xs)&&(e=r.data_xs,i=t,n=!1,Object.keys(e).forEach(function(t){e[t]===i&&(n=!0)}),n)},l.prototype.isNotX=function(t){return!this.isX(t)},l.prototype.getXKey=function(t){var e=this.config;return e.data_x?e.data_x:C(e.data_xs)?e.data_xs[t]:null},l.prototype.getXValuesOfXKey=function(e,t){var i,n=this;return(t&&C(t)?n.mapToIds(t):[]).forEach(function(t){n.getXKey(t)===e&&(i=n.data.xs[t])}),i},l.prototype.getXValue=function(t,e){return t in this.data.xs&&this.data.xs[t]&&P(this.data.xs[t][e])?this.data.xs[t][e]:e},l.prototype.getOtherTargetXs=function(){var t=Object.keys(this.data.xs);return t.length?this.data.xs[t[0]]:null},l.prototype.getOtherTargetX=function(t){var e=this.getOtherTargetXs();return e&&t<e.length?e[t]:null},l.prototype.addXs=function(e){var i=this;Object.keys(e).forEach(function(t){i.config.data_xs[t]=e[t]})},l.prototype.addName=function(t){var e;return t&&(e=this.config.data_names[t.id],t.name=void 0!==e?e:t.id),t},l.prototype.getValueOnIndex=function(t,e){var i=t.filter(function(t){return t.index===e});return i.length?i[0]:null},l.prototype.updateTargetX=function(t,n){var r=this;t.forEach(function(i){i.values.forEach(function(t,e){t.x=r.generateTargetX(n[e],i.id,e)}),r.data.xs[i.id]=n})},l.prototype.updateTargetXs=function(t,e){var i=this;t.forEach(function(t){e[t.id]&&i.updateTargetX([t],e[t.id])})},l.prototype.generateTargetX=function(t,e,i){var n=this;return n.isTimeSeries()?t?n.parseDate(t):n.parseDate(n.getXValue(e,i)):n.isCustomX()&&!n.isCategorized()?P(t)?+t:n.getXValue(e,i):i},l.prototype.cloneTarget=function(t){return{id:t.id,id_org:t.id_org,values:t.values.map(function(t){return{x:t.x,value:t.value,id:t.id}})}},l.prototype.getMaxDataCount=function(){return this.d3.max(this.data.targets,function(t){return t.values.length})},l.prototype.mapToIds=function(t){return t.map(function(t){return t.id})},l.prototype.mapToTargetIds=function(t){return t?[].concat(t):this.mapToIds(this.data.targets)},l.prototype.hasTarget=function(t,e){var i,n=this.mapToIds(t);for(i=0;i<n.length;i++)if(n[i]===e)return!0;return!1},l.prototype.isTargetToShow=function(t){return this.hiddenTargetIds.indexOf(t)<0},l.prototype.isLegendToShow=function(t){return this.hiddenLegendIds.indexOf(t)<0},l.prototype.filterTargetsToShow=function(t){var e=this;return t.filter(function(t){return e.isTargetToShow(t.id)})},l.prototype.mapTargetsToUniqueXs=function(t){var e=this.d3.set(this.d3.merge(t.map(function(t){return t.values.map(function(t){return+t.x})}))).values();return(e=this.isTimeSeries()?e.map(function(t){return new Date(+t)}):e.map(function(t){return+t})).sort(function(t,e){return t<e?-1:e<t?1:e<=t?0:NaN})},l.prototype.addHiddenTargetIds=function(t){t=t instanceof Array?t:new Array(t);for(var e=0;e<t.length;e++)this.hiddenTargetIds.indexOf(t[e])<0&&(this.hiddenTargetIds=this.hiddenTargetIds.concat(t[e]))},l.prototype.removeHiddenTargetIds=function(e){this.hiddenTargetIds=this.hiddenTargetIds.filter(function(t){return e.indexOf(t)<0})},l.prototype.addHiddenLegendIds=function(t){t=t instanceof Array?t:new Array(t);for(var e=0;e<t.length;e++)this.hiddenLegendIds.indexOf(t[e])<0&&(this.hiddenLegendIds=this.hiddenLegendIds.concat(t[e]))},l.prototype.removeHiddenLegendIds=function(e){this.hiddenLegendIds=this.hiddenLegendIds.filter(function(t){return e.indexOf(t)<0})},l.prototype.getValuesAsIdKeyed=function(t){var i={};return t.forEach(function(e){i[e.id]=[],e.values.forEach(function(t){i[e.id].push(t.value)})}),i},l.prototype.checkValueInTargets=function(t,e){var i,n,r,a=Object.keys(t);for(i=0;i<a.length;i++)for(r=t[a[i]].values,n=0;n<r.length;n++)if(e(r[n].value))return!0;return!1},l.prototype.hasNegativeValueInTargets=function(t){return this.checkValueInTargets(t,function(t){return t<0})},l.prototype.hasPositiveValueInTargets=function(t){return this.checkValueInTargets(t,function(t){return 0<t})},l.prototype.isOrderDesc=function(){var t=this.config;return"string"==typeof t.data_order&&"desc"===t.data_order.toLowerCase()},l.prototype.isOrderAsc=function(){var t=this.config;return"string"==typeof t.data_order&&"asc"===t.data_order.toLowerCase()},l.prototype.getOrderFunction=function(){var t=this.config,r=this.isOrderAsc(),e=this.isOrderDesc();if(r||e){var a=function(t,e){return t+Math.abs(e.value)};return function(t,e){var i=t.values.reduce(a,0),n=e.values.reduce(a,0);return r?n-i:i-n}}if(h(t.data_order))return t.data_order;if(o(t.data_order)){var i=t.data_order;return function(t,e){return i.indexOf(t.id)-i.indexOf(e.id)}}},l.prototype.orderTargets=function(t){var e=this.getOrderFunction();return e&&t.sort(e),t},l.prototype.filterByX=function(t,e){return this.d3.merge(t.map(function(t){return t.values})).filter(function(t){return t.x-e==0})},l.prototype.filterRemoveNull=function(t){return t.filter(function(t){return P(t.value)})},l.prototype.filterByXDomain=function(t,e){return t.map(function(t){return{id:t.id,id_org:t.id_org,values:t.values.filter(function(t){return e[0]<=t.x&&t.x<=e[1]})}})},l.prototype.hasDataLabel=function(){var t=this.config;return!("boolean"!=typeof t.data_labels||!t.data_labels)||!("object"!==s(t.data_labels)||!C(t.data_labels))},l.prototype.getDataLabelLength=function(t,e,i){var n=this,r=[0,0];return n.selectChart.select("svg").selectAll(".dummy").data([t,e]).enter().append("text").text(function(t){return n.dataLabelFormat(t.id)(t)}).each(function(t,e){r[e]=1.3*this.getBoundingClientRect()[i]}).remove(),r},l.prototype.isNoneArc=function(t){return this.hasTarget(this.data.targets,t.id)},l.prototype.isArc=function(t){return"data"in t&&this.hasTarget(this.data.targets,t.data.id)},l.prototype.findClosestFromTargets=function(t,e){var i,n=this;return i=t.map(function(t){return n.findClosest(t.values,e)}),n.findClosest(i,e)},l.prototype.findClosest=function(t,i){var n,r=this,a=r.config.point_sensitivity;return t.filter(function(t){return t&&r.isBarType(t.id)}).forEach(function(t){var e=r.main.select("."+Y.bars+r.getTargetSelectorSuffix(t.id)+" ."+Y.bar+"-"+t.index).node();!n&&r.isWithinBar(r.d3.mouse(e),e)&&(n=t)}),t.filter(function(t){return t&&!r.isBarType(t.id)}).forEach(function(t){var e=r.dist(t,i);e<a&&(a=e,n=t)}),n},l.prototype.dist=function(t,e){var i=this.config,n=i.axis_rotated?1:0,r=i.axis_rotated?0:1,a=this.circleY(t,t.index),o=this.x(t.x);return Math.sqrt(Math.pow(o-e[n],2)+Math.pow(a-e[r],2))},l.prototype.convertValuesToStep=function(t){var e,i=[].concat(t);if(!this.isCategorized())return t;for(e=t.length+1;0<e;e--)i[e]=i[e-1];return i[0]={x:i[0].x-1,value:i[0].value,id:i[0].id},i[t.length+1]={x:i[t.length].x+1,value:i[t.length].value,id:i[t.length].id},i},l.prototype.updateDataAttributes=function(t,e){var i=this.config["data_"+t];return void 0===e||(Object.keys(e).forEach(function(t){i[t]=e[t]}),this.redraw({withLegend:!0})),i},l.prototype.load=function(i,n){var r=this;i&&(n.filter&&(i=i.filter(n.filter)),(n.type||n.types)&&i.forEach(function(t){var e=n.types&&n.types[t.id]?n.types[t.id]:n.type;r.setTargetType(t.id,e)}),r.data.targets.forEach(function(t){for(var e=0;e<i.length;e++)if(t.id===i[e].id){t.values=i[e].values,i.splice(e,1);break}}),r.data.targets=r.data.targets.concat(i)),r.updateTargets(r.data.targets),r.redraw({withUpdateOrgXDomain:!0,withUpdateXDomain:!0,withLegend:!0}),n.done&&n.done()},l.prototype.loadFromArgs=function(e){var i=this;e.data?i.load(i.convertDataToTargets(e.data),e):e.url?i.convertUrlToData(e.url,e.mimeType,e.headers,e.keys,function(t){i.load(i.convertDataToTargets(t),e)}):e.json?i.load(i.convertDataToTargets(i.convertJsonToData(e.json,e.keys)),e):e.rows?i.load(i.convertDataToTargets(i.convertRowsToData(e.rows)),e):e.columns?i.load(i.convertDataToTargets(i.convertColumnsToData(e.columns)),e):i.load(null,e)},l.prototype.unload=function(t,e){var i=this;e||(e=function(){}),(t=t.filter(function(t){return i.hasTarget(i.data.targets,t)}))&&0!==t.length?(i.svg.selectAll(t.map(function(t){return i.selectorTarget(t)})).transition().style("opacity",0).remove().call(i.endall,e),t.forEach(function(e){i.withoutFadeIn[e]=!1,i.legend&&i.legend.selectAll("."+Y.legendItem+i.getTargetSelectorSuffix(e)).remove(),i.data.targets=i.data.targets.filter(function(t){return t.id!==e})})):e()},l.prototype.getYDomainMin=function(t){var e,i,n,r,a,o,s=this,c=s.config,d=s.mapToIds(t),l=s.getValuesAsIdKeyed(t);if(0<c.data_groups.length)for(o=s.hasNegativeValueInTargets(t),e=0;e<c.data_groups.length;e++)if(0!==(r=c.data_groups[e].filter(function(t){return 0<=d.indexOf(t)})).length)for(n=r[0],o&&l[n]&&l[n].forEach(function(t,e){l[n][e]=t<0?t:0}),i=1;i<r.length;i++)a=r[i],l[a]&&l[a].forEach(function(t,e){s.axis.getId(a)!==s.axis.getId(n)||!l[n]||o&&0<+t||(l[n][e]+=+t)});return s.d3.min(Object.keys(l).map(function(t){return s.d3.min(l[t])}))},l.prototype.getYDomainMax=function(t){var e,i,n,r,a,o,s=this,c=s.config,d=s.mapToIds(t),l=s.getValuesAsIdKeyed(t);if(0<c.data_groups.length)for(o=s.hasPositiveValueInTargets(t),e=0;e<c.data_groups.length;e++)if(0!==(r=c.data_groups[e].filter(function(t){return 0<=d.indexOf(t)})).length)for(n=r[0],o&&l[n]&&l[n].forEach(function(t,e){l[n][e]=0<t?t:0}),i=1;i<r.length;i++)a=r[i],l[a]&&l[a].forEach(function(t,e){s.axis.getId(a)!==s.axis.getId(n)||!l[n]||o&&+t<0||(l[n][e]+=+t)});return s.d3.max(Object.keys(l).map(function(t){return s.d3.max(l[t])}))},l.prototype.getYDomain=function(t,e,i){var n,r,a,o,s,c,d,l,u,h,g=this,p=g.config,f=t.filter(function(t){return g.axis.getId(t.id)===e}),_=i?g.filterByXDomain(f,i):f,x="y2"===e?p.axis_y2_min:p.axis_y_min,y="y2"===e?p.axis_y2_max:p.axis_y_max,m=g.getYDomainMin(_),S=g.getYDomainMax(_),w="y2"===e?p.axis_y2_center:p.axis_y_center,v=g.hasType("bar",_)&&p.bar_zerobased||g.hasType("area",_)&&p.area_zerobased,b="y2"===e?p.axis_y2_inverted:p.axis_y_inverted,A=g.hasDataLabel()&&p.axis_rotated,T=g.hasDataLabel()&&!p.axis_rotated;return m=P(x)?x:P(y)?m<y?m:y-10:m,S=P(y)?y:P(x)?x<S?S:x+10:S,0===_.length?"y2"===e?g.y2.domain():g.y.domain():(isNaN(m)&&(m=0),isNaN(S)&&(S=m),m===S&&(m<0?S=0:m=0),u=0<=m&&0<=S,h=m<=0&&S<=0,(P(x)&&u||P(y)&&h)&&(v=!1),v&&(u&&(m=0),h&&(S=0)),a=o=.1*(r=Math.abs(S-m)),void 0!==w&&(S=w+(s=Math.max(Math.abs(m),Math.abs(S))),m=w-s),A?(c=g.getDataLabelLength(m,S,"width"),d=R(g.y.range()),a+=r*((l=[c[0]/d,c[1]/d])[1]/(1-l[0]-l[1])),o+=r*(l[0]/(1-l[0]-l[1]))):T&&(c=g.getDataLabelLength(m,S,"height"),a+=g.axis.convertPixelsToAxisPadding(c[1],r),o+=g.axis.convertPixelsToAxisPadding(c[0],r)),"y"===e&&C(p.axis_y_padding)&&(a=g.axis.getPadding(p.axis_y_padding,"top",a,r),o=g.axis.getPadding(p.axis_y_padding,"bottom",o,r)),"y2"===e&&C(p.axis_y2_padding)&&(a=g.axis.getPadding(p.axis_y2_padding,"top",a,r),o=g.axis.getPadding(p.axis_y2_padding,"bottom",o,r)),v&&(u&&(o=m),h&&(a=-S)),n=[m-o,S+a],b?n.reverse():n)},l.prototype.getXDomainMin=function(t){var e=this,i=e.config;return k(i.axis_x_min)?e.isTimeSeries()?this.parseDate(i.axis_x_min):i.axis_x_min:e.d3.min(t,function(t){return e.d3.min(t.values,function(t){return t.x})})},l.prototype.getXDomainMax=function(t){var e=this,i=e.config;return k(i.axis_x_max)?e.isTimeSeries()?this.parseDate(i.axis_x_max):i.axis_x_max:e.d3.max(t,function(t){return e.d3.max(t.values,function(t){return t.x})})},l.prototype.getXDomainPadding=function(t){var e,i,n,r,a=this.config,o=t[1]-t[0];return i=this.isCategorized()?0:this.hasType("bar")?1<(e=this.getMaxDataCount())?o/(e-1)/2:.5:.01*o,"object"===s(a.axis_x_padding)&&C(a.axis_x_padding)?(n=P(a.axis_x_padding.left)?a.axis_x_padding.left:i,r=P(a.axis_x_padding.right)?a.axis_x_padding.right:i):n=r="number"==typeof a.axis_x_padding?a.axis_x_padding:i,{left:n,right:r}},l.prototype.getXDomain=function(t){var e=this,i=[e.getXDomainMin(t),e.getXDomainMax(t)],n=i[0],r=i[1],a=e.getXDomainPadding(i),o=0,s=0;return n-r!=0||e.isCategorized()||(r=e.isTimeSeries()?(n=new Date(.5*n.getTime()),new Date(1.5*r.getTime())):(n=0===n?1:.5*n,0===r?-1:1.5*r)),(n||0===n)&&(o=e.isTimeSeries()?new Date(n.getTime()-a.left):n-a.left),(r||0===r)&&(s=e.isTimeSeries()?new Date(r.getTime()+a.right):r+a.right),[o,s]},l.prototype.updateXDomain=function(t,e,i,n,r){var a=this,o=a.config;return i&&(a.x.domain(r||a.d3.extent(a.getXDomain(t))),a.orgXDomain=a.x.domain(),o.zoom_enabled&&a.zoom.update(),a.subX.domain(a.x.domain()),a.brush&&a.brush.updateScale(a.subX)),e&&a.x.domain(r||(!a.brush||a.brush.empty()?a.orgXDomain:a.brush.selectionAsValue())),n&&a.x.domain(a.trimXDomain(a.x.orgDomain())),a.x.domain()},l.prototype.trimXDomain=function(t){var e=this.getZoomDomain(),i=e[0],n=e[1];return t[0]<=i&&(t[1]=+t[1]+(i-t[0]),t[0]=i),n<=t[1]&&(t[0]=+t[0]-(t[1]-n),t[1]=n),t},l.prototype.drag=function(t){var e,i,n,r,h,g,p,f,_=this,a=_.config,o=_.main,x=_.d3;_.hasArcType()||a.data_selection_enabled&&a.data_selection_multiple&&(e=_.dragStart[0],i=_.dragStart[1],n=t[0],r=t[1],h=Math.min(e,n),g=Math.max(e,n),p=a.data_selection_grouped?_.margin.top:Math.min(i,r),f=a.data_selection_grouped?_.height:Math.max(i,r),o.select("."+Y.dragarea).attr("x",h).attr("y",p).attr("width",g-h).attr("height",f-p),o.selectAll("."+Y.shapes).selectAll("."+Y.shape).filter(function(t){return a.data_selection_isselectable(t)}).each(function(t,e){var i,n,r,a,o,s,c=x.select(this),d=c.classed(Y.SELECTED),l=c.classed(Y.INCLUDED),u=!1;if(c.classed(Y.circle))i=1*c.attr("cx"),n=1*c.attr("cy"),o=_.togglePoint,u=h<i&&i<g&&p<n&&n<f;else{if(!c.classed(Y.bar))return;i=(s=y(this)).x,n=s.y,r=s.width,a=s.height,o=_.togglePath,u=!(g<i||i+r<h||f<n||n+a<p)}u^l&&(c.classed(Y.INCLUDED,!l),c.classed(Y.SELECTED,!d),o.call(_,!d,c,t,e))}))},l.prototype.dragstart=function(t){var e=this,i=e.config;e.hasArcType()||i.data_selection_enabled&&(e.dragStart=t,e.main.select("."+Y.chart).append("rect").attr("class",Y.dragarea).style("opacity",.1),e.dragging=!0)},l.prototype.dragend=function(){var t=this,e=t.config;t.hasArcType()||e.data_selection_enabled&&(t.main.select("."+Y.dragarea).transition().duration(100).style("opacity",0).remove(),t.main.selectAll("."+Y.shape).classed(Y.INCLUDED,!1),t.dragging=!1)},l.prototype.getYFormat=function(t){var n=this,r=t&&!n.hasType("gauge")?n.defaultArcValueFormat:n.yFormat,a=t&&!n.hasType("gauge")?n.defaultArcValueFormat:n.y2Format;return function(t,e,i){return("y2"===n.axis.getId(i)?a:r).call(n,t,e)}},l.prototype.yFormat=function(t){var e=this.config;return(e.axis_y_tick_format?e.axis_y_tick_format:this.defaultValueFormat)(t)},l.prototype.y2Format=function(t){var e=this.config;return(e.axis_y2_tick_format?e.axis_y2_tick_format:this.defaultValueFormat)(t)},l.prototype.defaultValueFormat=function(t){return P(t)?+t:""},l.prototype.defaultArcValueFormat=function(t,e){return(100*e).toFixed(1)+"%"},l.prototype.dataLabelFormat=function(t){var e=this.config.data_labels,i=function(t){return P(t)?+t:""};return"function"==typeof e.format?e.format:"object"===s(e.format)?e.format[t]?!0===e.format[t]?i:e.format[t]:function(){return""}:i},l.prototype.initGrid=function(){var t=this,e=t.config,i=t.d3;t.grid=t.main.append("g").attr("clip-path",t.clipPathForGrid).attr("class",Y.grid),e.grid_x_show&&t.grid.append("g").attr("class",Y.xgrids),e.grid_y_show&&t.grid.append("g").attr("class",Y.ygrids),e.grid_focus_show&&t.grid.append("g").attr("class",Y.xgridFocus).append("line").attr("class",Y.xgridFocus),t.xgrid=i.selectAll([]),e.grid_lines_front||t.initGridLines()},l.prototype.initGridLines=function(){var t=this,e=t.d3;t.gridLines=t.main.append("g").attr("clip-path",t.clipPathForGrid).attr("class",Y.grid+" "+Y.gridLines),t.gridLines.append("g").attr("class",Y.xgridLines),t.gridLines.append("g").attr("class",Y.ygridLines),t.xgridLines=e.selectAll([])},l.prototype.updateXGrid=function(t){var e=this,i=e.config,n=e.d3,r=e.generateGridData(i.grid_x_type,e.x),a=e.isCategorized()?e.xAxis.tickOffset():0;e.xgridAttr=i.axis_rotated?{x1:0,x2:e.width,y1:function(t){return e.x(t)-a},y2:function(t){return e.x(t)-a}}:{x1:function(t){return e.x(t)+a},x2:function(t){return e.x(t)+a},y1:0,y2:e.height},e.xgridAttr.opacity=function(){return+n.select(this).attr(i.axis_rotated?"y1":"x1")===(i.axis_rotated?e.height:0)?0:1};var o=e.main.select("."+Y.xgrids).selectAll("."+Y.xgrid).data(r),s=o.enter().append("line").attr("class",Y.xgrid).attr("x1",e.xgridAttr.x1).attr("x2",e.xgridAttr.x2).attr("y1",e.xgridAttr.y1).attr("y2",e.xgridAttr.y2).style("opacity",0);e.xgrid=s.merge(o),t||e.xgrid.attr("x1",e.xgridAttr.x1).attr("x2",e.xgridAttr.x2).attr("y1",e.xgridAttr.y1).attr("y2",e.xgridAttr.y2).style("opacity",e.xgridAttr.opacity),o.exit().remove()},l.prototype.updateYGrid=function(){var t=this,e=t.config,i=t.yAxis.tickValues()||t.y.ticks(e.grid_y_ticks),n=t.main.select("."+Y.ygrids).selectAll("."+Y.ygrid).data(i),r=n.enter().append("line").attr("class",Y.ygrid);t.ygrid=r.merge(n),t.ygrid.attr("x1",e.axis_rotated?t.y:0).attr("x2",e.axis_rotated?t.y:t.width).attr("y1",e.axis_rotated?0:t.y).attr("y2",e.axis_rotated?t.height:t.y),n.exit().remove(),t.smoothLines(t.ygrid,"grid")},l.prototype.gridTextAnchor=function(t){return t.position?t.position:"end"},l.prototype.gridTextDx=function(t){return"start"===t.position?4:"middle"===t.position?0:-4},l.prototype.xGridTextX=function(t){return"start"===t.position?-this.height:"middle"===t.position?-this.height/2:0},l.prototype.yGridTextX=function(t){return"start"===t.position?0:"middle"===t.position?this.width/2:this.width},l.prototype.updateGrid=function(t){var e,i,n,r,a=this,o=a.main,s=a.config,c=a.xv.bind(a),d=a.yv.bind(a),l=a.xGridTextX.bind(a),u=a.yGridTextX.bind(a);a.grid.style("visibility",a.hasArcType()?"hidden":"visible"),o.select("line."+Y.xgridFocus).style("visibility","hidden"),s.grid_x_show&&a.updateXGrid(),(i=(e=o.select("."+Y.xgridLines).selectAll("."+Y.xgridLine).data(s.grid_x_lines)).enter().append("g").attr("class",function(t){return Y.xgridLine+(t.class?" "+t.class:"")})).append("line").attr("x1",s.axis_rotated?0:c).attr("x2",s.axis_rotated?a.width:c).attr("y1",s.axis_rotated?c:0).attr("y2",s.axis_rotated?c:a.height).style("opacity",0),i.append("text").attr("text-anchor",a.gridTextAnchor).attr("transform",s.axis_rotated?"":"rotate(-90)").attr("x",s.axis_rotated?u:l).attr("y",c).attr("dx",a.gridTextDx).attr("dy",-5).style("opacity",0),a.xgridLines=i.merge(e),e.exit().transition().duration(t).style("opacity",0).remove(),s.grid_y_show&&a.updateYGrid(),(r=(n=o.select("."+Y.ygridLines).selectAll("."+Y.ygridLine).data(s.grid_y_lines)).enter().append("g").attr("class",function(t){return Y.ygridLine+(t.class?" "+t.class:"")})).append("line").attr("x1",s.axis_rotated?d:0).attr("x2",s.axis_rotated?d:a.width).attr("y1",s.axis_rotated?0:d).attr("y2",s.axis_rotated?a.height:d).style("opacity",0),r.append("text").attr("text-anchor",a.gridTextAnchor).attr("transform",s.axis_rotated?"rotate(-90)":"").attr("x",s.axis_rotated?l:u).attr("y",d).attr("dx",a.gridTextDx).attr("dy",-5).style("opacity",0),a.ygridLines=r.merge(n),a.ygridLines.select("line").transition().duration(t).attr("x1",s.axis_rotated?d:0).attr("x2",s.axis_rotated?d:a.width).attr("y1",s.axis_rotated?0:d).attr("y2",s.axis_rotated?a.height:d).style("opacity",1),a.ygridLines.select("text").transition().duration(t).attr("x",s.axis_rotated?a.xGridTextX.bind(a):a.yGridTextX.bind(a)).attr("y",d).text(function(t){return t.text}).style("opacity",1),n.exit().transition().duration(t).style("opacity",0).remove()},l.prototype.redrawGrid=function(t,e){var i=this,n=i.config,r=i.xv.bind(i),a=i.xgridLines.select("line"),o=i.xgridLines.select("text");return[(t?a.transition(e):a).attr("x1",n.axis_rotated?0:r).attr("x2",n.axis_rotated?i.width:r).attr("y1",n.axis_rotated?r:0).attr("y2",n.axis_rotated?r:i.height).style("opacity",1),(t?o.transition(e):o).attr("x",n.axis_rotated?i.yGridTextX.bind(i):i.xGridTextX.bind(i)).attr("y",r).text(function(t){return t.text}).style("opacity",1)]},l.prototype.showXGridFocus=function(t){var e=this,i=e.config,n=t.filter(function(t){return t&&P(t.value)}),r=e.main.selectAll("line."+Y.xgridFocus),a=e.xx.bind(e);i.tooltip_show&&(e.hasType("scatter")||e.hasArcType()||(r.style("visibility","visible").data([n[0]]).attr(i.axis_rotated?"y1":"x1",a).attr(i.axis_rotated?"y2":"x2",a),e.smoothLines(r,"grid")))},l.prototype.hideXGridFocus=function(){this.main.select("line."+Y.xgridFocus).style("visibility","hidden")},l.prototype.updateXgridFocus=function(){var t=this.config;this.main.select("line."+Y.xgridFocus).attr("x1",t.axis_rotated?0:-10).attr("x2",t.axis_rotated?this.width:-10).attr("y1",t.axis_rotated?-10:0).attr("y2",t.axis_rotated?-10:this.height)},l.prototype.generateGridData=function(t,e){var i,n,r,a,o=[],s=this.main.select("."+Y.axisX).selectAll(".tick").size();if("year"===t)for(n=(i=this.getXDomain())[0].getFullYear(),r=i[1].getFullYear(),a=n;a<=r;a++)o.push(new Date(a+"-01-01 00:00:00"));else(o=e.ticks(10)).length>s&&(o=o.filter(function(t){return(""+t).indexOf(".")<0}));return o},l.prototype.getGridFilterToRemove=function(t){return t?function(e){var i=!1;return[].concat(t).forEach(function(t){("value"in t&&e.value===t.value||"class"in t&&e.class===t.class)&&(i=!0)}),i}:function(){return!0}},l.prototype.removeGridLines=function(t,e){var i=this.config,n=this.getGridFilterToRemove(t),r=function(t){return!n(t)},a=e?Y.xgridLines:Y.ygridLines,o=e?Y.xgridLine:Y.ygridLine;this.main.select("."+a).selectAll("."+o).filter(n).transition().duration(i.transition_duration).style("opacity",0).remove(),e?i.grid_x_lines=i.grid_x_lines.filter(r):i.grid_y_lines=i.grid_y_lines.filter(r)},l.prototype.initEventRect=function(){var t=this,e=t.config;t.main.select("."+Y.chart).append("g").attr("class",Y.eventRects).style("fill-opacity",0),t.eventRect=t.main.select("."+Y.eventRects).append("rect").attr("class",Y.eventRect),e.zoom_enabled&&t.zoom&&(t.eventRect.call(t.zoom).on("dblclick.zoom",null),e.zoom_initialRange&&t.eventRect.transition().duration(0).call(t.zoom.transform,t.zoomTransform(e.zoom_initialRange)))},l.prototype.redrawEventRect=function(){var t,e,r=this,a=r.d3,o=r.config;function s(){r.svg.select("."+Y.eventRect).style("cursor",null),r.hideXGridFocus(),r.hideTooltip(),r.unexpandCircles(),r.unexpandBars()}t=r.width,e=r.height,r.main.select("."+Y.eventRects).style("cursor",o.zoom_enabled?o.axis_rotated?"ns-resize":"ew-resize":null),r.eventRect.attr("x",0).attr("y",0).attr("width",t).attr("height",e).on("mouseout",o.interaction_enabled?function(){o&&(r.hasArcType()||s())}:null).on("mousemove",o.interaction_enabled?function(){var t,e,i,n;r.dragging||r.hasArcType(t)||(t=r.filterTargetsToShow(r.data.targets),e=a.mouse(this),i=r.findClosestFromTargets(t,e),!r.mouseover||i&&i.id===r.mouseover.id||(o.data_onmouseout.call(r.api,r.mouseover),r.mouseover=void 0),i?(n=(r.isScatterType(i)||!o.tooltip_grouped?[i]:r.filterByX(t,i.x)).map(function(t){return r.addName(t)}),r.showTooltip(n,this),o.point_focus_expand_enabled&&(r.unexpandCircles(),n.forEach(function(t){r.expandCircles(t.index,t.id,!1)})),r.expandBars(i.index,i.id,!0),r.showXGridFocus(n),(r.isBarType(i.id)||r.dist(i,e)<o.point_sensitivity)&&(r.svg.select("."+Y.eventRect).style("cursor","pointer"),r.mouseover||(o.data_onmouseover.call(r.api,i),r.mouseover=i))):s())}:null).on("click",o.interaction_enabled?function(){var t,e,i;r.hasArcType(t)||(t=r.filterTargetsToShow(r.data.targets),e=a.mouse(this),(i=r.findClosestFromTargets(t,e))&&(r.isBarType(i.id)||r.dist(i,e)<o.point_sensitivity)&&(r.isScatterType(i)||!o.data_selection_grouped?[i]:r.filterByX(t,i.x)).forEach(function(t){r.main.selectAll("."+Y.shapes+r.getTargetSelectorSuffix(t.id)).selectAll("."+Y.shape+"-"+t.index).each(function(){(o.data_selection_grouped||r.isWithinShape(this,t))&&(r.toggleShape(this,t,t.index),o.data_onclick.call(r.api,t,this))})}))}:null).call(o.interaction_enabled&&o.data_selection_draggable&&r.drag?a.drag().on("drag",function(){r.drag(a.mouse(this))}).on("start",function(){r.dragstart(a.mouse(this))}).on("end",function(){r.dragend()}):function(){})},l.prototype.getMousePosition=function(t){return[this.x(t.x),this.getYScale(t.id)(t.value)]},l.prototype.dispatchEvent=function(t,e){var i="."+Y.eventRect,n=this.main.select(i).node(),r=n.getBoundingClientRect(),a=r.left+(e?e[0]:0),o=r.top+(e?e[1]:0),s=document.createEvent("MouseEvents");s.initMouseEvent(t,!0,!0,window,0,a,o,a,o,!1,!1,!1,!1,0,null),n.dispatchEvent(s)},l.prototype.initLegend=function(){var t=this;if(t.legendItemTextBox={},t.legendHasRendered=!1,t.legend=t.svg.append("g").attr("transform",t.getTranslate("legend")),!t.config.legend_show)return t.legend.style("visibility","hidden"),void(t.hiddenLegendIds=t.mapToIds(t.data.targets));t.updateLegendWithDefaults()},l.prototype.updateLegendWithDefaults=function(){this.updateLegend(this.mapToIds(this.data.targets),{withTransform:!1,withTransitionForTransform:!1,withTransition:!1})},l.prototype.updateSizeForLegend=function(t,e){var i=this,n=i.config,r={top:i.isLegendTop?i.getCurrentPaddingTop()+n.legend_inset_y+5.5:i.currentHeight-t-i.getCurrentPaddingBottom()-n.legend_inset_y,left:i.isLegendLeft?i.getCurrentPaddingLeft()+n.legend_inset_x+.5:i.currentWidth-e-i.getCurrentPaddingRight()-n.legend_inset_x+.5};i.margin3={top:i.isLegendRight?0:i.isLegendInset?r.top:i.currentHeight-t,right:NaN,bottom:0,left:i.isLegendRight?i.currentWidth-e:i.isLegendInset?r.left:0}},l.prototype.transformLegend=function(t){(t?this.legend.transition():this.legend).attr("transform",this.getTranslate("legend"))},l.prototype.updateLegendStep=function(t){this.legendStep=t},l.prototype.updateLegendItemWidth=function(t){this.legendItemWidth=t},l.prototype.updateLegendItemHeight=function(t){this.legendItemHeight=t},l.prototype.getLegendWidth=function(){var t=this;return t.config.legend_show?t.isLegendRight||t.isLegendInset?t.legendItemWidth*(t.legendStep+1):t.currentWidth:0},l.prototype.getLegendHeight=function(){var t=this,e=0;return t.config.legend_show&&(e=t.isLegendRight?t.currentHeight:Math.max(20,t.legendItemHeight)*(t.legendStep+1)),e},l.prototype.opacityForLegend=function(t){return t.classed(Y.legendItemHidden)?null:1},l.prototype.opacityForUnfocusedLegend=function(t){return t.classed(Y.legendItemHidden)?null:.3},l.prototype.toggleFocusLegend=function(e,t){var i=this;e=i.mapToTargetIds(e),i.legend.selectAll("."+Y.legendItem).filter(function(t){return 0<=e.indexOf(t)}).classed(Y.legendItemFocused,t).transition().duration(100).style("opacity",function(){return(t?i.opacityForLegend:i.opacityForUnfocusedLegend).call(i,i.d3.select(this))})},l.prototype.revertLegend=function(){var t=this,e=t.d3;t.legend.selectAll("."+Y.legendItem).classed(Y.legendItemFocused,!1).transition().duration(100).style("opacity",function(){return t.opacityForLegend(e.select(this))})},l.prototype.showLegend=function(t){var e=this,i=e.config;i.legend_show||(i.legend_show=!0,e.legend.style("visibility","visible"),e.legendHasRendered||e.updateLegendWithDefaults()),e.removeHiddenLegendIds(t),e.legend.selectAll(e.selectorLegends(t)).style("visibility","visible").transition().style("opacity",function(){return e.opacityForLegend(e.d3.select(this))})},l.prototype.hideLegend=function(t){var e=this,i=e.config;i.legend_show&&u(t)&&(i.legend_show=!1,e.legend.style("visibility","hidden")),e.addHiddenLegendIds(t),e.legend.selectAll(e.selectorLegends(t)).style("opacity",0).style("visibility","hidden")},l.prototype.clearLegendItemTextBoxCache=function(){this.legendItemTextBox={}},l.prototype.updateLegend=function(f,t,e){var i,n,r,a,o,s,c,d,l,u,h,g,p,_,x,y,m=this,S=m.config,w=4,v=10,b=0,A=0,T=10,P=S.legend_item_tile_width+5,C=0,L={},V={},G={},E=[0],I={},O=0;function R(t,e,i){var n,r,a,o,s=0===i,c=i===f.length-1,d=(a=t,o=e,m.legendItemTextBox[o]||(m.legendItemTextBox[o]=m.getTextRect(a.textContent,Y.legendItem,a)),m.legendItemTextBox[o]),l=d.width+P+(!c||m.isLegendRight||m.isLegendInset?v:0)+S.legend_padding,u=d.height+w,h=m.isLegendRight||m.isLegendInset?u:l,g=m.isLegendRight||m.isLegendInset?m.getLegendHeight():m.getLegendWidth();function p(t,e){e||(n=(g-C-h)/2)<T&&(n=(g-h)/2,C=0,O++),I[t]=O,E[O]=m.isLegendInset?10:n,L[t]=C,C+=h}s&&(A=b=O=C=0),!S.legend_show||m.isLegendToShow(e)?(V[e]=l,G[e]=u,(!b||b<=l)&&(b=l),(!A||A<=u)&&(A=u),r=m.isLegendRight||m.isLegendInset?A:b,S.legend_equally?(Object.keys(V).forEach(function(t){V[t]=b}),Object.keys(G).forEach(function(t){G[t]=A}),(n=(g-r*f.length)/2)<T?(O=C=0,f.forEach(function(t){p(t)})):p(e,!0)):p(e)):V[e]=G[e]=I[e]=L[e]=0}f=f.filter(function(t){return!k(S.data_names[t])||null!==S.data_names[t]}),h=N(t=t||{},"withTransition",!0),g=N(t,"withTransitionForTransform",!0),m.isLegendInset&&(O=S.legend_inset_step?S.legend_inset_step:f.length,m.updateLegendStep(O)),a=m.isLegendRight?(i=function(t){return b*I[t]},function(t){return E[I[t]]+L[t]}):m.isLegendInset?(i=function(t){return b*I[t]+10},function(t){return E[I[t]]+L[t]}):(i=function(t){return E[I[t]]+L[t]},function(t){return A*I[t]}),n=function(t,e){return i(t,e)+4+S.legend_item_tile_width},o=function(t,e){return a(t,e)+9},r=function(t,e){return i(t,e)},s=function(t,e){return a(t,e)-5},c=function(t,e){return i(t,e)-2},d=function(t,e){return i(t,e)-2+S.legend_item_tile_width},l=function(t,e){return a(t,e)+4},(u=m.legend.selectAll("."+Y.legendItem).data(f).enter().append("g").attr("class",function(t){return m.generateClass(Y.legendItem,t)}).style("visibility",function(t){return m.isLegendToShow(t)?"visible":"hidden"}).style("cursor","pointer").on("click",function(t){S.legend_item_onclick?S.legend_item_onclick.call(m,t):m.d3.event.altKey?(m.api.hide(),m.api.show(t)):(m.api.toggle(t),m.isTargetToShow(t)?m.api.focus(t):m.api.revert())}).on("mouseover",function(t){S.legend_item_onmouseover?S.legend_item_onmouseover.call(m,t):(m.d3.select(this).classed(Y.legendItemFocused,!0),!m.transiting&&m.isTargetToShow(t)&&m.api.focus(t))}).on("mouseout",function(t){S.legend_item_onmouseout?S.legend_item_onmouseout.call(m,t):(m.d3.select(this).classed(Y.legendItemFocused,!1),m.api.revert())})).append("text").text(function(t){return k(S.data_names[t])?S.data_names[t]:t}).each(function(t,e){R(this,t,e)}).style("pointer-events","none").attr("x",m.isLegendRight||m.isLegendInset?n:-200).attr("y",m.isLegendRight||m.isLegendInset?-200:o),u.append("rect").attr("class",Y.legendItemEvent).style("fill-opacity",0).attr("x",m.isLegendRight||m.isLegendInset?r:-200).attr("y",m.isLegendRight||m.isLegendInset?-200:s),u.append("line").attr("class",Y.legendItemTile).style("stroke",m.color).style("pointer-events","none").attr("x1",m.isLegendRight||m.isLegendInset?c:-200).attr("y1",m.isLegendRight||m.isLegendInset?-200:l).attr("x2",m.isLegendRight||m.isLegendInset?d:-200).attr("y2",m.isLegendRight||m.isLegendInset?-200:l).attr("stroke-width",S.legend_item_tile_height),y=m.legend.select("."+Y.legendBackground+" rect"),m.isLegendInset&&0<b&&0===y.size()&&(y=m.legend.insert("g","."+Y.legendItem).attr("class",Y.legendBackground).append("rect")),p=m.legend.selectAll("text").data(f).text(function(t){return k(S.data_names[t])?S.data_names[t]:t}).each(function(t,e){R(this,t,e)}),(h?p.transition():p).attr("x",n).attr("y",o),_=m.legend.selectAll("rect."+Y.legendItemEvent).data(f),(h?_.transition():_).attr("width",function(t){return V[t]}).attr("height",function(t){return G[t]}).attr("x",r).attr("y",s),x=m.legend.selectAll("line."+Y.legendItemTile).data(f),(h?x.transition():x).style("stroke",m.levelColor?function(t){return m.levelColor(m.cache[t].values[0].value)}:m.color).attr("x1",c).attr("y1",l).attr("x2",d).attr("y2",l),y&&(h?y.transition():y).attr("height",m.getLegendHeight()-12).attr("width",b*(O+1)+10),m.legend.selectAll("."+Y.legendItem).classed(Y.legendItemHidden,function(t){return!m.isTargetToShow(t)}),m.updateLegendItemWidth(b),m.updateLegendItemHeight(A),m.updateLegendStep(O),m.updateSizes(),m.updateScales(),m.updateSvgSize(),m.transformAll(g,e),m.legendHasRendered=!0},l.prototype.initRegion=function(){this.region=this.main.append("g").attr("clip-path",this.clipPath).attr("class",Y.regions)},l.prototype.updateRegion=function(t){var e=this,i=e.config;e.region.style("visibility",e.hasArcType()?"hidden":"visible");var n=e.main.select("."+Y.regions).selectAll("."+Y.region).data(i.regions),r=n.enter().append("rect").attr("x",e.regionX.bind(e)).attr("y",e.regionY.bind(e)).attr("width",e.regionWidth.bind(e)).attr("height",e.regionHeight.bind(e)).style("fill-opacity",0);e.mainRegion=r.merge(n).attr("class",e.classRegion.bind(e)),n.exit().transition().duration(t).style("opacity",0).remove()},l.prototype.redrawRegion=function(t,e){var i=this,n=i.mainRegion;return[(t?n.transition(e):n).attr("x",i.regionX.bind(i)).attr("y",i.regionY.bind(i)).attr("width",i.regionWidth.bind(i)).attr("height",i.regionHeight.bind(i)).style("fill-opacity",function(t){return P(t.opacity)?t.opacity:.1})]},l.prototype.regionX=function(t){var e=this,i=e.config,n="y"===t.axis?e.y:e.y2;return"y"===t.axis||"y2"===t.axis?i.axis_rotated&&"start"in t?n(t.start):0:i.axis_rotated?0:"start"in t?e.x(e.isTimeSeries()?e.parseDate(t.start):t.start):0},l.prototype.regionY=function(t){var e=this,i=e.config,n="y"===t.axis?e.y:e.y2;return"y"===t.axis||"y2"===t.axis?i.axis_rotated?0:"end"in t?n(t.end):0:i.axis_rotated&&"start"in t?e.x(e.isTimeSeries()?e.parseDate(t.start):t.start):0},l.prototype.regionWidth=function(t){var e,i=this,n=i.config,r=i.regionX(t),a="y"===t.axis?i.y:i.y2;return(e="y"===t.axis||"y2"===t.axis?n.axis_rotated&&"end"in t?a(t.end):i.width:n.axis_rotated?i.width:"end"in t?i.x(i.isTimeSeries()?i.parseDate(t.end):t.end):i.width)<r?0:e-r},l.prototype.regionHeight=function(t){var e,i=this,n=i.config,r=this.regionY(t),a="y"===t.axis?i.y:i.y2;return(e="y"===t.axis||"y2"===t.axis?n.axis_rotated?i.height:"start"in t?a(t.start):i.height:n.axis_rotated&&"end"in t?i.x(i.isTimeSeries()?i.parseDate(t.end):t.end):i.height)<r?0:e-r},l.prototype.isRegionOnX=function(t){return!t.axis||"x"===t.axis},l.prototype.getScale=function(t,e,i){return(i?this.d3.scaleTime():this.d3.scaleLinear()).range([t,e])},l.prototype.getX=function(t,e,i,n){var r,a=this.getScale(t,e,this.isTimeSeries()),o=i?a.domain(i):a;for(r in a=this.isCategorized()?(n=n||function(){return 0},function(t,e){var i=o(t)+n(t);return e?i:Math.ceil(i)}):function(t,e){var i=o(t);return e?i:Math.ceil(i)},o)a[r]=o[r];return a.orgDomain=function(){return o.domain()},this.isCategorized()&&(a.domain=function(t){return arguments.length?(o.domain(t),a):[(t=this.orgDomain())[0],t[1]+1]}),a},l.prototype.getY=function(t,e,i){var n=this.getScale(t,e,this.isTimeSeriesY());return i&&n.domain(i),n},l.prototype.getYScale=function(t){return"y2"===this.axis.getId(t)?this.y2:this.y},l.prototype.getSubYScale=function(t){return"y2"===this.axis.getId(t)?this.subY2:this.subY},l.prototype.updateScales=function(){var e=this,t=e.config,i=!e.x;e.xMin=t.axis_rotated?1:0,e.xMax=t.axis_rotated?e.height:e.width,e.yMin=t.axis_rotated?0:e.height,e.yMax=t.axis_rotated?e.width:1,e.subXMin=e.xMin,e.subXMax=e.xMax,e.subYMin=t.axis_rotated?0:e.height2,e.subYMax=t.axis_rotated?e.width2:1,e.x=e.getX(e.xMin,e.xMax,i?void 0:e.x.orgDomain(),function(){return e.xAxis.tickOffset()}),e.y=e.getY(e.yMin,e.yMax,i?t.axis_y_default:e.y.domain()),e.y2=e.getY(e.yMin,e.yMax,i?t.axis_y2_default:e.y2.domain()),e.subX=e.getX(e.xMin,e.xMax,e.orgXDomain,function(t){return t%1?0:e.subXAxis.tickOffset()}),e.subY=e.getY(e.subYMin,e.subYMax,i?t.axis_y_default:e.subY.domain()),e.subY2=e.getY(e.subYMin,e.subYMax,i?t.axis_y2_default:e.subY2.domain()),e.xAxisTickFormat=e.axis.getXAxisTickFormat(),e.xAxisTickValues=e.axis.getXAxisTickValues(),e.yAxisTickValues=e.axis.getYAxisTickValues(),e.y2AxisTickValues=e.axis.getY2AxisTickValues(),e.xAxis=e.axis.getXAxis(e.x,e.xOrient,e.xAxisTickFormat,e.xAxisTickValues,t.axis_x_tick_outer),e.subXAxis=e.axis.getXAxis(e.subX,e.subXOrient,e.xAxisTickFormat,e.xAxisTickValues,t.axis_x_tick_outer),e.yAxis=e.axis.getYAxis(e.y,e.yOrient,t.axis_y_tick_format,e.yAxisTickValues,t.axis_y_tick_outer),e.y2Axis=e.axis.getYAxis(e.y2,e.y2Orient,t.axis_y2_tick_format,e.y2AxisTickValues,t.axis_y2_tick_outer),i||e.brush&&e.brush.updateScale(e.subX),e.updateArc&&e.updateArc()},l.prototype.selectPoint=function(t,e,i){var n=this,r=n.config,a=(r.axis_rotated?n.circleY:n.circleX).bind(n),o=(r.axis_rotated?n.circleX:n.circleY).bind(n),s=n.pointSelectR.bind(n);r.data_onselected.call(n.api,e,t.node()),n.main.select("."+Y.selectedCircles+n.getTargetSelectorSuffix(e.id)).selectAll("."+Y.selectedCircle+"-"+i).data([e]).enter().append("circle").attr("class",function(){return n.generateClass(Y.selectedCircle,i)}).attr("cx",a).attr("cy",o).attr("stroke",function(){return n.color(e)}).attr("r",function(t){return 1.4*n.pointSelectR(t)}).transition().duration(100).attr("r",s)},l.prototype.unselectPoint=function(t,e,i){this.config.data_onunselected.call(this.api,e,t.node()),this.main.select("."+Y.selectedCircles+this.getTargetSelectorSuffix(e.id)).selectAll("."+Y.selectedCircle+"-"+i).transition().duration(100).attr("r",0).remove()},l.prototype.togglePoint=function(t,e,i,n){t?this.selectPoint(e,i,n):this.unselectPoint(e,i,n)},l.prototype.selectPath=function(t,e){var i=this;i.config.data_onselected.call(i,e,t.node()),i.config.interaction_brighten&&t.transition().duration(100).style("fill",function(){return i.d3.rgb(i.color(e)).brighter(.75)})},l.prototype.unselectPath=function(t,e){var i=this;i.config.data_onunselected.call(i,e,t.node()),i.config.interaction_brighten&&t.transition().duration(100).style("fill",function(){return i.color(e)})},l.prototype.togglePath=function(t,e,i,n){t?this.selectPath(e,i,n):this.unselectPath(e,i,n)},l.prototype.getToggle=function(t,e){var i;return"circle"===t.nodeName?i=this.isStepType(e)?function(){}:this.togglePoint:"path"===t.nodeName&&(i=this.togglePath),i},l.prototype.toggleShape=function(t,e,i){var n=this,r=n.d3,a=n.config,o=r.select(t),s=o.classed(Y.SELECTED),c=n.getToggle(t,e).bind(n);a.data_selection_enabled&&a.data_selection_isselectable(e)&&(a.data_selection_multiple||n.main.selectAll("."+Y.shapes+(a.data_selection_grouped?n.getTargetSelectorSuffix(e.id):"")).selectAll("."+Y.shape).each(function(t,e){var i=r.select(this);i.classed(Y.SELECTED)&&c(!1,i.classed(Y.SELECTED,!1),t,e)}),o.classed(Y.SELECTED,!s),c(!s,o,e,i))},l.prototype.initBar=function(){this.main.select("."+Y.chart).append("g").attr("class",Y.chartBars)},l.prototype.updateTargetsForBar=function(t){var e=this,i=e.config,n=e.classChartBar.bind(e),r=e.classBars.bind(e),a=e.classFocus.bind(e);e.main.select("."+Y.chartBars).selectAll("."+Y.chartBar).data(t).attr("class",function(t){return n(t)+a(t)}).enter().append("g").attr("class",n).style("pointer-events","none").append("g").attr("class",r).style("cursor",function(t){return i.data_selection_isselectable(t)?"pointer":null})},l.prototype.updateBar=function(t){var e=this,i=e.barData.bind(e),n=e.classBar.bind(e),r=e.initialOpacity.bind(e),a=function(t){return e.color(t.id)},o=e.main.selectAll("."+Y.bars).selectAll("."+Y.bar).data(i),s=o.enter().append("path").attr("class",n).style("stroke",a).style("fill",a);e.mainBar=s.merge(o).style("opacity",r),o.exit().transition().duration(t).style("opacity",0)},l.prototype.redrawBar=function(t,e,i){return[(e?this.mainBar.transition(i):this.mainBar).attr("d",t).style("stroke",this.color).style("fill",this.color).style("opacity",1)]},l.prototype.getBarW=function(t,e){var i=this.config,n="number"==typeof i.bar_width?i.bar_width:e?t.tickInterval()*i.bar_width_ratio/e:0;return i.bar_width_max&&n>i.bar_width_max?i.bar_width_max:n},l.prototype.getBars=function(t,e){return(e?this.main.selectAll("."+Y.bars+this.getTargetSelectorSuffix(e)):this.main).selectAll("."+Y.bar+(P(t)?"-"+t:""))},l.prototype.expandBars=function(t,e,i){i&&this.unexpandBars(),this.getBars(t,e).classed(Y.EXPANDED,!0)},l.prototype.unexpandBars=function(t){this.getBars(t).classed(Y.EXPANDED,!1)},l.prototype.generateDrawBar=function(t,e){var a=this.config,o=this.generateGetBarPoints(t,e);return function(t,e){var i=o(t,e),n=a.axis_rotated?1:0,r=a.axis_rotated?0:1;return"M "+i[0][n]+","+i[0][r]+" L"+i[1][n]+","+i[1][r]+" L"+i[2][n]+","+i[2][r]+" L"+i[3][n]+","+i[3][r]+" z"}},l.prototype.generateGetBarPoints=function(t,e){var o=this,i=e?o.subXAxis:o.xAxis,n=t.__max__+1,s=o.getBarW(i,n),c=o.getShapeX(s,n,t,!!e),d=o.getShapeY(!!e),l=o.getShapeOffset(o.isBarType,t,!!e),u=s*(o.config.bar_space/2),h=e?o.getSubYScale:o.getYScale;return function(t,e){var i=h.call(o,t.id)(0),n=l(t,e)||i,r=c(t),a=d(t);return o.config.axis_rotated&&(0<t.value&&a<i||t.value<0&&i<a)&&(a=i),[[r+u,n],[r+u,a-(i-n)],[r+s-u,a-(i-n)],[r+s-u,n]]}},l.prototype.isWithinBar=function(t,e){var i=e.getBoundingClientRect(),n=e.pathSegList.getItem(0),r=e.pathSegList.getItem(1),a=Math.min(n.x,r.x),o=Math.min(n.y,r.y),s=a+i.width+2,c=o+i.height+2,d=o-2;return a-2<t[0]&&t[0]<s&&d<t[1]&&t[1]<c},l.prototype.getShapeIndices=function(t){var e,i,n=this.config,r={},a=0;return this.filterTargetsToShow(this.data.targets.filter(t,this)).forEach(function(t){for(e=0;e<n.data_groups.length;e++)if(!(n.data_groups[e].indexOf(t.id)<0))for(i=0;i<n.data_groups[e].length;i++)if(n.data_groups[e][i]in r){r[t.id]=r[n.data_groups[e][i]];break}v(r[t.id])&&(r[t.id]=a++)}),r.__max__=a-1,r},l.prototype.getShapeX=function(i,n,r,t){var a=t?this.subX:this.x;return function(t){var e=t.id in r?r[t.id]:0;return t.x||0===t.x?a(t.x)-i*(n/2-e):0}},l.prototype.getShapeY=function(e){var i=this;return function(t){return(e?i.getSubYScale(t.id):i.getYScale(t.id))(t.value)}},l.prototype.getShapeOffset=function(t,s,e){var c=this,d=c.orderTargets(c.filterTargetsToShow(c.data.targets.filter(t,c))),l=d.map(function(t){return t.id});return function(i,n){var r=e?c.getSubYScale(i.id):c.getYScale(i.id),a=r(0),o=a;return d.forEach(function(t){var e=c.isStepType(i)?c.convertValuesToStep(t.values):t.values;t.id!==i.id&&s[t.id]===s[i.id]&&l.indexOf(t.id)<l.indexOf(i.id)&&(void 0!==e[n]&&+e[n].x==+i.x||(n=-1,e.forEach(function(t,e){t.x===i.x&&(n=e)})),n in e&&0<=e[n].value*i.value&&(o+=r(e[n].value)-a))}),o}},l.prototype.isWithinShape=function(t,e){var i,n=this,r=n.d3.select(t);return n.isTargetToShow(e.id)?"circle"===t.nodeName?i=n.isStepType(e)?n.isWithinStep(t,n.getYScale(e.id)(e.value)):n.isWithinCircle(t,1.5*n.pointSelectR(e)):"path"===t.nodeName&&(i=!r.classed(Y.bar)||n.isWithinBar(n.d3.mouse(t),t)):i=!1,i},l.prototype.getInterpolate=function(t){var e=this,i=e.d3,n={linear:i.curveLinear,"linear-closed":i.curveLinearClosed,basis:i.curveBasis,"basis-open":i.curveBasisOpen,"basis-closed":i.curveBasisClosed,bundle:i.curveBundle,cardinal:i.curveCardinal,"cardinal-open":i.curveCardinalOpen,"cardinal-closed":i.curveCardinalClosed,monotone:i.curveMonotoneX,step:i.curveStep,"step-before":i.curveStepBefore,"step-after":i.curveStepAfter};return e.isSplineType(t)?n[e.config.spline_interpolation_type]||n.cardinal:e.isStepType(t)?n[e.config.line_step_type]:n.linear},l.prototype.initLine=function(){this.main.select("."+Y.chart).append("g").attr("class",Y.chartLines)},l.prototype.updateTargetsForLine=function(t){var e,i=this,n=i.config,r=i.classChartLine.bind(i),a=i.classLines.bind(i),o=i.classAreas.bind(i),s=i.classCircles.bind(i),c=i.classFocus.bind(i);(e=i.main.select("."+Y.chartLines).selectAll("."+Y.chartLine).data(t).attr("class",function(t){return r(t)+c(t)}).enter().append("g").attr("class",r).style("opacity",0).style("pointer-events","none")).append("g").attr("class",a),e.append("g").attr("class",o),e.append("g").attr("class",function(t){return i.generateClass(Y.selectedCircles,t.id)}),e.append("g").attr("class",s).style("cursor",function(t){return n.data_selection_isselectable(t)?"pointer":null}),t.forEach(function(e){i.main.selectAll("."+Y.selectedCircles+i.getTargetSelectorSuffix(e.id)).selectAll("."+Y.selectedCircle).each(function(t){t.value=e.values[t.index].value})})},l.prototype.updateLine=function(t){var e=this,i=e.main.selectAll("."+Y.lines).selectAll("."+Y.line).data(e.lineData.bind(e)),n=i.enter().append("path").attr("class",e.classLine.bind(e)).style("stroke",e.color);e.mainLine=n.merge(i).style("opacity",e.initialOpacity.bind(e)).style("shape-rendering",function(t){return e.isStepType(t)?"crispEdges":""}).attr("transform",null),i.exit().transition().duration(t).style("opacity",0)},l.prototype.redrawLine=function(t,e,i){return[(e?this.mainLine.transition(i):this.mainLine).attr("d",t).style("stroke",this.color).style("opacity",1)]},l.prototype.generateDrawLine=function(t,o){var s=this,c=s.config,d=s.d3.line(),i=s.generateGetLinePoints(t,o),l=o?s.getSubYScale:s.getYScale,e=function(t){return(o?s.subxx:s.xx).call(s,t)},n=function(t,e){return 0<c.data_groups.length?i(t,e)[0][1]:l.call(s,t.id)(t.value)};return d=c.axis_rotated?d.x(n).y(e):d.x(e).y(n),c.line_connectNull||(d=d.defined(function(t){return null!=t.value})),function(t){var e=c.line_connectNull?s.filterRemoveNull(t.values):t.values,i=o?s.subX:s.x,n=l.call(s,t.id),r=0,a=0;return(s.isLineType(t)?c.data_regions[t.id]?s.lineWithRegions(e,i,n,c.data_regions[t.id]):(s.isStepType(t)&&(e=s.convertValuesToStep(e)),d.curve(s.getInterpolate(t))(e)):(e[0]&&(r=i(e[0].x),a=n(e[0].value)),c.axis_rotated?"M "+a+" "+r:"M "+r+" "+a))||"M 0 0"}},l.prototype.generateGetLinePoints=function(t,e){var o=this,s=o.config,i=t.__max__+1,c=o.getShapeX(0,i,t,!!e),d=o.getShapeY(!!e),l=o.getShapeOffset(o.isLineType,t,!!e),u=e?o.getSubYScale:o.getYScale;return function(t,e){var i=u.call(o,t.id)(0),n=l(t,e)||i,r=c(t),a=d(t);return s.axis_rotated&&(0<t.value&&a<i||t.value<0&&i<a)&&(a=i),[[r,a-(i-n)],[r,a-(i-n)],[r,a-(i-n)],[r,a-(i-n)]]}},l.prototype.lineWithRegions=function(t,c,d,e){var i,n,r,a,l,o,s,u,h,g,p,f=this,_=f.config,x="M",y=f.isCategorized()?.5:0,m=[];function S(t,e){var i;for(i=0;i<e.length;i++)if(e[i].start<t&&t<=e[i].end)return!0;return!1}if(k(e))for(i=0;i<e.length;i++)m[i]={},v(e[i].start)?m[i].start=t[0].x:m[i].start=f.isTimeSeries()?f.parseDate(e[i].start):e[i].start,v(e[i].end)?m[i].end=t[t.length-1].x:m[i].end=f.isTimeSeries()?f.parseDate(e[i].end):e[i].end;function w(t){return"M"+t[0][0]+" "+t[0][1]+" "+t[1][0]+" "+t[1][1]}for(g=_.axis_rotated?function(t){return d(t.value)}:function(t){return c(t.x)},p=_.axis_rotated?function(t){return c(t.x)}:function(t){return d(t.value)},r=f.isTimeSeries()?function(t,e,i,n){var r=t.x.getTime(),a=e.x-t.x,o=new Date(r+a*i),s=new Date(r+a*(i+n));return w(_.axis_rotated?[[d(l(i)),c(o)],[d(l(i+n)),c(s)]]:[[c(o),d(l(i))],[c(s),d(l(i+n))]])}:function(t,e,i,n){return w(_.axis_rotated?[[d(l(i),!0),c(a(i))],[d(l(i+n),!0),c(a(i+n))]]:[[c(a(i),!0),d(l(i))],[c(a(i+n),!0),d(l(i+n))]])},i=0;i<t.length;i++){if(v(m)||!S(t[i].x,m))x+=" "+g(t[i])+" "+p(t[i]);else for(a=f.getScale(t[i-1].x+y,t[i].x+y,f.isTimeSeries()),l=f.getScale(t[i-1].value,t[i].value),o=c(t[i].x)-c(t[i-1].x),s=d(t[i].value)-d(t[i-1].value),h=2*(u=2/Math.sqrt(Math.pow(o,2)+Math.pow(s,2))),n=u;n<=1;n+=h)x+=r(t[i-1],t[i],n,u);t[i].x}return x},l.prototype.updateArea=function(t){var e=this,i=e.d3,n=e.main.selectAll("."+Y.areas).selectAll("."+Y.area).data(e.lineData.bind(e)),r=n.enter().append("path").attr("class",e.classArea.bind(e)).style("fill",e.color).style("opacity",function(){return e.orgAreaOpacity=+i.select(this).style("opacity"),0});e.mainArea=r.merge(n).style("opacity",e.orgAreaOpacity),n.exit().transition().duration(t).style("opacity",0)},l.prototype.redrawArea=function(t,e,i){return[(e?this.mainArea.transition(i):this.mainArea).attr("d",t).style("fill",this.color).style("opacity",this.orgAreaOpacity)]},l.prototype.generateDrawArea=function(t,e){var r=this,a=r.config,o=r.d3.area(),i=r.generateGetAreaPoints(t,e),n=e?r.getSubYScale:r.getYScale,s=function(t){return(e?r.subxx:r.xx).call(r,t)},c=function(t,e){return 0<a.data_groups.length?i(t,e)[0][1]:n.call(r,t.id)(r.getAreaBaseValue(t.id))},d=function(t,e){return 0<a.data_groups.length?i(t,e)[1][1]:n.call(r,t.id)(t.value)};return o=a.axis_rotated?o.x0(c).x1(d).y(s):o.x(s).y0(a.area_above?0:c).y1(d),a.line_connectNull||(o=o.defined(function(t){return null!==t.value})),function(t){var e=a.line_connectNull?r.filterRemoveNull(t.values):t.values,i=0,n=0;return(r.isAreaType(t)?(r.isStepType(t)&&(e=r.convertValuesToStep(e)),o.curve(r.getInterpolate(t))(e)):(e[0]&&(i=r.x(e[0].x),n=r.getYScale(t.id)(e[0].value)),a.axis_rotated?"M "+n+" "+i:"M "+i+" "+n))||"M 0 0"}},l.prototype.getAreaBaseValue=function(){return 0},l.prototype.generateGetAreaPoints=function(t,e){var o=this,s=o.config,i=t.__max__+1,c=o.getShapeX(0,i,t,!!e),d=o.getShapeY(!!e),l=o.getShapeOffset(o.isAreaType,t,!!e),u=e?o.getSubYScale:o.getYScale;return function(t,e){var i=u.call(o,t.id)(0),n=l(t,e)||i,r=c(t),a=d(t);return s.axis_rotated&&(0<t.value&&a<i||t.value<0&&i<a)&&(a=i),[[r,n],[r,a-(i-n)],[r,a-(i-n)],[r,n]]}},l.prototype.updateCircle=function(t,e){var i=this,n=i.main.selectAll("."+Y.circles).selectAll("."+Y.circle).data(i.lineOrScatterData.bind(i)),r=n.enter().append("circle").attr("class",i.classCircle.bind(i)).attr("cx",t).attr("cy",e).attr("r",i.pointR.bind(i)).style("fill",i.color);i.mainCircle=r.merge(n).style("opacity",i.initialOpacityForCircle.bind(i)),n.exit().style("opacity",0)},l.prototype.redrawCircle=function(t,e,i,n){var r=this,a=r.main.selectAll("."+Y.selectedCircle);return[(i?r.mainCircle.transition(n):r.mainCircle).style("opacity",this.opacityForCircle.bind(r)).style("fill",r.color).attr("cx",t).attr("cy",e),(i?a.transition(n):a).attr("cx",t).attr("cy",e)]},l.prototype.circleX=function(t){return t.x||0===t.x?this.x(t.x):null},l.prototype.updateCircleY=function(){var t,i,e=this;0<e.config.data_groups.length?(t=e.getShapeIndices(e.isLineType),i=e.generateGetLinePoints(t),e.circleY=function(t,e){return i(t,e)[0][1]}):e.circleY=function(t){return e.getYScale(t.id)(t.value)}},l.prototype.getCircles=function(t,e){return(e?this.main.selectAll("."+Y.circles+this.getTargetSelectorSuffix(e)):this.main).selectAll("."+Y.circle+(P(t)?"-"+t:""))},l.prototype.expandCircles=function(t,e,i){var n=this.pointExpandedR.bind(this);i&&this.unexpandCircles(),this.getCircles(t,e).classed(Y.EXPANDED,!0).attr("r",n)},l.prototype.unexpandCircles=function(t){var e=this,i=e.pointR.bind(e);e.getCircles(t).filter(function(){return e.d3.select(this).classed(Y.EXPANDED)}).classed(Y.EXPANDED,!1).attr("r",i)},l.prototype.pointR=function(t){var e=this.config;return this.isStepType(t)?0:h(e.point_r)?e.point_r(t):e.point_r},l.prototype.pointExpandedR=function(t){var e=this.config;return e.point_focus_expand_enabled?h(e.point_focus_expand_r)?e.point_focus_expand_r(t):e.point_focus_expand_r?e.point_focus_expand_r:1.75*this.pointR(t):this.pointR(t)},l.prototype.pointSelectR=function(t){var e=this.config;return h(e.point_select_r)?e.point_select_r(t):e.point_select_r?e.point_select_r:4*this.pointR(t)},l.prototype.isWithinCircle=function(t,e){var i=this.d3,n=i.mouse(t),r=i.select(t),a=+r.attr("cx"),o=+r.attr("cy");return Math.sqrt(Math.pow(a-n[0],2)+Math.pow(o-n[1],2))<e},l.prototype.isWithinStep=function(t,e){return Math.abs(e-this.d3.mouse(t)[1])<30},l.prototype.getCurrentWidth=function(){var t=this.config;return t.size_width?t.size_width:this.getParentWidth()},l.prototype.getCurrentHeight=function(){var t=this.config,e=t.size_height?t.size_height:this.getParentHeight();return 0<e?e:320/(this.hasType("gauge")&&!t.gauge_fullCircle?2:1)},l.prototype.getCurrentPaddingTop=function(){var t=this.config,e=P(t.padding_top)?t.padding_top:0;return this.title&&this.title.node()&&(e+=this.getTitlePadding()),e},l.prototype.getCurrentPaddingBottom=function(){var t=this.config;return P(t.padding_bottom)?t.padding_bottom:0},l.prototype.getCurrentPaddingLeft=function(t){var e=this.config;return P(e.padding_left)?e.padding_left:e.axis_rotated?!e.axis_x_show||e.axis_x_inner?1:Math.max(r(this.getAxisWidthByAxisId("x",t)),40):!e.axis_y_show||e.axis_y_inner?this.axis.getYAxisLabelPosition().isOuter?30:1:r(this.getAxisWidthByAxisId("y",t))},l.prototype.getCurrentPaddingRight=function(){var t=this,e=t.config,i=t.isLegendRight?t.getLegendWidth()+20:0;return P(e.padding_right)?e.padding_right+1:e.axis_rotated?10+i:!e.axis_y2_show||e.axis_y2_inner?2+i+(t.axis.getY2AxisLabelPosition().isOuter?20:0):r(t.getAxisWidthByAxisId("y2"))+i},l.prototype.getParentRectValue=function(e){for(var i,n=this.selectChart.node();n&&"BODY"!==n.tagName;){try{i=n.getBoundingClientRect()[e]}catch(t){"width"===e&&(i=n.offsetWidth)}if(i)break;n=n.parentNode}return i},l.prototype.getParentWidth=function(){return this.getParentRectValue("width")},l.prototype.getParentHeight=function(){var t=this.selectChart.style("height");return 0<t.indexOf("px")?+t.replace("px",""):0},l.prototype.getSvgLeft=function(t){var e=this,i=e.config,n=i.axis_rotated||!i.axis_rotated&&!i.axis_y_inner,r=i.axis_rotated?Y.axisX:Y.axisY,a=e.main.select("."+r).node(),o=a&&n?a.getBoundingClientRect():{right:0},s=e.selectChart.node().getBoundingClientRect(),c=e.hasArcType(),d=o.right-s.left-(c?0:e.getCurrentPaddingLeft(t));return 0<d?d:0},l.prototype.getAxisWidthByAxisId=function(t,e){var i=this.axis.getLabelPositionById(t);return this.axis.getMaxTickWidth(t,e)+(i.isInner?20:40)},l.prototype.getHorizontalAxisHeight=function(t){var e=this,i=e.config,n=30;return"x"!==t||i.axis_x_show?"x"===t&&i.axis_x_height?i.axis_x_height:"y"!==t||i.axis_y_show?"y2"!==t||i.axis_y2_show?("x"===t&&!i.axis_rotated&&i.axis_x_tick_rotate&&(n=30+e.axis.getMaxTickWidth(t)*Math.cos(Math.PI*(90-Math.abs(i.axis_x_tick_rotate))/180)),"y"===t&&i.axis_rotated&&i.axis_y_tick_rotate&&(n=30+e.axis.getMaxTickWidth(t)*Math.cos(Math.PI*(90-Math.abs(i.axis_y_tick_rotate))/180)),n+(e.axis.getLabelPositionById(t).isInner?0:10)+("y2"===t?-10:0)):e.rotated_padding_top:!i.legend_show||e.isLegendRight||e.isLegendInset?1:10:8},l.prototype.initBrush=function(t){var r=this,e=r.d3;return r.brush=(r.config.axis_rotated?e.brushY():e.brushX()).on("brush",function(){var t=e.event.sourceEvent;t&&"zoom"===t.type||r.redrawForBrush()}).on("end",function(){var t=e.event.sourceEvent;t&&"zoom"===t.type||r.brush.empty()&&t&&"end"!==t.type&&r.brush.clear()}),r.brush.updateExtent=function(){var t,e=this.scale.range();return t=r.config.axis_rotated?[[0,e[0]],[r.width2,e[1]]]:[[e[0],0],[e[1],r.height2]],this.extent(t),this},r.brush.updateScale=function(t){return this.scale=t,this},r.brush.update=function(t){this.updateScale(t||r.subX).updateExtent(),r.context.select("."+Y.brush).call(this)},r.brush.clear=function(){r.context.select("."+Y.brush).call(r.brush.move,null)},r.brush.selection=function(){return e.brushSelection(r.context.select("."+Y.brush).node())},r.brush.selectionAsValue=function(t,e){var i,n;return t?(r.context&&(i=[this.scale(t[0]),this.scale(t[1])],n=r.context.select("."+Y.brush),e&&(n=n.transition()),r.brush.move(n,i)),[]):(i=r.brush.selection()||[0,0],[this.scale.invert(i[0]),this.scale.invert(i[1])])},r.brush.empty=function(){var t=r.brush.selection();return!t||t[0]===t[1]},r.brush.updateScale(t)},l.prototype.initSubchart=function(){var t=this,e=t.config,i=t.context=t.svg.append("g").attr("transform",t.getTranslate("context")),n=e.subchart_show?"visible":"hidden";i.style("visibility",n),i.append("g").attr("clip-path",t.clipPathForSubchart).attr("class",Y.chart),i.select("."+Y.chart).append("g").attr("class",Y.chartBars),i.select("."+Y.chart).append("g").attr("class",Y.chartLines),i.append("g").attr("clip-path",t.clipPath).attr("class",Y.brush),t.axes.subx=i.append("g").attr("class",Y.axisX).attr("transform",t.getTranslate("subx")).attr("clip-path",e.axis_rotated?"":t.clipPathForXAxis)},l.prototype.initSubchartBrush=function(){this.initBrush(this.subX).updateExtent(),this.context.select("."+Y.brush).call(this.brush)},l.prototype.updateTargetsForSubchart=function(t){var e,i,n,r,a=this,o=a.context,s=a.config,c=a.classChartBar.bind(a),d=a.classBars.bind(a),l=a.classChartLine.bind(a),u=a.classLines.bind(a),h=a.classAreas.bind(a);s.subchart_show&&((n=(r=o.select("."+Y.chartBars).selectAll("."+Y.chartBar).data(t)).enter().append("g").style("opacity",0)).merge(r).attr("class",c),n.append("g").attr("class",d),(e=(i=o.select("."+Y.chartLines).selectAll("."+Y.chartLine).data(t)).enter().append("g").style("opacity",0)).merge(i).attr("class",l),e.append("g").attr("class",u),e.append("g").attr("class",h),o.selectAll("."+Y.brush+" rect").attr(s.axis_rotated?"width":"height",s.axis_rotated?a.width2:a.height2))},l.prototype.updateBarForSubchart=function(t){var e=this,i=e.context.selectAll("."+Y.bars).selectAll("."+Y.bar).data(e.barData.bind(e)),n=i.enter().append("path").attr("class",e.classBar.bind(e)).style("stroke","none").style("fill",e.color);i.exit().transition().duration(t).style("opacity",0).remove(),e.contextBar=n.merge(i).style("opacity",e.initialOpacity.bind(e))},l.prototype.redrawBarForSubchart=function(t,e,i){(e?this.contextBar.transition(Math.random().toString()).duration(i):this.contextBar).attr("d",t).style("opacity",1)},l.prototype.updateLineForSubchart=function(t){var e=this,i=e.context.selectAll("."+Y.lines).selectAll("."+Y.line).data(e.lineData.bind(e)),n=i.enter().append("path").attr("class",e.classLine.bind(e)).style("stroke",e.color);i.exit().transition().duration(t).style("opacity",0).remove(),e.contextLine=n.merge(i).style("opacity",e.initialOpacity.bind(e))},l.prototype.redrawLineForSubchart=function(t,e,i){(e?this.contextLine.transition(Math.random().toString()).duration(i):this.contextLine).attr("d",t).style("opacity",1)},l.prototype.updateAreaForSubchart=function(t){var e=this,i=e.d3,n=e.context.selectAll("."+Y.areas).selectAll("."+Y.area).data(e.lineData.bind(e)),r=n.enter().append("path").attr("class",e.classArea.bind(e)).style("fill",e.color).style("opacity",function(){return e.orgAreaOpacity=+i.select(this).style("opacity"),0});n.exit().transition().duration(t).style("opacity",0).remove(),e.contextArea=r.merge(n).style("opacity",0)},l.prototype.redrawAreaForSubchart=function(t,e,i){(e?this.contextArea.transition(Math.random().toString()).duration(i):this.contextArea).attr("d",t).style("fill",this.color).style("opacity",this.orgAreaOpacity)},l.prototype.redrawSubchart=function(t,e,i,n,r,a,o){var s,c,d,l=this,u=l.d3,h=l.config;l.context.style("visibility",h.subchart_show?"visible":"hidden"),h.subchart_show&&(u.event&&"zoom"===u.event.type&&l.brush.selectionAsValue(l.x.orgDomain()),t&&(l.brush.empty()||l.brush.selectionAsValue(l.x.orgDomain()),s=l.generateDrawArea(r,!0),c=l.generateDrawBar(a,!0),d=l.generateDrawLine(o,!0),l.updateBarForSubchart(i),l.updateLineForSubchart(i),l.updateAreaForSubchart(i),l.redrawBarForSubchart(c,i,i),l.redrawLineForSubchart(d,i,i),l.redrawAreaForSubchart(s,i,i)))},l.prototype.redrawForBrush=function(){var t,e=this,i=e.x,n=e.d3;e.redraw({withTransition:!1,withY:e.config.zoom_rescale,withSubchart:!1,withUpdateXDomain:!0,withEventRect:!1,withDimension:!1}),t=n.event.selection||e.brush.scale.range(),e.main.select("."+Y.eventRect).call(e.zoom.transform,n.zoomIdentity.scale(e.width/(t[1]-t[0])).translate(-t[0],0)),e.config.subchart_onbrush.call(e.api,i.orgDomain())},l.prototype.transformContext=function(t,e){var i;e&&e.axisSubX?i=e.axisSubX:(i=this.context.select("."+Y.axisX),t&&(i=i.transition())),this.context.attr("transform",this.getTranslate("context")),i.attr("transform",this.getTranslate("subx"))},l.prototype.getDefaultSelection=function(){var t=this,e=t.config,i=h(e.axis_x_selection)?e.axis_x_selection(t.getXDomain(t.data.targets)):e.axis_x_selection;return t.isTimeSeries()&&(i=[t.parseDate(i[0]),t.parseDate(i[1])]),i},l.prototype.initText=function(){this.main.select("."+Y.chart).append("g").attr("class",Y.chartTexts),this.mainText=this.d3.selectAll([])},l.prototype.updateTargetsForText=function(t){var e=this,i=e.classChartText.bind(e),n=e.classTexts.bind(e),r=e.classFocus.bind(e),a=e.main.select("."+Y.chartTexts).selectAll("."+Y.chartText).data(t),o=a.enter().append("g").attr("class",i).style("opacity",0).style("pointer-events","none");o.append("g").attr("class",n),o.merge(a).attr("class",function(t){return i(t)+r(t)})},l.prototype.updateText=function(t,e,i){var n=this,r=n.config,a=n.barOrLineData.bind(n),o=n.classText.bind(n),s=n.main.selectAll("."+Y.texts).selectAll("."+Y.text).data(a),c=s.enter().append("text").attr("class",o).attr("text-anchor",function(t){return r.axis_rotated?t.value<0?"end":"start":"middle"}).style("stroke","none").attr("x",t).attr("y",e).style("fill",function(t){return n.color(t)}).style("fill-opacity",0);n.mainText=c.merge(s).text(function(t,e,i){return n.dataLabelFormat(t.id)(t.value,t.id,e,i)}),s.exit().transition().duration(i).style("fill-opacity",0).remove()},l.prototype.redrawText=function(t,e,i,n,r){return[(n?this.mainText.transition(r):this.mainText).attr("x",t).attr("y",e).style("fill",this.color).style("fill-opacity",i?0:this.opacityForText.bind(this))]},l.prototype.getTextRect=function(t,e,i){var n,r=this.d3.select("body").append("div").classed("c3",!0),a=r.append("svg").style("visibility","hidden").style("position","fixed").style("top",0).style("left",0),o=this.d3.select(i).style("font");return a.selectAll(".dummy").data([t]).enter().append("text").classed(e||"",!0).style("font",o).text(t).each(function(){n=this.getBoundingClientRect()}),r.remove(),n},l.prototype.generateXYForText=function(t,e,i,n){var r=this,a=r.generateGetAreaPoints(t,!1),o=r.generateGetBarPoints(e,!1),s=r.generateGetLinePoints(i,!1),c=n?r.getXForText:r.getYForText;return function(t,e){var i=r.isAreaType(t)?a:r.isBarType(t)?o:s;return c.call(r,i(t,e),t,this)}},l.prototype.getXForText=function(t,e,i){var n,r,a=this,o=i.getBoundingClientRect();return n=a.config.axis_rotated?(r=a.isBarType(e)?4:6,t[2][1]+r*(e.value<0?-1:1)):a.hasType("bar")?(t[2][0]+t[0][0])/2:t[0][0],null===e.value&&(n>a.width?n=a.width-o.width:n<0&&(n=4)),n},l.prototype.getYForText=function(t,e,i){var n,r=this,a=i.getBoundingClientRect();return r.config.axis_rotated?n=(t[0][0]+t[2][0]+.6*a.height)/2:(n=t[2][1],e.value<0||0===e.value&&!r.hasPositiveValue?(n+=a.height,r.isBarType(e)&&r.isSafari()?n-=3:!r.isBarType(e)&&r.isChrome()&&(n+=3)):n+=r.isBarType(e)?-3:-6),null!==e.value||r.config.axis_rotated||(n<a.height?n=a.height:n>this.height&&(n=this.height-4)),n},l.prototype.initTitle=function(){this.title=this.svg.append("text").text(this.config.title_text).attr("class",this.CLASS.title)},l.prototype.redrawTitle=function(){var t=this;t.title.attr("x",t.xForTitle.bind(t)).attr("y",t.yForTitle.bind(t))},l.prototype.xForTitle=function(){var t=this,e=t.config,i=e.title_position||"left";return 0<=i.indexOf("right")?t.currentWidth-t.getTextRect(t.title.node().textContent,t.CLASS.title,t.title.node()).width-e.title_padding.right:0<=i.indexOf("center")?(t.currentWidth-t.getTextRect(t.title.node().textContent,t.CLASS.title,t.title.node()).width)/2:e.title_padding.left},l.prototype.yForTitle=function(){var t=this;return t.config.title_padding.top+t.getTextRect(t.title.node().textContent,t.CLASS.title,t.title.node()).height},l.prototype.getTitlePadding=function(){return this.yForTitle()+this.config.title_padding.bottom},l.prototype.initTooltip=function(){var t,e=this,i=e.config;if(e.tooltip=e.selectChart.style("position","relative").append("div").attr("class",Y.tooltipContainer).style("position","absolute").style("pointer-events","none").style("display","none"),i.tooltip_init_show){if(e.isTimeSeries()&&c(i.tooltip_init_x)){for(i.tooltip_init_x=e.parseDate(i.tooltip_init_x),t=0;t<e.data.targets[0].values.length&&e.data.targets[0].values[t].x-i.tooltip_init_x!=0;t++);i.tooltip_init_x=t}e.tooltip.html(i.tooltip_contents.call(e,e.data.targets.map(function(t){return e.addName(t.values[i.tooltip_init_x])}),e.axis.getXAxisTickFormat(),e.getYFormat(e.hasArcType()),e.color)),e.tooltip.style("top",i.tooltip_init_position.top).style("left",i.tooltip_init_position.left).style("display","block")}},l.prototype.getTooltipSortFunction=function(){var t=this,e=t.config;if(0!==e.data_groups.length&&void 0===e.tooltip_order){var i=t.orderTargets(t.data.targets).map(function(t){return t.id});return(t.isOrderAsc()||t.isOrderDesc())&&(i=i.reverse()),function(t,e){return i.indexOf(t.id)-i.indexOf(e.id)}}var n=e.tooltip_order;void 0===n&&(n=e.data_order);var r=function(t){return t?t.value:null};if(c(n)&&"asc"===n.toLowerCase())return function(t,e){return r(t)-r(e)};if(c(n)&&"desc"===n.toLowerCase())return function(t,e){return r(e)-r(t)};if(h(n)){var a=n;return void 0===e.tooltip_order&&(a=function(t,e){return n(t?{id:t.id,values:[t]}:null,e?{id:e.id,values:[e]}:null)}),a}return o(n)?function(t,e){return n.indexOf(t.id)-n.indexOf(e.id)}:void 0},l.prototype.getTooltipContent=function(t,e,i,n){var r,a,o,s,c,d,l=this,u=l.config,h=u.tooltip_format_title||e,g=u.tooltip_format_name||function(t){return t},p=u.tooltip_format_value||i,f=this.getTooltipSortFunction();for(f&&t.sort(f),a=0;a<t.length;a++)if(t[a]&&(t[a].value||0===t[a].value)&&(r||(o=_(h?h(t[a].x):t[a].x),r="<table class='"+l.CLASS.tooltip+"'>"+(o||0===o?"<tr><th colspan='2'>"+o+"</th></tr>":"")),void 0!==(s=_(p(t[a].value,t[a].ratio,t[a].id,t[a].index,t))))){if(null===t[a].name)continue;c=_(g(t[a].name,t[a].ratio,t[a].id,t[a].index)),d=l.levelColor?l.levelColor(t[a].value):n(t[a].id),r+="<tr class='"+l.CLASS.tooltipName+"-"+l.getTargetSelectorSuffix(t[a].id)+"'>",r+="<td class='name'><span style='background-color:"+d+"'></span>"+c+"</td>",r+="<td class='value'>"+s+"</td>",r+="</tr>"}return r+"</table>"},l.prototype.tooltipPosition=function(t,e,i,n){var r,a,o,s,c,d=this,l=d.config,u=d.d3,h=d.hasArcType(),g=u.mouse(n);return h?(a=(d.width-(d.isLegendRight?d.getLegendWidth():0))/2+g[0],s=(d.hasType("gauge")?d.height:d.height/2)+g[1]+20):(r=d.getSvgLeft(!0),s=l.axis_rotated?(o=(a=r+g[0]+100)+e,c=d.currentWidth-d.getCurrentPaddingRight(),d.x(t[0].x)+20):(o=(a=r+d.getCurrentPaddingLeft(!0)+d.x(t[0].x)+20)+e,c=r+d.currentWidth-d.getCurrentPaddingRight(),g[1]+15),c<o&&(a-=o-c+20),s+i>d.currentHeight&&(s-=i+30)),s<0&&(s=0),{top:s,left:a}},l.prototype.showTooltip=function(t,e){var i,n,r,a=this,o=a.config,s=a.hasArcType(),c=t.filter(function(t){return t&&P(t.value)}),d=o.tooltip_position||l.prototype.tooltipPosition;0!==c.length&&o.tooltip_show&&(a.tooltip.html(o.tooltip_contents.call(a,t,a.axis.getXAxisTickFormat(),a.getYFormat(s),a.color)).style("display","block"),i=a.tooltip.property("offsetWidth"),n=a.tooltip.property("offsetHeight"),r=d.call(this,c,i,n,e),a.tooltip.style("top",r.top+"px").style("left",r.left+"px"))},l.prototype.hideTooltip=function(){this.tooltip.style("display","none")},l.prototype.setTargetType=function(t,e){var i=this,n=i.config;i.mapToTargetIds(t).forEach(function(t){i.withoutFadeIn[t]=e===n.data_types[t],n.data_types[t]=e}),t||(n.data_type=e)},l.prototype.hasType=function(i,t){var n=this.config.data_types,r=!1;return(t=t||this.data.targets)&&t.length?t.forEach(function(t){var e=n[t.id];(e&&0<=e.indexOf(i)||!e&&"line"===i)&&(r=!0)}):Object.keys(n).length?Object.keys(n).forEach(function(t){n[t]===i&&(r=!0)}):r=this.config.data_type===i,r},l.prototype.hasArcType=function(t){return this.hasType("pie",t)||this.hasType("donut",t)||this.hasType("gauge",t)},l.prototype.isLineType=function(t){var e=this.config,i=c(t)?t:t.id;return!e.data_types[i]||0<=["line","spline","area","area-spline","step","area-step"].indexOf(e.data_types[i])},l.prototype.isStepType=function(t){var e=c(t)?t:t.id;return 0<=["step","area-step"].indexOf(this.config.data_types[e])},l.prototype.isSplineType=function(t){var e=c(t)?t:t.id;return 0<=["spline","area-spline"].indexOf(this.config.data_types[e])},l.prototype.isAreaType=function(t){var e=c(t)?t:t.id;return 0<=["area","area-spline","area-step"].indexOf(this.config.data_types[e])},l.prototype.isBarType=function(t){var e=c(t)?t:t.id;return"bar"===this.config.data_types[e]},l.prototype.isScatterType=function(t){var e=c(t)?t:t.id;return"scatter"===this.config.data_types[e]},l.prototype.isPieType=function(t){var e=c(t)?t:t.id;return"pie"===this.config.data_types[e]},l.prototype.isGaugeType=function(t){var e=c(t)?t:t.id;return"gauge"===this.config.data_types[e]},l.prototype.isDonutType=function(t){var e=c(t)?t:t.id;return"donut"===this.config.data_types[e]},l.prototype.isArcType=function(t){return this.isPieType(t)||this.isDonutType(t)||this.isGaugeType(t)},l.prototype.lineData=function(t){return this.isLineType(t)?[t]:[]},l.prototype.arcData=function(t){return this.isArcType(t.data)?[t]:[]},l.prototype.barData=function(t){return this.isBarType(t)?t.values:[]},l.prototype.lineOrScatterData=function(t){return this.isLineType(t)||this.isScatterType(t)?t.values:[]},l.prototype.barOrLineData=function(t){return this.isBarType(t)||this.isLineType(t)?t.values:[]},l.prototype.isSafari=function(){var t=window.navigator.userAgent;return 0<=t.indexOf("Safari")&&t.indexOf("Chrome")<0},l.prototype.isChrome=function(){return 0<=window.navigator.userAgent.indexOf("Chrome")},l.prototype.initZoom=function(){var e,i=this,n=i.d3,r=i.config;return i.zoom=n.zoom().on("start",function(){if("scroll"===r.zoom_type){var t=n.event.sourceEvent;t&&"brush"===t.type||(e=t,r.zoom_onzoomstart.call(i.api,t))}}).on("zoom",function(){if("scroll"===r.zoom_type){var t=n.event.sourceEvent;t&&"brush"===t.type||(i.redrawForZoom(),r.zoom_onzoom.call(i.api,i.x.orgDomain()))}}).on("end",function(){if("scroll"===r.zoom_type){var t=n.event.sourceEvent;t&&"brush"===t.type||t&&e.clientX===t.clientX&&e.clientY===t.clientY||r.zoom_onzoomend.call(i.api,i.x.orgDomain())}}),i.zoom.updateDomain=function(){return n.event&&n.event.transform&&i.x.domain(n.event.transform.rescaleX(i.subX).domain()),this},i.zoom.updateExtent=function(){return this.scaleExtent([1,1/0]).translateExtent([[0,0],[i.width,i.height]]).extent([[0,0],[i.width,i.height]]),this},i.zoom.update=function(){return this.updateExtent().updateDomain()},i.zoom.updateExtent()},l.prototype.zoomTransform=function(t){var e=[this.x(t[0]),this.x(t[1])];return this.d3.zoomIdentity.scale(this.width/(e[1]-e[0])).translate(-e[0],0)},l.prototype.initDragZoom=function(){var e=this,i=e.d3,n=e.config,t=e.context=e.svg,r=e.margin.left+20.5,a=e.margin.top+.5;if("drag"===n.zoom_type&&n.zoom_enabled){var o=function(t){return t&&t.map(function(t){return e.x.invert(t)})},s=e.dragZoomBrush=i.brushX().on("start",function(){e.api.unzoom(),e.svg.select("."+Y.dragZoom).classed("disabled",!1),n.zoom_onzoomstart.call(e.api,i.event.sourceEvent)}).on("brush",function(){n.zoom_onzoom.call(e.api,o(i.event.selection))}).on("end",function(){if(null!=i.event.selection){var t=o(i.event.selection);n.zoom_disableDefaultBehavior||e.api.zoom(t),e.svg.select("."+Y.dragZoom).classed("disabled",!0),n.zoom_onzoomend.call(e.api,t)}});t.append("g").classed(Y.dragZoom,!0).attr("clip-path",e.clipPath).attr("transform","translate("+r+","+a+")").call(s)}},l.prototype.getZoomDomain=function(){var t=this.config,e=this.d3;return[e.min([this.orgXDomain[0],t.zoom_x_min]),e.max([this.orgXDomain[1],t.zoom_x_max])]},l.prototype.redrawForZoom=function(){var t=this,e=t.d3,i=t.config,n=t.zoom,r=t.x;i.zoom_enabled&&0!==t.filterTargetsToShow(t.data.targets).length&&(n.update(),i.zoom_disableDefaultBehavior||(t.isCategorized()&&r.orgDomain()[0]===t.orgXDomain[0]&&r.domain([t.orgXDomain[0]-1e-10,r.orgDomain()[1]]),t.redraw({withTransition:!1,withY:i.zoom_rescale,withSubchart:!1,withEventRect:!1,withDimension:!1}),e.event.sourceEvent&&"mousemove"===e.event.sourceEvent.type&&(t.cancelClick=!0)))},t});c3.js000064400001304215151701472650005425 0ustar00/* @license C3.js v0.6.8 | (c) C3 Team and other contributors | http://c3js.org/ */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  (global.c3 = factory());
}(this, (function () { 'use strict';

  function _typeof(obj) {
    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
      _typeof = function (obj) {
        return typeof obj;
      };
    } else {
      _typeof = function (obj) {
        return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
      };
    }

    return _typeof(obj);
  }

  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }

  function _defineProperty(obj, key, value) {
    if (key in obj) {
      Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
      });
    } else {
      obj[key] = value;
    }

    return obj;
  }

  function ChartInternal(api) {
    var $$ = this;
    $$.d3 = window.d3 ? window.d3 : typeof require !== 'undefined' ? require("d3") : undefined;
    $$.api = api;
    $$.config = $$.getDefaultConfig();
    $$.data = {};
    $$.cache = {};
    $$.axes = {};
  }

  function Chart(config) {
    var $$ = this.internal = new ChartInternal(this);
    $$.loadConfig(config);
    $$.beforeInit(config);
    $$.init();
    $$.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);
  }

  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 = this.getBoundingClientRect(),
          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 scale1(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',
    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_'
  };

  var asHalfPixel = function asHalfPixel(n) {
    return Math.ceil(n) + 0.5;
  };
  var ceil10 = function ceil10(v) {
    return Math.ceil(v / 10) * 10;
  };
  var diffDomain = function diffDomain(d) {
    return d[1] - d[0];
  };
  var getOption = function getOption(options, key, defaultValue) {
    return isDefined(options[key]) ? options[key] : defaultValue;
  };
  var getPathBox = function getPathBox(path) {
    var box = path.getBoundingClientRect(),
        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 hasValue = function hasValue(dict, value) {
    var found = false;
    Object.keys(dict).forEach(function (key) {
      if (dict[key] === value) {
        found = true;
      }
    });
    return found;
  };
  var isArray = function isArray(o) {
    return Array.isArray(o);
  };
  var isDefined = function isDefined(v) {
    return typeof v !== 'undefined';
  };
  var isEmpty = function isEmpty(o) {
    return typeof o === 'undefined' || o === null || isString(o) && o.length === 0 || _typeof(o) === 'object' && Object.keys(o).length === 0;
  };
  var isFunction = function isFunction(o) {
    return typeof o === 'function';
  };
  var isString = function isString(o) {
    return typeof o === 'string';
  };
  var isUndefined = function isUndefined(v) {
    return typeof v === 'undefined';
  };
  var isValue = function isValue(v) {
    return v || v === 0;
  };
  var notEmpty = function notEmpty(o) {
    return !isEmpty(o);
  };
  var sanitise = function sanitise(str) {
    return typeof str === 'string' ? str.replace(/</g, '&lt;').replace(/>/g, '&gt;') : str;
  };

  var Axis = function Axis(owner) {
    _classCallCheck(this, Axis);

    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(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) {
    var $$ = this.owner,
        config = $$.config,
        axisParams = {
      withOuterTick: withOuterTick,
      withoutTransition: withoutTransition,
      tickTextRotate: withoutRotateTickText ? 0 : config.axis_y_tick_rotate
    },
        axis = new this.internal(this, axisParams).axis.scale(scale).orient(orient).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;
    var 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 format(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" : config.axis_x_height ? config.axis_x_height - 10 : "3em";
    }
  };

  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,
        config = $$.config,
        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(scale, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues, false, true, true);
      } else if (id === 'y2') {
        scale = $$.y2.copy().domain($$.getYDomain(targetsToShow, 'y2'));
        axis = this.getYAxis(scale, $$.y2Orient, config.axis_y2_tick_format, $$.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 = this.getBoundingClientRect();

          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.6.8",
    chart: {
      fn: Chart.prototype,
      internal: {
        fn: ChartInternal.prototype,
        axis: {
          fn: Axis.prototype,
          internal: {
            fn: AxisInternal.prototype
          }
        }
      }
    },
    generate: function generate(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() + '-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 = false;
    $$.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);
    } // 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 ($$.initSubchart) {
      $$.initSubchart();
    }

    if ($$.initTooltip) {
      $$.initTooltip();
    }

    if ($$.initLegend) {
      $$.initLegend();
    }

    if ($$.initTitle) {
      $$.initTitle();
    }

    if ($$.initZoom) {
      $$.initZoom();
    } // 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 ($$.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();
    } // 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 resize event


    $$.bindResize(); // export element of the chart

    $$.api.element = $$.selectChart.node();
  };

  ChartInternal.prototype.smoothLines = function (el, type) {
    var $$ = this;

    if (type === 'grid') {
      el.each(function () {
        var g = $$.d3.select(this),
            x1 = g.attr('x1'),
            x2 = g.attr('x2'),
            y1 = g.attr('y1'),
            y2 = g.attr('y2');
        g.attr({
          'x1': Math.ceil(x1),
          'x2': Math.ceil(x2),
          'y1': Math.ceil(y1),
          'y2': Math.ceil(y2)
        });
      });
    }
  };

  ChartInternal.prototype.updateSizes = function () {
    var $$ = this,
        config = $$.config;
    var legendHeight = $$.legend ? $$.getLegendHeight() : 0,
        legendWidth = $$.legend ? $$.getLegendWidth() : 0,
        legendHeightForBottom = $$.isLegendRight || $$.isLegendInset ? 0 : legendHeight,
        hasArc = $$.hasArcType(),
        xAxisHeight = config.axis_rotated || hasArc ? 0 : $$.getHorizontalAxisHeight('x'),
        subchartHeight = config.subchart_show && !hasArc ? config.subchart_size_height + xAxisHeight : 0;
    $$.currentWidth = $$.getCurrentWidth();
    $$.currentHeight = $$.getCurrentHeight(); // for main

    $$.margin = config.axis_rotated ? {
      top: $$.getHorizontalAxisHeight('y2') + $$.getCurrentPaddingTop(),
      right: hasArc ? 0 : $$.getCurrentPaddingRight(),
      bottom: $$.getHorizontalAxisHeight('y') + legendHeightForBottom + $$.getCurrentPaddingBottom(),
      left: subchartHeight + (hasArc ? 0 : $$.getCurrentPaddingLeft())
    } : {
      top: 4 + $$.getCurrentPaddingTop(),
      // for top tick text
      right: hasArc ? 0 : $$.getCurrentPaddingRight(),
      bottom: xAxisHeight + subchartHeight + legendHeightForBottom + $$.getCurrentPaddingBottom(),
      left: hasArc ? 0 : $$.getCurrentPaddingLeft()
    }; // for subchart

    $$.margin2 = config.axis_rotated ? {
      top: $$.margin.top,
      right: NaN,
      bottom: 20 + legendHeightForBottom,
      left: $$.rotated_padding_left
    } : {
      top: $$.currentHeight - subchartHeight - legendHeightForBottom,
      right: NaN,
      bottom: xAxisHeight + legendHeightForBottom,
      left: $$.margin.left
    }; // for legend

    $$.margin3 = {
      top: 0,
      right: NaN,
      bottom: 0,
      left: 0
    };

    if ($$.updateSizeForLegend) {
      $$.updateSizeForLegend(legendHeight, legendWidth);
    }

    $$.width = $$.currentWidth - $$.margin.left - $$.margin.right;
    $$.height = $$.currentHeight - $$.margin.top - $$.margin.bottom;

    if ($$.width < 0) {
      $$.width = 0;
    }

    if ($$.height < 0) {
      $$.height = 0;
    }

    $$.width2 = config.axis_rotated ? $$.margin.left - $$.rotated_padding_left - $$.rotated_padding_right : $$.width;
    $$.height2 = config.axis_rotated ? $$.height : $$.currentHeight - $$.margin2.top - $$.margin2.bottom;

    if ($$.width2 < 0) {
      $$.width2 = 0;
    }

    if ($$.height2 < 0) {
      $$.height2 = 0;
    } // for arc


    $$.arcWidth = $$.width - ($$.isLegendRight ? legendWidth + 10 : 0);
    $$.arcHeight = $$.height - ($$.isLegendRight ? 0 : 10);

    if ($$.hasType('gauge') && !config.gauge_fullCircle) {
      $$.arcHeight += $$.height - $$.getGaugeLabelHeight();
    }

    if ($$.updateRadius) {
      $$.updateRadius();
    }

    if ($$.isLegendRight && hasArc) {
      $$.margin3.left = $$.arcWidth / 2 + $$.radiusExpanded * 1.1;
    }
  };

  ChartInternal.prototype.updateTargets = function (targets) {
    var $$ = this;
    /*-- Main --*/
    //-- Text --//

    $$.updateTargetsForText(targets); //-- Bar --//

    $$.updateTargetsForBar(targets); //-- Line --//

    $$.updateTargetsForLine(targets); //-- Arc --//

    if ($$.hasArcType() && $$.updateTargetsForArc) {
      $$.updateTargetsForArc(targets);
    }
    /*-- Sub --*/


    if ($$.updateTargetsForSubchart) {
      $$.updateTargetsForSubchart(targets);
    } // Fade-in each chart


    $$.showTargets();
  };

  ChartInternal.prototype.showTargets = function () {
    var $$ = this;
    $$.svg.selectAll('.' + CLASS.target).filter(function (d) {
      return $$.isTargetToShow(d.id);
    }).transition().duration($$.config.transition_duration).style("opacity", 1);
  };

  ChartInternal.prototype.redraw = function (options, transitions) {
    var $$ = this,
        main = $$.main,
        d3 = $$.d3,
        config = $$.config;
    var areaIndices = $$.getShapeIndices($$.isAreaType),
        barIndices = $$.getShapeIndices($$.isBarType),
        lineIndices = $$.getShapeIndices($$.isLineType);
    var withY, withSubchart, withTransition, withTransitionForExit, withTransitionForAxis, withTransform, withUpdateXDomain, withUpdateOrgXDomain, withTrimXDomain, withLegend, withEventRect, withDimension, withUpdateXAxis;
    var hideAxis = $$.hasArcType();
    var drawArea, drawBar, drawLine, xForText, yForText;
    var duration, durationForExit, durationForAxis;
    var transitionsToWait, waitForDraw, flow, transition;
    var targetsToShow = $$.filterTargetsToShow($$.data.targets),
        tickValues,
        i,
        intervalForCulling,
        xDomainForZoom;
    var xv = $$.xv.bind($$),
        cx,
        cy;
    options = options || {};
    withY = getOption(options, "withY", true);
    withSubchart = getOption(options, "withSubchart", true);
    withTransition = getOption(options, "withTransition", true);
    withTransform = getOption(options, "withTransform", false);
    withUpdateXDomain = getOption(options, "withUpdateXDomain", false);
    withUpdateOrgXDomain = getOption(options, "withUpdateOrgXDomain", false);
    withTrimXDomain = getOption(options, "withTrimXDomain", true);
    withUpdateXAxis = getOption(options, "withUpdateXAxis", withUpdateXDomain);
    withLegend = getOption(options, "withLegend", false);
    withEventRect = getOption(options, "withEventRect", true);
    withDimension = getOption(options, "withDimension", true);
    withTransitionForExit = getOption(options, "withTransitionForExit", withTransition);
    withTransitionForAxis = getOption(options, "withTransitionForAxis", withTransition);
    duration = withTransition ? config.transition_duration : 0;
    durationForExit = withTransitionForExit ? duration : 0;
    durationForAxis = withTransitionForAxis ? duration : 0;
    transitions = transitions || $$.axis.generateTransitions(durationForAxis); // update legend and transform each g

    if (withLegend && config.legend_show) {
      $$.updateLegend($$.mapToIds($$.data.targets), options, transitions);
    } else if (withDimension) {
      // need to update dimension (e.g. axis.y.tick.values) because y tick values should change
      // no need to update axis in it because they will be updated in redraw()
      $$.updateDimension(true);
    } // MEMO: needed for grids calculation


    if ($$.isCategorized() && targetsToShow.length === 0) {
      $$.x.domain([0, $$.axes.x.selectAll('.tick').size()]);
    }

    if (targetsToShow.length) {
      $$.updateXDomain(targetsToShow, withUpdateXDomain, withUpdateOrgXDomain, withTrimXDomain);

      if (!config.axis_x_tick_values) {
        tickValues = $$.axis.updateXAxisTickValues(targetsToShow);
      }
    } else {
      $$.xAxis.tickValues([]);
      $$.subXAxis.tickValues([]);
    }

    if (config.zoom_rescale && !options.flow) {
      xDomainForZoom = $$.x.orgDomain();
    }

    $$.y.domain($$.getYDomain(targetsToShow, 'y', xDomainForZoom));
    $$.y2.domain($$.getYDomain(targetsToShow, 'y2', xDomainForZoom));

    if (!config.axis_y_tick_values && config.axis_y_tick_count) {
      $$.yAxis.tickValues($$.axis.generateTickValues($$.y.domain(), config.axis_y_tick_count));
    }

    if (!config.axis_y2_tick_values && config.axis_y2_tick_count) {
      $$.y2Axis.tickValues($$.axis.generateTickValues($$.y2.domain(), config.axis_y2_tick_count));
    } // axes


    $$.axis.redraw(durationForAxis, hideAxis); // Update axis label

    $$.axis.updateLabels(withTransition); // show/hide if manual culling needed

    if ((withUpdateXDomain || withUpdateXAxis) && targetsToShow.length) {
      if (config.axis_x_tick_culling && tickValues) {
        for (i = 1; i < tickValues.length; i++) {
          if (tickValues.length / i < config.axis_x_tick_culling_max) {
            intervalForCulling = i;
            break;
          }
        }

        $$.svg.selectAll('.' + CLASS.axisX + ' .tick text').each(function (e) {
          var index = tickValues.indexOf(e);

          if (index >= 0) {
            d3.select(this).style('display', index % intervalForCulling ? 'none' : 'block');
          }
        });
      } else {
        $$.svg.selectAll('.' + CLASS.axisX + ' .tick text').style('display', 'block');
      }
    } // setup drawer - MEMO: these must be called after axis updated


    drawArea = $$.generateDrawArea ? $$.generateDrawArea(areaIndices, false) : undefined;
    drawBar = $$.generateDrawBar ? $$.generateDrawBar(barIndices) : undefined;
    drawLine = $$.generateDrawLine ? $$.generateDrawLine(lineIndices, false) : undefined;
    xForText = $$.generateXYForText(areaIndices, barIndices, lineIndices, true);
    yForText = $$.generateXYForText(areaIndices, barIndices, lineIndices, false); // update circleY based on updated parameters

    $$.updateCircleY(); // generate circle x/y functions depending on updated params

    cx = ($$.config.axis_rotated ? $$.circleY : $$.circleX).bind($$);
    cy = ($$.config.axis_rotated ? $$.circleX : $$.circleY).bind($$); // Update sub domain

    if (withY) {
      $$.subY.domain($$.getYDomain(targetsToShow, 'y'));
      $$.subY2.domain($$.getYDomain(targetsToShow, 'y2'));
    } // xgrid focus


    $$.updateXgridFocus(); // Data empty label positioning and text.

    main.select("text." + CLASS.text + '.' + CLASS.empty).attr("x", $$.width / 2).attr("y", $$.height / 2).text(config.data_empty_label_text).transition().style('opacity', targetsToShow.length ? 0 : 1); // event rect

    if (withEventRect) {
      $$.redrawEventRect();
    } // grid


    $$.updateGrid(duration); // rect for regions

    $$.updateRegion(duration); // bars

    $$.updateBar(durationForExit); // lines, areas and cricles

    $$.updateLine(durationForExit);
    $$.updateArea(durationForExit);
    $$.updateCircle(cx, cy); // text

    if ($$.hasDataLabel()) {
      $$.updateText(xForText, yForText, durationForExit);
    } // title


    if ($$.redrawTitle) {
      $$.redrawTitle();
    } // arc


    if ($$.redrawArc) {
      $$.redrawArc(duration, durationForExit, withTransform);
    } // subchart


    if ($$.redrawSubchart) {
      $$.redrawSubchart(withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices);
    } // circles for select


    main.selectAll('.' + CLASS.selectedCircles).filter($$.isBarType.bind($$)).selectAll('circle').remove();

    if (options.flow) {
      flow = $$.generateFlow({
        targets: targetsToShow,
        flow: options.flow,
        duration: options.flow.duration,
        drawBar: drawBar,
        drawLine: drawLine,
        drawArea: drawArea,
        cx: cx,
        cy: cy,
        xv: xv,
        xForText: xForText,
        yForText: yForText
      });
    }

    if ($$.isTabVisible()) {
      // Only use transition if tab visible. See #938.
      if (duration) {
        // transition should be derived from one transition
        transition = d3.transition().duration(duration);
        transitionsToWait = [];
        [$$.redrawBar(drawBar, true, transition), $$.redrawLine(drawLine, true, transition), $$.redrawArea(drawArea, true, transition), $$.redrawCircle(cx, cy, true, transition), $$.redrawText(xForText, yForText, options.flow, true, transition), $$.redrawRegion(true, transition), $$.redrawGrid(true, transition)].forEach(function (transitions) {
          transitions.forEach(function (transition) {
            transitionsToWait.push(transition);
          });
        }); // Wait for end of transitions to call flow and onrendered callback

        waitForDraw = $$.generateWait();
        transitionsToWait.forEach(function (t) {
          waitForDraw.add(t);
        });
        waitForDraw(function () {
          if (flow) {
            flow();
          }

          if (config.onrendered) {
            config.onrendered.call($$);
          }
        });
      } else {
        $$.redrawBar(drawBar);
        $$.redrawLine(drawLine);
        $$.redrawArea(drawArea);
        $$.redrawCircle(cx, cy);
        $$.redrawText(xForText, yForText, options.flow);
        $$.redrawRegion();
        $$.redrawGrid();

        if (flow) {
          flow();
        }

        if (config.onrendered) {
          config.onrendered.call($$);
        }
      }
    } // update fadein condition


    $$.mapToIds($$.data.targets).forEach(function (id) {
      $$.withoutFadeIn[id] = true;
    });
  };

  ChartInternal.prototype.updateAndRedraw = function (options) {
    var $$ = this,
        config = $$.config,
        transitions;
    options = options || {}; // same with redraw

    options.withTransition = getOption(options, "withTransition", true);
    options.withTransform = getOption(options, "withTransform", false);
    options.withLegend = getOption(options, "withLegend", false); // NOT same with redraw

    options.withUpdateXDomain = getOption(options, "withUpdateXDomain", true);
    options.withUpdateOrgXDomain = getOption(options, "withUpdateOrgXDomain", true);
    options.withTransitionForExit = false;
    options.withTransitionForTransform = getOption(options, "withTransitionForTransform", options.withTransition); // MEMO: this needs to be called before updateLegend and it means this ALWAYS needs to be called)

    $$.updateSizes(); // MEMO: called in updateLegend in redraw if withLegend

    if (!(options.withLegend && config.legend_show)) {
      transitions = $$.axis.generateTransitions(options.withTransitionForAxis ? config.transition_duration : 0); // Update scales

      $$.updateScales();
      $$.updateSvgSize(); // Update g positions

      $$.transformAll(options.withTransitionForTransform, transitions);
    } // Draw with new sizes & scales


    $$.redraw(options, transitions);
  };

  ChartInternal.prototype.redrawWithoutRescale = function () {
    this.redraw({
      withY: false,
      withSubchart: false,
      withEventRect: false,
      withTransitionForAxis: false
    });
  };

  ChartInternal.prototype.isTimeSeries = function () {
    return this.config.axis_x_type === 'timeseries';
  };

  ChartInternal.prototype.isCategorized = function () {
    return this.config.axis_x_type.indexOf('categor') >= 0;
  };

  ChartInternal.prototype.isCustomX = function () {
    var $$ = this,
        config = $$.config;
    return !$$.isTimeSeries() && (config.data_x || notEmpty(config.data_xs));
  };

  ChartInternal.prototype.isTimeSeriesY = function () {
    return this.config.axis_y_type === 'timeseries';
  };

  ChartInternal.prototype.getTranslate = function (target) {
    var $$ = this,
        config = $$.config,
        x,
        y;

    if (target === 'main') {
      x = asHalfPixel($$.margin.left);
      y = asHalfPixel($$.margin.top);
    } else if (target === 'context') {
      x = asHalfPixel($$.margin2.left);
      y = asHalfPixel($$.margin2.top);
    } else if (target === 'legend') {
      x = $$.margin3.left;
      y = $$.margin3.top;
    } else if (target === 'x') {
      x = 0;
      y = config.axis_rotated ? 0 : $$.height;
    } else if (target === 'y') {
      x = 0;
      y = config.axis_rotated ? $$.height : 0;
    } else if (target === 'y2') {
      x = config.axis_rotated ? 0 : $$.width;
      y = config.axis_rotated ? 1 : 0;
    } else if (target === 'subx') {
      x = 0;
      y = config.axis_rotated ? 0 : $$.height2;
    } else if (target === 'arc') {
      x = $$.arcWidth / 2;
      y = $$.arcHeight / 2 - ($$.hasType('gauge') ? 6 : 0); // to prevent wrong display of min and max label
    }

    return "translate(" + x + "," + y + ")";
  };

  ChartInternal.prototype.initialOpacity = function (d) {
    return d.value !== null && this.withoutFadeIn[d.id] ? 1 : 0;
  };

  ChartInternal.prototype.initialOpacityForCircle = function (d) {
    return d.value !== null && this.withoutFadeIn[d.id] ? this.opacityForCircle(d) : 0;
  };

  ChartInternal.prototype.opacityForCircle = function (d) {
    var isPointShouldBeShown = isFunction(this.config.point_show) ? this.config.point_show(d) : this.config.point_show;
    var opacity = isPointShouldBeShown ? 1 : 0;
    return isValue(d.value) ? this.isScatterType(d) ? 0.5 : opacity : 0;
  };

  ChartInternal.prototype.opacityForText = function () {
    return this.hasDataLabel() ? 1 : 0;
  };

  ChartInternal.prototype.xx = function (d) {
    return d ? this.x(d.x) : null;
  };

  ChartInternal.prototype.xv = function (d) {
    var $$ = this,
        value = d.value;

    if ($$.isTimeSeries()) {
      value = $$.parseDate(d.value);
    } else if ($$.isCategorized() && typeof d.value === 'string') {
      value = $$.config.axis_x_categories.indexOf(d.value);
    }

    return Math.ceil($$.x(value));
  };

  ChartInternal.prototype.yv = function (d) {
    var $$ = this,
        yScale = d.axis && d.axis === 'y2' ? $$.y2 : $$.y;
    return Math.ceil(yScale(d.value));
  };

  ChartInternal.prototype.subxx = function (d) {
    return d ? this.subX(d.x) : null;
  };

  ChartInternal.prototype.transformMain = function (withTransition, transitions) {
    var $$ = this,
        xAxis,
        yAxis,
        y2Axis;

    if (transitions && transitions.axisX) {
      xAxis = transitions.axisX;
    } else {
      xAxis = $$.main.select('.' + CLASS.axisX);

      if (withTransition) {
        xAxis = xAxis.transition();
      }
    }

    if (transitions && transitions.axisY) {
      yAxis = transitions.axisY;
    } else {
      yAxis = $$.main.select('.' + CLASS.axisY);

      if (withTransition) {
        yAxis = yAxis.transition();
      }
    }

    if (transitions && transitions.axisY2) {
      y2Axis = transitions.axisY2;
    } else {
      y2Axis = $$.main.select('.' + CLASS.axisY2);

      if (withTransition) {
        y2Axis = y2Axis.transition();
      }
    }

    (withTransition ? $$.main.transition() : $$.main).attr("transform", $$.getTranslate('main'));
    xAxis.attr("transform", $$.getTranslate('x'));
    yAxis.attr("transform", $$.getTranslate('y'));
    y2Axis.attr("transform", $$.getTranslate('y2'));
    $$.main.select('.' + CLASS.chartArcs).attr("transform", $$.getTranslate('arc'));
  };

  ChartInternal.prototype.transformAll = function (withTransition, transitions) {
    var $$ = this;
    $$.transformMain(withTransition, transitions);

    if ($$.config.subchart_show) {
      $$.transformContext(withTransition, transitions);
    }

    if ($$.legend) {
      $$.transformLegend(withTransition);
    }
  };

  ChartInternal.prototype.updateSvgSize = function () {
    var $$ = this,
        brush = $$.svg.select(".c3-brush .overlay");
    $$.svg.attr('width', $$.currentWidth).attr('height', $$.currentHeight);
    $$.svg.selectAll(['#' + $$.clipId, '#' + $$.clipIdForGrid]).select('rect').attr('width', $$.width).attr('height', $$.height);
    $$.svg.select('#' + $$.clipIdForXAxis).select('rect').attr('x', $$.getXAxisClipX.bind($$)).attr('y', $$.getXAxisClipY.bind($$)).attr('width', $$.getXAxisClipWidth.bind($$)).attr('height', $$.getXAxisClipHeight.bind($$));
    $$.svg.select('#' + $$.clipIdForYAxis).select('rect').attr('x', $$.getYAxisClipX.bind($$)).attr('y', $$.getYAxisClipY.bind($$)).attr('width', $$.getYAxisClipWidth.bind($$)).attr('height', $$.getYAxisClipHeight.bind($$));
    $$.svg.select('#' + $$.clipIdForSubchart).select('rect').attr('width', $$.width).attr('height', brush.size() ? brush.attr('height') : 0); // MEMO: parent div's height will be bigger than svg when <!DOCTYPE html>

    $$.selectChart.style('max-height', $$.currentHeight + "px");
  };

  ChartInternal.prototype.updateDimension = function (withoutAxis) {
    var $$ = this;

    if (!withoutAxis) {
      if ($$.config.axis_rotated) {
        $$.axes.x.call($$.xAxis);
        $$.axes.subx.call($$.subXAxis);
      } else {
        $$.axes.y.call($$.yAxis);
        $$.axes.y2.call($$.y2Axis);
      }
    }

    $$.updateSizes();
    $$.updateScales();
    $$.updateSvgSize();
    $$.transformAll(false);
  };

  ChartInternal.prototype.observeInserted = function (selection) {
    var $$ = this,
        observer;

    if (typeof MutationObserver === 'undefined') {
      window.console.error("MutationObserver not defined.");
      return;
    }

    observer = new MutationObserver(function (mutations) {
      mutations.forEach(function (mutation) {
        if (mutation.type === 'childList' && mutation.previousSibling) {
          observer.disconnect(); // need to wait for completion of load because size calculation requires the actual sizes determined after that completion

          $$.intervalForObserveInserted = window.setInterval(function () {
            // parentNode will NOT be null when completed
            if (selection.node().parentNode) {
              window.clearInterval($$.intervalForObserveInserted);
              $$.updateDimension();

              if ($$.brush) {
                $$.brush.update();
              }

              $$.config.oninit.call($$);
              $$.redraw({
                withTransform: true,
                withUpdateXDomain: true,
                withUpdateOrgXDomain: true,
                withTransition: false,
                withTransitionForTransform: false,
                withLegend: true
              });
              selection.transition().style('opacity', 1);
            }
          }, 10);
        }
      });
    });
    observer.observe(selection.node(), {
      attributes: true,
      childList: true,
      characterData: true
    });
  };

  ChartInternal.prototype.bindResize = function () {
    var $$ = this,
        config = $$.config;
    $$.resizeFunction = $$.generateResize(); // need to call .remove

    $$.resizeFunction.add(function () {
      config.onresize.call($$);
    });

    if (config.resize_auto) {
      $$.resizeFunction.add(function () {
        if ($$.resizeTimeout !== undefined) {
          window.clearTimeout($$.resizeTimeout);
        }

        $$.resizeTimeout = window.setTimeout(function () {
          delete $$.resizeTimeout;
          $$.updateAndRedraw({
            withUpdateXDomain: false,
            withUpdateOrgXDomain: false,
            withTransition: false,
            withTransitionForTransform: false,
            withLegend: true
          });

          if ($$.brush) {
            $$.brush.update();
          }
        }, 100);
      });
    }

    $$.resizeFunction.add(function () {
      config.onresized.call($$);
    });

    $$.resizeIfElementDisplayed = function () {
      // if element not displayed skip it
      if ($$.api == null || !$$.api.element.offsetParent) {
        return;
      }

      $$.resizeFunction();
    };

    if (window.attachEvent) {
      window.attachEvent('onresize', $$.resizeIfElementDisplayed);
    } else if (window.addEventListener) {
      window.addEventListener('resize', $$.resizeIfElementDisplayed, false);
    } else {
      // fallback to this, if this is a very old browser
      var wrapper = window.onresize;

      if (!wrapper) {
        // create a wrapper that will call all charts
        wrapper = $$.generateResize();
      } else if (!wrapper.add || !wrapper.remove) {
        // there is already a handler registered, make sure we call it too
        wrapper = $$.generateResize();
        wrapper.add(window.onresize);
      } // add this graph to the wrapper, we will be removed if the user calls destroy


      wrapper.add($$.resizeFunction);

      window.onresize = function () {
        // if element not displayed skip it
        if (!$$.api.element.offsetParent) {
          return;
        }

        wrapper();
      };
    }
  };

  ChartInternal.prototype.generateResize = function () {
    var resizeFunctions = [];

    function callResizeFunctions() {
      resizeFunctions.forEach(function (f) {
        f();
      });
    }

    callResizeFunctions.add = function (f) {
      resizeFunctions.push(f);
    };

    callResizeFunctions.remove = function (f) {
      for (var i = 0; i < resizeFunctions.length; i++) {
        if (resizeFunctions[i] === f) {
          resizeFunctions.splice(i, 1);
          break;
        }
      }
    };

    return callResizeFunctions;
  };

  ChartInternal.prototype.endall = function (transition, callback) {
    var n = 0;
    transition.each(function () {
      ++n;
    }).on("end", function () {
      if (! --n) {
        callback.apply(this, arguments);
      }
    });
  };

  ChartInternal.prototype.generateWait = function () {
    var transitionsToWait = [],
        f = function f(callback) {
      var timer = setInterval(function () {
        var done = 0;
        transitionsToWait.forEach(function (t) {
          if (t.empty()) {
            done += 1;
            return;
          }

          try {
            t.transition();
          } catch (e) {
            done += 1;
          }
        });

        if (done === transitionsToWait.length) {
          clearInterval(timer);

          if (callback) {
            callback();
          }
        }
      }, 50);
    };

    f.add = function (transition) {
      transitionsToWait.push(transition);
    };

    return f;
  };

  ChartInternal.prototype.parseDate = function (date) {
    var $$ = this,
        parsedDate;

    if (date instanceof Date) {
      parsedDate = date;
    } else if (typeof date === 'string') {
      parsedDate = $$.dataTimeParse(date);
    } else if (_typeof(date) === 'object') {
      parsedDate = new Date(+date);
    } else if (typeof date === 'number' && !isNaN(date)) {
      parsedDate = new Date(+date);
    }

    if (!parsedDate || isNaN(+parsedDate)) {
      window.console.error("Failed to parse x '" + date + "' to Date object");
    }

    return parsedDate;
  };

  ChartInternal.prototype.isTabVisible = function () {
    var hidden;

    if (typeof document.hidden !== "undefined") {
      // Opera 12.10 and Firefox 18 and later support
      hidden = "hidden";
    } else if (typeof document.mozHidden !== "undefined") {
      hidden = "mozHidden";
    } else if (typeof document.msHidden !== "undefined") {
      hidden = "msHidden";
    } else if (typeof document.webkitHidden !== "undefined") {
      hidden = "webkitHidden";
    }

    return document[hidden] ? false : true;
  };

  ChartInternal.prototype.getPathBox = getPathBox;
  ChartInternal.prototype.CLASS = CLASS;

  /* jshint ignore:start */
  // SVGPathSeg API polyfill
  // https://github.com/progers/pathseg
  //
  // This is a drop-in replacement for the SVGPathSeg and SVGPathSegList APIs that were removed from
  // SVG2 (https://lists.w3.org/Archives/Public/www-svg/2015Jun/0044.html), including the latest spec
  // changes which were implemented in Firefox 43 and Chrome 46.
  (function () {

    if (!("SVGPathSeg" in window)) {
      // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSeg
      window.SVGPathSeg = function (type, typeAsLetter, owningPathSegList) {
        this.pathSegType = type;
        this.pathSegTypeAsLetter = typeAsLetter;
        this._owningPathSegList = owningPathSegList;
      };

      window.SVGPathSeg.prototype.classname = "SVGPathSeg";
      window.SVGPathSeg.PATHSEG_UNKNOWN = 0;
      window.SVGPathSeg.PATHSEG_CLOSEPATH = 1;
      window.SVGPathSeg.PATHSEG_MOVETO_ABS = 2;
      window.SVGPathSeg.PATHSEG_MOVETO_REL = 3;
      window.SVGPathSeg.PATHSEG_LINETO_ABS = 4;
      window.SVGPathSeg.PATHSEG_LINETO_REL = 5;
      window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS = 6;
      window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL = 7;
      window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS = 8;
      window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL = 9;
      window.SVGPathSeg.PATHSEG_ARC_ABS = 10;
      window.SVGPathSeg.PATHSEG_ARC_REL = 11;
      window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS = 12;
      window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL = 13;
      window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS = 14;
      window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL = 15;
      window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS = 16;
      window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL = 17;
      window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS = 18;
      window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL = 19; // Notify owning PathSegList on any changes so they can be synchronized back to the path element.

      window.SVGPathSeg.prototype._segmentChanged = function () {
        if (this._owningPathSegList) this._owningPathSegList.segmentChanged(this);
      };

      window.SVGPathSegClosePath = function (owningPathSegList) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CLOSEPATH, "z", owningPathSegList);
      };

      window.SVGPathSegClosePath.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegClosePath.prototype.toString = function () {
        return "[object SVGPathSegClosePath]";
      };

      window.SVGPathSegClosePath.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter;
      };

      window.SVGPathSegClosePath.prototype.clone = function () {
        return new window.SVGPathSegClosePath(undefined);
      };

      window.SVGPathSegMovetoAbs = function (owningPathSegList, x, y) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_MOVETO_ABS, "M", owningPathSegList);
        this._x = x;
        this._y = y;
      };

      window.SVGPathSegMovetoAbs.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegMovetoAbs.prototype.toString = function () {
        return "[object SVGPathSegMovetoAbs]";
      };

      window.SVGPathSegMovetoAbs.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x + " " + this._y;
      };

      window.SVGPathSegMovetoAbs.prototype.clone = function () {
        return new window.SVGPathSegMovetoAbs(undefined, this._x, this._y);
      };

      Object.defineProperty(window.SVGPathSegMovetoAbs.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegMovetoAbs.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegMovetoRel = function (owningPathSegList, x, y) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_MOVETO_REL, "m", owningPathSegList);
        this._x = x;
        this._y = y;
      };

      window.SVGPathSegMovetoRel.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegMovetoRel.prototype.toString = function () {
        return "[object SVGPathSegMovetoRel]";
      };

      window.SVGPathSegMovetoRel.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x + " " + this._y;
      };

      window.SVGPathSegMovetoRel.prototype.clone = function () {
        return new window.SVGPathSegMovetoRel(undefined, this._x, this._y);
      };

      Object.defineProperty(window.SVGPathSegMovetoRel.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegMovetoRel.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegLinetoAbs = function (owningPathSegList, x, y) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_LINETO_ABS, "L", owningPathSegList);
        this._x = x;
        this._y = y;
      };

      window.SVGPathSegLinetoAbs.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegLinetoAbs.prototype.toString = function () {
        return "[object SVGPathSegLinetoAbs]";
      };

      window.SVGPathSegLinetoAbs.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x + " " + this._y;
      };

      window.SVGPathSegLinetoAbs.prototype.clone = function () {
        return new window.SVGPathSegLinetoAbs(undefined, this._x, this._y);
      };

      Object.defineProperty(window.SVGPathSegLinetoAbs.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegLinetoAbs.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegLinetoRel = function (owningPathSegList, x, y) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_LINETO_REL, "l", owningPathSegList);
        this._x = x;
        this._y = y;
      };

      window.SVGPathSegLinetoRel.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegLinetoRel.prototype.toString = function () {
        return "[object SVGPathSegLinetoRel]";
      };

      window.SVGPathSegLinetoRel.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x + " " + this._y;
      };

      window.SVGPathSegLinetoRel.prototype.clone = function () {
        return new window.SVGPathSegLinetoRel(undefined, this._x, this._y);
      };

      Object.defineProperty(window.SVGPathSegLinetoRel.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegLinetoRel.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegCurvetoCubicAbs = function (owningPathSegList, x, y, x1, y1, x2, y2) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS, "C", owningPathSegList);
        this._x = x;
        this._y = y;
        this._x1 = x1;
        this._y1 = y1;
        this._x2 = x2;
        this._y2 = y2;
      };

      window.SVGPathSegCurvetoCubicAbs.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegCurvetoCubicAbs.prototype.toString = function () {
        return "[object SVGPathSegCurvetoCubicAbs]";
      };

      window.SVGPathSegCurvetoCubicAbs.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y;
      };

      window.SVGPathSegCurvetoCubicAbs.prototype.clone = function () {
        return new window.SVGPathSegCurvetoCubicAbs(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2);
      };

      Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, "x1", {
        get: function get() {
          return this._x1;
        },
        set: function set(x1) {
          this._x1 = x1;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, "y1", {
        get: function get() {
          return this._y1;
        },
        set: function set(y1) {
          this._y1 = y1;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, "x2", {
        get: function get() {
          return this._x2;
        },
        set: function set(x2) {
          this._x2 = x2;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, "y2", {
        get: function get() {
          return this._y2;
        },
        set: function set(y2) {
          this._y2 = y2;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegCurvetoCubicRel = function (owningPathSegList, x, y, x1, y1, x2, y2) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL, "c", owningPathSegList);
        this._x = x;
        this._y = y;
        this._x1 = x1;
        this._y1 = y1;
        this._x2 = x2;
        this._y2 = y2;
      };

      window.SVGPathSegCurvetoCubicRel.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegCurvetoCubicRel.prototype.toString = function () {
        return "[object SVGPathSegCurvetoCubicRel]";
      };

      window.SVGPathSegCurvetoCubicRel.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y;
      };

      window.SVGPathSegCurvetoCubicRel.prototype.clone = function () {
        return new window.SVGPathSegCurvetoCubicRel(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2);
      };

      Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, "x1", {
        get: function get() {
          return this._x1;
        },
        set: function set(x1) {
          this._x1 = x1;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, "y1", {
        get: function get() {
          return this._y1;
        },
        set: function set(y1) {
          this._y1 = y1;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, "x2", {
        get: function get() {
          return this._x2;
        },
        set: function set(x2) {
          this._x2 = x2;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, "y2", {
        get: function get() {
          return this._y2;
        },
        set: function set(y2) {
          this._y2 = y2;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegCurvetoQuadraticAbs = function (owningPathSegList, x, y, x1, y1) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS, "Q", owningPathSegList);
        this._x = x;
        this._y = y;
        this._x1 = x1;
        this._y1 = y1;
      };

      window.SVGPathSegCurvetoQuadraticAbs.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegCurvetoQuadraticAbs.prototype.toString = function () {
        return "[object SVGPathSegCurvetoQuadraticAbs]";
      };

      window.SVGPathSegCurvetoQuadraticAbs.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x + " " + this._y;
      };

      window.SVGPathSegCurvetoQuadraticAbs.prototype.clone = function () {
        return new window.SVGPathSegCurvetoQuadraticAbs(undefined, this._x, this._y, this._x1, this._y1);
      };

      Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype, "x1", {
        get: function get() {
          return this._x1;
        },
        set: function set(x1) {
          this._x1 = x1;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype, "y1", {
        get: function get() {
          return this._y1;
        },
        set: function set(y1) {
          this._y1 = y1;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegCurvetoQuadraticRel = function (owningPathSegList, x, y, x1, y1) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL, "q", owningPathSegList);
        this._x = x;
        this._y = y;
        this._x1 = x1;
        this._y1 = y1;
      };

      window.SVGPathSegCurvetoQuadraticRel.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegCurvetoQuadraticRel.prototype.toString = function () {
        return "[object SVGPathSegCurvetoQuadraticRel]";
      };

      window.SVGPathSegCurvetoQuadraticRel.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x1 + " " + this._y1 + " " + this._x + " " + this._y;
      };

      window.SVGPathSegCurvetoQuadraticRel.prototype.clone = function () {
        return new window.SVGPathSegCurvetoQuadraticRel(undefined, this._x, this._y, this._x1, this._y1);
      };

      Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype, "x1", {
        get: function get() {
          return this._x1;
        },
        set: function set(x1) {
          this._x1 = x1;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype, "y1", {
        get: function get() {
          return this._y1;
        },
        set: function set(y1) {
          this._y1 = y1;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegArcAbs = function (owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_ARC_ABS, "A", owningPathSegList);
        this._x = x;
        this._y = y;
        this._r1 = r1;
        this._r2 = r2;
        this._angle = angle;
        this._largeArcFlag = largeArcFlag;
        this._sweepFlag = sweepFlag;
      };

      window.SVGPathSegArcAbs.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegArcAbs.prototype.toString = function () {
        return "[object SVGPathSegArcAbs]";
      };

      window.SVGPathSegArcAbs.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._r1 + " " + this._r2 + " " + this._angle + " " + (this._largeArcFlag ? "1" : "0") + " " + (this._sweepFlag ? "1" : "0") + " " + this._x + " " + this._y;
      };

      window.SVGPathSegArcAbs.prototype.clone = function () {
        return new window.SVGPathSegArcAbs(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag);
      };

      Object.defineProperty(window.SVGPathSegArcAbs.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegArcAbs.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegArcAbs.prototype, "r1", {
        get: function get() {
          return this._r1;
        },
        set: function set(r1) {
          this._r1 = r1;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegArcAbs.prototype, "r2", {
        get: function get() {
          return this._r2;
        },
        set: function set(r2) {
          this._r2 = r2;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegArcAbs.prototype, "angle", {
        get: function get() {
          return this._angle;
        },
        set: function set(angle) {
          this._angle = angle;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegArcAbs.prototype, "largeArcFlag", {
        get: function get() {
          return this._largeArcFlag;
        },
        set: function set(largeArcFlag) {
          this._largeArcFlag = largeArcFlag;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegArcAbs.prototype, "sweepFlag", {
        get: function get() {
          return this._sweepFlag;
        },
        set: function set(sweepFlag) {
          this._sweepFlag = sweepFlag;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegArcRel = function (owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_ARC_REL, "a", owningPathSegList);
        this._x = x;
        this._y = y;
        this._r1 = r1;
        this._r2 = r2;
        this._angle = angle;
        this._largeArcFlag = largeArcFlag;
        this._sweepFlag = sweepFlag;
      };

      window.SVGPathSegArcRel.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegArcRel.prototype.toString = function () {
        return "[object SVGPathSegArcRel]";
      };

      window.SVGPathSegArcRel.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._r1 + " " + this._r2 + " " + this._angle + " " + (this._largeArcFlag ? "1" : "0") + " " + (this._sweepFlag ? "1" : "0") + " " + this._x + " " + this._y;
      };

      window.SVGPathSegArcRel.prototype.clone = function () {
        return new window.SVGPathSegArcRel(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag);
      };

      Object.defineProperty(window.SVGPathSegArcRel.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegArcRel.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegArcRel.prototype, "r1", {
        get: function get() {
          return this._r1;
        },
        set: function set(r1) {
          this._r1 = r1;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegArcRel.prototype, "r2", {
        get: function get() {
          return this._r2;
        },
        set: function set(r2) {
          this._r2 = r2;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegArcRel.prototype, "angle", {
        get: function get() {
          return this._angle;
        },
        set: function set(angle) {
          this._angle = angle;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegArcRel.prototype, "largeArcFlag", {
        get: function get() {
          return this._largeArcFlag;
        },
        set: function set(largeArcFlag) {
          this._largeArcFlag = largeArcFlag;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegArcRel.prototype, "sweepFlag", {
        get: function get() {
          return this._sweepFlag;
        },
        set: function set(sweepFlag) {
          this._sweepFlag = sweepFlag;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegLinetoHorizontalAbs = function (owningPathSegList, x) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS, "H", owningPathSegList);
        this._x = x;
      };

      window.SVGPathSegLinetoHorizontalAbs.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegLinetoHorizontalAbs.prototype.toString = function () {
        return "[object SVGPathSegLinetoHorizontalAbs]";
      };

      window.SVGPathSegLinetoHorizontalAbs.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x;
      };

      window.SVGPathSegLinetoHorizontalAbs.prototype.clone = function () {
        return new window.SVGPathSegLinetoHorizontalAbs(undefined, this._x);
      };

      Object.defineProperty(window.SVGPathSegLinetoHorizontalAbs.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegLinetoHorizontalRel = function (owningPathSegList, x) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL, "h", owningPathSegList);
        this._x = x;
      };

      window.SVGPathSegLinetoHorizontalRel.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegLinetoHorizontalRel.prototype.toString = function () {
        return "[object SVGPathSegLinetoHorizontalRel]";
      };

      window.SVGPathSegLinetoHorizontalRel.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x;
      };

      window.SVGPathSegLinetoHorizontalRel.prototype.clone = function () {
        return new window.SVGPathSegLinetoHorizontalRel(undefined, this._x);
      };

      Object.defineProperty(window.SVGPathSegLinetoHorizontalRel.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegLinetoVerticalAbs = function (owningPathSegList, y) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS, "V", owningPathSegList);
        this._y = y;
      };

      window.SVGPathSegLinetoVerticalAbs.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegLinetoVerticalAbs.prototype.toString = function () {
        return "[object SVGPathSegLinetoVerticalAbs]";
      };

      window.SVGPathSegLinetoVerticalAbs.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._y;
      };

      window.SVGPathSegLinetoVerticalAbs.prototype.clone = function () {
        return new window.SVGPathSegLinetoVerticalAbs(undefined, this._y);
      };

      Object.defineProperty(window.SVGPathSegLinetoVerticalAbs.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegLinetoVerticalRel = function (owningPathSegList, y) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL, "v", owningPathSegList);
        this._y = y;
      };

      window.SVGPathSegLinetoVerticalRel.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegLinetoVerticalRel.prototype.toString = function () {
        return "[object SVGPathSegLinetoVerticalRel]";
      };

      window.SVGPathSegLinetoVerticalRel.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._y;
      };

      window.SVGPathSegLinetoVerticalRel.prototype.clone = function () {
        return new window.SVGPathSegLinetoVerticalRel(undefined, this._y);
      };

      Object.defineProperty(window.SVGPathSegLinetoVerticalRel.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegCurvetoCubicSmoothAbs = function (owningPathSegList, x, y, x2, y2) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS, "S", owningPathSegList);
        this._x = x;
        this._y = y;
        this._x2 = x2;
        this._y2 = y2;
      };

      window.SVGPathSegCurvetoCubicSmoothAbs.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegCurvetoCubicSmoothAbs.prototype.toString = function () {
        return "[object SVGPathSegCurvetoCubicSmoothAbs]";
      };

      window.SVGPathSegCurvetoCubicSmoothAbs.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y;
      };

      window.SVGPathSegCurvetoCubicSmoothAbs.prototype.clone = function () {
        return new window.SVGPathSegCurvetoCubicSmoothAbs(undefined, this._x, this._y, this._x2, this._y2);
      };

      Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothAbs.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothAbs.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothAbs.prototype, "x2", {
        get: function get() {
          return this._x2;
        },
        set: function set(x2) {
          this._x2 = x2;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothAbs.prototype, "y2", {
        get: function get() {
          return this._y2;
        },
        set: function set(y2) {
          this._y2 = y2;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegCurvetoCubicSmoothRel = function (owningPathSegList, x, y, x2, y2) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL, "s", owningPathSegList);
        this._x = x;
        this._y = y;
        this._x2 = x2;
        this._y2 = y2;
      };

      window.SVGPathSegCurvetoCubicSmoothRel.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegCurvetoCubicSmoothRel.prototype.toString = function () {
        return "[object SVGPathSegCurvetoCubicSmoothRel]";
      };

      window.SVGPathSegCurvetoCubicSmoothRel.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x2 + " " + this._y2 + " " + this._x + " " + this._y;
      };

      window.SVGPathSegCurvetoCubicSmoothRel.prototype.clone = function () {
        return new window.SVGPathSegCurvetoCubicSmoothRel(undefined, this._x, this._y, this._x2, this._y2);
      };

      Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothRel.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothRel.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothRel.prototype, "x2", {
        get: function get() {
          return this._x2;
        },
        set: function set(x2) {
          this._x2 = x2;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoCubicSmoothRel.prototype, "y2", {
        get: function get() {
          return this._y2;
        },
        set: function set(y2) {
          this._y2 = y2;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegCurvetoQuadraticSmoothAbs = function (owningPathSegList, x, y) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS, "T", owningPathSegList);
        this._x = x;
        this._y = y;
      };

      window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype.toString = function () {
        return "[object SVGPathSegCurvetoQuadraticSmoothAbs]";
      };

      window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x + " " + this._y;
      };

      window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype.clone = function () {
        return new window.SVGPathSegCurvetoQuadraticSmoothAbs(undefined, this._x, this._y);
      };

      Object.defineProperty(window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      });

      window.SVGPathSegCurvetoQuadraticSmoothRel = function (owningPathSegList, x, y) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL, "t", owningPathSegList);
        this._x = x;
        this._y = y;
      };

      window.SVGPathSegCurvetoQuadraticSmoothRel.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegCurvetoQuadraticSmoothRel.prototype.toString = function () {
        return "[object SVGPathSegCurvetoQuadraticSmoothRel]";
      };

      window.SVGPathSegCurvetoQuadraticSmoothRel.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x + " " + this._y;
      };

      window.SVGPathSegCurvetoQuadraticSmoothRel.prototype.clone = function () {
        return new window.SVGPathSegCurvetoQuadraticSmoothRel(undefined, this._x, this._y);
      };

      Object.defineProperty(window.SVGPathSegCurvetoQuadraticSmoothRel.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathSegCurvetoQuadraticSmoothRel.prototype, "y", {
        get: function get() {
          return this._y;
        },
        set: function set(y) {
          this._y = y;

          this._segmentChanged();
        },
        enumerable: true
      }); // Add createSVGPathSeg* functions to window.SVGPathElement.
      // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-Interfacewindow.SVGPathElement.

      window.SVGPathElement.prototype.createSVGPathSegClosePath = function () {
        return new window.SVGPathSegClosePath(undefined);
      };

      window.SVGPathElement.prototype.createSVGPathSegMovetoAbs = function (x, y) {
        return new window.SVGPathSegMovetoAbs(undefined, x, y);
      };

      window.SVGPathElement.prototype.createSVGPathSegMovetoRel = function (x, y) {
        return new window.SVGPathSegMovetoRel(undefined, x, y);
      };

      window.SVGPathElement.prototype.createSVGPathSegLinetoAbs = function (x, y) {
        return new window.SVGPathSegLinetoAbs(undefined, x, y);
      };

      window.SVGPathElement.prototype.createSVGPathSegLinetoRel = function (x, y) {
        return new window.SVGPathSegLinetoRel(undefined, x, y);
      };

      window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicAbs = function (x, y, x1, y1, x2, y2) {
        return new window.SVGPathSegCurvetoCubicAbs(undefined, x, y, x1, y1, x2, y2);
      };

      window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicRel = function (x, y, x1, y1, x2, y2) {
        return new window.SVGPathSegCurvetoCubicRel(undefined, x, y, x1, y1, x2, y2);
      };

      window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticAbs = function (x, y, x1, y1) {
        return new window.SVGPathSegCurvetoQuadraticAbs(undefined, x, y, x1, y1);
      };

      window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticRel = function (x, y, x1, y1) {
        return new window.SVGPathSegCurvetoQuadraticRel(undefined, x, y, x1, y1);
      };

      window.SVGPathElement.prototype.createSVGPathSegArcAbs = function (x, y, r1, r2, angle, largeArcFlag, sweepFlag) {
        return new window.SVGPathSegArcAbs(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag);
      };

      window.SVGPathElement.prototype.createSVGPathSegArcRel = function (x, y, r1, r2, angle, largeArcFlag, sweepFlag) {
        return new window.SVGPathSegArcRel(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag);
      };

      window.SVGPathElement.prototype.createSVGPathSegLinetoHorizontalAbs = function (x) {
        return new window.SVGPathSegLinetoHorizontalAbs(undefined, x);
      };

      window.SVGPathElement.prototype.createSVGPathSegLinetoHorizontalRel = function (x) {
        return new window.SVGPathSegLinetoHorizontalRel(undefined, x);
      };

      window.SVGPathElement.prototype.createSVGPathSegLinetoVerticalAbs = function (y) {
        return new window.SVGPathSegLinetoVerticalAbs(undefined, y);
      };

      window.SVGPathElement.prototype.createSVGPathSegLinetoVerticalRel = function (y) {
        return new window.SVGPathSegLinetoVerticalRel(undefined, y);
      };

      window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothAbs = function (x, y, x2, y2) {
        return new window.SVGPathSegCurvetoCubicSmoothAbs(undefined, x, y, x2, y2);
      };

      window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothRel = function (x, y, x2, y2) {
        return new window.SVGPathSegCurvetoCubicSmoothRel(undefined, x, y, x2, y2);
      };

      window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothAbs = function (x, y) {
        return new window.SVGPathSegCurvetoQuadraticSmoothAbs(undefined, x, y);
      };

      window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothRel = function (x, y) {
        return new window.SVGPathSegCurvetoQuadraticSmoothRel(undefined, x, y);
      };

      if (!("getPathSegAtLength" in window.SVGPathElement.prototype)) {
        // Add getPathSegAtLength to SVGPathElement.
        // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-__svg__SVGPathElement__getPathSegAtLength
        // This polyfill requires SVGPathElement.getTotalLength to implement the distance-along-a-path algorithm.
        window.SVGPathElement.prototype.getPathSegAtLength = function (distance) {
          if (distance === undefined || !isFinite(distance)) throw "Invalid arguments.";
          var measurementElement = document.createElementNS("http://www.w3.org/2000/svg", "path");
          measurementElement.setAttribute("d", this.getAttribute("d"));
          var lastPathSegment = measurementElement.pathSegList.numberOfItems - 1; // If the path is empty, return 0.

          if (lastPathSegment <= 0) return 0;

          do {
            measurementElement.pathSegList.removeItem(lastPathSegment);
            if (distance > measurementElement.getTotalLength()) break;
            lastPathSegment--;
          } while (lastPathSegment > 0);

          return lastPathSegment;
        };
      }
    }

    if (!("SVGPathSegList" in window)) {
      // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSegList
      window.SVGPathSegList = function (pathElement) {
        this._pathElement = pathElement;
        this._list = this._parsePath(this._pathElement.getAttribute("d")); // Use a MutationObserver to catch changes to the path's "d" attribute.

        this._mutationObserverConfig = {
          "attributes": true,
          "attributeFilter": ["d"]
        };
        this._pathElementMutationObserver = new MutationObserver(this._updateListFromPathMutations.bind(this));

        this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig);
      };

      window.SVGPathSegList.prototype.classname = "SVGPathSegList";
      Object.defineProperty(window.SVGPathSegList.prototype, "numberOfItems", {
        get: function get() {
          this._checkPathSynchronizedToList();

          return this._list.length;
        },
        enumerable: true
      }); // Add the pathSegList accessors to window.SVGPathElement.
      // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGAnimatedPathData

      Object.defineProperty(window.SVGPathElement.prototype, "pathSegList", {
        get: function get() {
          if (!this._pathSegList) this._pathSegList = new window.SVGPathSegList(this);
          return this._pathSegList;
        },
        enumerable: true
      }); // FIXME: The following are not implemented and simply return window.SVGPathElement.pathSegList.

      Object.defineProperty(window.SVGPathElement.prototype, "normalizedPathSegList", {
        get: function get() {
          return this.pathSegList;
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathElement.prototype, "animatedPathSegList", {
        get: function get() {
          return this.pathSegList;
        },
        enumerable: true
      });
      Object.defineProperty(window.SVGPathElement.prototype, "animatedNormalizedPathSegList", {
        get: function get() {
          return this.pathSegList;
        },
        enumerable: true
      }); // Process any pending mutations to the path element and update the list as needed.
      // This should be the first call of all public functions and is needed because
      // MutationObservers are not synchronous so we can have pending asynchronous mutations.

      window.SVGPathSegList.prototype._checkPathSynchronizedToList = function () {
        this._updateListFromPathMutations(this._pathElementMutationObserver.takeRecords());
      };

      window.SVGPathSegList.prototype._updateListFromPathMutations = function (mutationRecords) {
        if (!this._pathElement) return;
        var hasPathMutations = false;
        mutationRecords.forEach(function (record) {
          if (record.attributeName == "d") hasPathMutations = true;
        });
        if (hasPathMutations) this._list = this._parsePath(this._pathElement.getAttribute("d"));
      }; // Serialize the list and update the path's 'd' attribute.


      window.SVGPathSegList.prototype._writeListToPath = function () {
        this._pathElementMutationObserver.disconnect();

        this._pathElement.setAttribute("d", window.SVGPathSegList._pathSegArrayAsString(this._list));

        this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig);
      }; // When a path segment changes the list needs to be synchronized back to the path element.


      window.SVGPathSegList.prototype.segmentChanged = function (pathSeg) {
        this._writeListToPath();
      };

      window.SVGPathSegList.prototype.clear = function () {
        this._checkPathSynchronizedToList();

        this._list.forEach(function (pathSeg) {
          pathSeg._owningPathSegList = null;
        });

        this._list = [];

        this._writeListToPath();
      };

      window.SVGPathSegList.prototype.initialize = function (newItem) {
        this._checkPathSynchronizedToList();

        this._list = [newItem];
        newItem._owningPathSegList = this;

        this._writeListToPath();

        return newItem;
      };

      window.SVGPathSegList.prototype._checkValidIndex = function (index) {
        if (isNaN(index) || index < 0 || index >= this.numberOfItems) throw "INDEX_SIZE_ERR";
      };

      window.SVGPathSegList.prototype.getItem = function (index) {
        this._checkPathSynchronizedToList();

        this._checkValidIndex(index);

        return this._list[index];
      };

      window.SVGPathSegList.prototype.insertItemBefore = function (newItem, index) {
        this._checkPathSynchronizedToList(); // Spec: If the index is greater than or equal to numberOfItems, then the new item is appended to the end of the list.


        if (index > this.numberOfItems) index = this.numberOfItems;

        if (newItem._owningPathSegList) {
          // SVG2 spec says to make a copy.
          newItem = newItem.clone();
        }

        this._list.splice(index, 0, newItem);

        newItem._owningPathSegList = this;

        this._writeListToPath();

        return newItem;
      };

      window.SVGPathSegList.prototype.replaceItem = function (newItem, index) {
        this._checkPathSynchronizedToList();

        if (newItem._owningPathSegList) {
          // SVG2 spec says to make a copy.
          newItem = newItem.clone();
        }

        this._checkValidIndex(index);

        this._list[index] = newItem;
        newItem._owningPathSegList = this;

        this._writeListToPath();

        return newItem;
      };

      window.SVGPathSegList.prototype.removeItem = function (index) {
        this._checkPathSynchronizedToList();

        this._checkValidIndex(index);

        var item = this._list[index];

        this._list.splice(index, 1);

        this._writeListToPath();

        return item;
      };

      window.SVGPathSegList.prototype.appendItem = function (newItem) {
        this._checkPathSynchronizedToList();

        if (newItem._owningPathSegList) {
          // SVG2 spec says to make a copy.
          newItem = newItem.clone();
        }

        this._list.push(newItem);

        newItem._owningPathSegList = this; // TODO: Optimize this to just append to the existing attribute.

        this._writeListToPath();

        return newItem;
      };

      window.SVGPathSegList._pathSegArrayAsString = function (pathSegArray) {
        var string = "";
        var first = true;
        pathSegArray.forEach(function (pathSeg) {
          if (first) {
            first = false;
            string += pathSeg._asPathString();
          } else {
            string += " " + pathSeg._asPathString();
          }
        });
        return string;
      }; // This closely follows SVGPathParser::parsePath from Source/core/svg/SVGPathParser.cpp.


      window.SVGPathSegList.prototype._parsePath = function (string) {
        if (!string || string.length == 0) return [];
        var owningPathSegList = this;

        var Builder = function Builder() {
          this.pathSegList = [];
        };

        Builder.prototype.appendSegment = function (pathSeg) {
          this.pathSegList.push(pathSeg);
        };

        var Source = function Source(string) {
          this._string = string;
          this._currentIndex = 0;
          this._endIndex = this._string.length;
          this._previousCommand = window.SVGPathSeg.PATHSEG_UNKNOWN;

          this._skipOptionalSpaces();
        };

        Source.prototype._isCurrentSpace = function () {
          var character = this._string[this._currentIndex];
          return character <= " " && (character == " " || character == "\n" || character == "\t" || character == "\r" || character == "\f");
        };

        Source.prototype._skipOptionalSpaces = function () {
          while (this._currentIndex < this._endIndex && this._isCurrentSpace()) {
            this._currentIndex++;
          }

          return this._currentIndex < this._endIndex;
        };

        Source.prototype._skipOptionalSpacesOrDelimiter = function () {
          if (this._currentIndex < this._endIndex && !this._isCurrentSpace() && this._string.charAt(this._currentIndex) != ",") return false;

          if (this._skipOptionalSpaces()) {
            if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == ",") {
              this._currentIndex++;

              this._skipOptionalSpaces();
            }
          }

          return this._currentIndex < this._endIndex;
        };

        Source.prototype.hasMoreData = function () {
          return this._currentIndex < this._endIndex;
        };

        Source.prototype.peekSegmentType = function () {
          var lookahead = this._string[this._currentIndex];
          return this._pathSegTypeFromChar(lookahead);
        };

        Source.prototype._pathSegTypeFromChar = function (lookahead) {
          switch (lookahead) {
            case "Z":
            case "z":
              return window.SVGPathSeg.PATHSEG_CLOSEPATH;

            case "M":
              return window.SVGPathSeg.PATHSEG_MOVETO_ABS;

            case "m":
              return window.SVGPathSeg.PATHSEG_MOVETO_REL;

            case "L":
              return window.SVGPathSeg.PATHSEG_LINETO_ABS;

            case "l":
              return window.SVGPathSeg.PATHSEG_LINETO_REL;

            case "C":
              return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS;

            case "c":
              return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL;

            case "Q":
              return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS;

            case "q":
              return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL;

            case "A":
              return window.SVGPathSeg.PATHSEG_ARC_ABS;

            case "a":
              return window.SVGPathSeg.PATHSEG_ARC_REL;

            case "H":
              return window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS;

            case "h":
              return window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL;

            case "V":
              return window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS;

            case "v":
              return window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL;

            case "S":
              return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS;

            case "s":
              return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL;

            case "T":
              return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS;

            case "t":
              return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL;

            default:
              return window.SVGPathSeg.PATHSEG_UNKNOWN;
          }
        };

        Source.prototype._nextCommandHelper = function (lookahead, previousCommand) {
          // Check for remaining coordinates in the current command.
          if ((lookahead == "+" || lookahead == "-" || lookahead == "." || lookahead >= "0" && lookahead <= "9") && previousCommand != window.SVGPathSeg.PATHSEG_CLOSEPATH) {
            if (previousCommand == window.SVGPathSeg.PATHSEG_MOVETO_ABS) return window.SVGPathSeg.PATHSEG_LINETO_ABS;
            if (previousCommand == window.SVGPathSeg.PATHSEG_MOVETO_REL) return window.SVGPathSeg.PATHSEG_LINETO_REL;
            return previousCommand;
          }

          return window.SVGPathSeg.PATHSEG_UNKNOWN;
        };

        Source.prototype.initialCommandIsMoveTo = function () {
          // If the path is empty it is still valid, so return true.
          if (!this.hasMoreData()) return true;
          var command = this.peekSegmentType(); // Path must start with moveTo.

          return command == window.SVGPathSeg.PATHSEG_MOVETO_ABS || command == window.SVGPathSeg.PATHSEG_MOVETO_REL;
        }; // Parse a number from an SVG path. This very closely follows genericParseNumber(...) from Source/core/svg/SVGParserUtilities.cpp.
        // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-PathDataBNF


        Source.prototype._parseNumber = function () {
          var exponent = 0;
          var integer = 0;
          var frac = 1;
          var decimal = 0;
          var sign = 1;
          var expsign = 1;
          var startIndex = this._currentIndex;

          this._skipOptionalSpaces(); // Read the sign.


          if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == "+") this._currentIndex++;else if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == "-") {
            this._currentIndex++;
            sign = -1;
          }
          if (this._currentIndex == this._endIndex || (this._string.charAt(this._currentIndex) < "0" || this._string.charAt(this._currentIndex) > "9") && this._string.charAt(this._currentIndex) != ".") // The first character of a number must be one of [0-9+-.].
            return undefined; // Read the integer part, build right-to-left.

          var startIntPartIndex = this._currentIndex;

          while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= "0" && this._string.charAt(this._currentIndex) <= "9") {
            this._currentIndex++;
          } // Advance to first non-digit.


          if (this._currentIndex != startIntPartIndex) {
            var scanIntPartIndex = this._currentIndex - 1;
            var multiplier = 1;

            while (scanIntPartIndex >= startIntPartIndex) {
              integer += multiplier * (this._string.charAt(scanIntPartIndex--) - "0");
              multiplier *= 10;
            }
          } // Read the decimals.


          if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == ".") {
            this._currentIndex++; // There must be a least one digit following the .

            if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < "0" || this._string.charAt(this._currentIndex) > "9") return undefined;

            while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= "0" && this._string.charAt(this._currentIndex) <= "9") {
              frac *= 10;
              decimal += (this._string.charAt(this._currentIndex) - "0") / frac;
              this._currentIndex += 1;
            }
          } // Read the exponent part.


          if (this._currentIndex != startIndex && this._currentIndex + 1 < this._endIndex && (this._string.charAt(this._currentIndex) == "e" || this._string.charAt(this._currentIndex) == "E") && this._string.charAt(this._currentIndex + 1) != "x" && this._string.charAt(this._currentIndex + 1) != "m") {
            this._currentIndex++; // Read the sign of the exponent.

            if (this._string.charAt(this._currentIndex) == "+") {
              this._currentIndex++;
            } else if (this._string.charAt(this._currentIndex) == "-") {
              this._currentIndex++;
              expsign = -1;
            } // There must be an exponent.


            if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < "0" || this._string.charAt(this._currentIndex) > "9") return undefined;

            while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= "0" && this._string.charAt(this._currentIndex) <= "9") {
              exponent *= 10;
              exponent += this._string.charAt(this._currentIndex) - "0";
              this._currentIndex++;
            }
          }

          var number = integer + decimal;
          number *= sign;
          if (exponent) number *= Math.pow(10, expsign * exponent);
          if (startIndex == this._currentIndex) return undefined;

          this._skipOptionalSpacesOrDelimiter();

          return number;
        };

        Source.prototype._parseArcFlag = function () {
          if (this._currentIndex >= this._endIndex) return undefined;
          var flag = false;

          var flagChar = this._string.charAt(this._currentIndex++);

          if (flagChar == "0") flag = false;else if (flagChar == "1") flag = true;else return undefined;

          this._skipOptionalSpacesOrDelimiter();

          return flag;
        };

        Source.prototype.parseSegment = function () {
          var lookahead = this._string[this._currentIndex];

          var command = this._pathSegTypeFromChar(lookahead);

          if (command == window.SVGPathSeg.PATHSEG_UNKNOWN) {
            // Possibly an implicit command. Not allowed if this is the first command.
            if (this._previousCommand == window.SVGPathSeg.PATHSEG_UNKNOWN) return null;
            command = this._nextCommandHelper(lookahead, this._previousCommand);
            if (command == window.SVGPathSeg.PATHSEG_UNKNOWN) return null;
          } else {
            this._currentIndex++;
          }

          this._previousCommand = command;

          switch (command) {
            case window.SVGPathSeg.PATHSEG_MOVETO_REL:
              return new window.SVGPathSegMovetoRel(owningPathSegList, this._parseNumber(), this._parseNumber());

            case window.SVGPathSeg.PATHSEG_MOVETO_ABS:
              return new window.SVGPathSegMovetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber());

            case window.SVGPathSeg.PATHSEG_LINETO_REL:
              return new window.SVGPathSegLinetoRel(owningPathSegList, this._parseNumber(), this._parseNumber());

            case window.SVGPathSeg.PATHSEG_LINETO_ABS:
              return new window.SVGPathSegLinetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber());

            case window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL:
              return new window.SVGPathSegLinetoHorizontalRel(owningPathSegList, this._parseNumber());

            case window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS:
              return new window.SVGPathSegLinetoHorizontalAbs(owningPathSegList, this._parseNumber());

            case window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL:
              return new window.SVGPathSegLinetoVerticalRel(owningPathSegList, this._parseNumber());

            case window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS:
              return new window.SVGPathSegLinetoVerticalAbs(owningPathSegList, this._parseNumber());

            case window.SVGPathSeg.PATHSEG_CLOSEPATH:
              this._skipOptionalSpaces();

              return new window.SVGPathSegClosePath(owningPathSegList);

            case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL:
              var points = {
                x1: this._parseNumber(),
                y1: this._parseNumber(),
                x2: this._parseNumber(),
                y2: this._parseNumber(),
                x: this._parseNumber(),
                y: this._parseNumber()
              };
              return new window.SVGPathSegCurvetoCubicRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2);

            case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS:
              var points = {
                x1: this._parseNumber(),
                y1: this._parseNumber(),
                x2: this._parseNumber(),
                y2: this._parseNumber(),
                x: this._parseNumber(),
                y: this._parseNumber()
              };
              return new window.SVGPathSegCurvetoCubicAbs(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2);

            case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL:
              var points = {
                x2: this._parseNumber(),
                y2: this._parseNumber(),
                x: this._parseNumber(),
                y: this._parseNumber()
              };
              return new window.SVGPathSegCurvetoCubicSmoothRel(owningPathSegList, points.x, points.y, points.x2, points.y2);

            case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS:
              var points = {
                x2: this._parseNumber(),
                y2: this._parseNumber(),
                x: this._parseNumber(),
                y: this._parseNumber()
              };
              return new window.SVGPathSegCurvetoCubicSmoothAbs(owningPathSegList, points.x, points.y, points.x2, points.y2);

            case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL:
              var points = {
                x1: this._parseNumber(),
                y1: this._parseNumber(),
                x: this._parseNumber(),
                y: this._parseNumber()
              };
              return new window.SVGPathSegCurvetoQuadraticRel(owningPathSegList, points.x, points.y, points.x1, points.y1);

            case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS:
              var points = {
                x1: this._parseNumber(),
                y1: this._parseNumber(),
                x: this._parseNumber(),
                y: this._parseNumber()
              };
              return new window.SVGPathSegCurvetoQuadraticAbs(owningPathSegList, points.x, points.y, points.x1, points.y1);

            case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL:
              return new window.SVGPathSegCurvetoQuadraticSmoothRel(owningPathSegList, this._parseNumber(), this._parseNumber());

            case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS:
              return new window.SVGPathSegCurvetoQuadraticSmoothAbs(owningPathSegList, this._parseNumber(), this._parseNumber());

            case window.SVGPathSeg.PATHSEG_ARC_REL:
              var points = {
                x1: this._parseNumber(),
                y1: this._parseNumber(),
                arcAngle: this._parseNumber(),
                arcLarge: this._parseArcFlag(),
                arcSweep: this._parseArcFlag(),
                x: this._parseNumber(),
                y: this._parseNumber()
              };
              return new window.SVGPathSegArcRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep);

            case window.SVGPathSeg.PATHSEG_ARC_ABS:
              var points = {
                x1: this._parseNumber(),
                y1: this._parseNumber(),
                arcAngle: this._parseNumber(),
                arcLarge: this._parseArcFlag(),
                arcSweep: this._parseArcFlag(),
                x: this._parseNumber(),
                y: this._parseNumber()
              };
              return new window.SVGPathSegArcAbs(owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep);

            default:
              throw "Unknown path seg type.";
          }
        };

        var builder = new Builder();
        var source = new Source(string);
        if (!source.initialCommandIsMoveTo()) return [];

        while (source.hasMoreData()) {
          var pathSeg = source.parseSegment();
          if (!pathSeg) return [];
          builder.appendSegment(pathSeg);
        }

        return builder.pathSegList;
      };
    }
  })(); // String.padEnd polyfill for IE11
  //
  // https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd


  if (!String.prototype.padEnd) {
    String.prototype.padEnd = function padEnd(targetLength, padString) {
      targetLength = targetLength >> 0; //floor if number or convert non-number to 0;

      padString = String(typeof padString !== 'undefined' ? padString : ' ');

      if (this.length > targetLength) {
        return String(this);
      } else {
        targetLength = targetLength - this.length;

        if (targetLength > padString.length) {
          padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
        }

        return String(this) + padString.slice(0, targetLength);
      }
    };
  }
  /* jshint ignore:end */

  Chart.prototype.axis = function () {};

  Chart.prototype.axis.labels = function (labels) {
    var $$ = this.internal;

    if (arguments.length) {
      Object.keys(labels).forEach(function (axisId) {
        $$.axis.setLabelText(axisId, labels[axisId]);
      });
      $$.axis.updateLabels();
    } // TODO: return some values?

  };

  Chart.prototype.axis.max = function (max) {
    var $$ = this.internal,
        config = $$.config;

    if (arguments.length) {
      if (_typeof(max) === 'object') {
        if (isValue(max.x)) {
          config.axis_x_max = max.x;
        }

        if (isValue(max.y)) {
          config.axis_y_max = max.y;
        }

        if (isValue(max.y2)) {
          config.axis_y2_max = max.y2;
        }
      } else {
        config.axis_y_max = config.axis_y2_max = max;
      }

      $$.redraw({
        withUpdateOrgXDomain: true,
        withUpdateXDomain: true
      });
    } else {
      return {
        x: config.axis_x_max,
        y: config.axis_y_max,
        y2: config.axis_y2_max
      };
    }
  };

  Chart.prototype.axis.min = function (min) {
    var $$ = this.internal,
        config = $$.config;

    if (arguments.length) {
      if (_typeof(min) === 'object') {
        if (isValue(min.x)) {
          config.axis_x_min = min.x;
        }

        if (isValue(min.y)) {
          config.axis_y_min = min.y;
        }

        if (isValue(min.y2)) {
          config.axis_y2_min = min.y2;
        }
      } else {
        config.axis_y_min = config.axis_y2_min = min;
      }

      $$.redraw({
        withUpdateOrgXDomain: true,
        withUpdateXDomain: true
      });
    } else {
      return {
        x: config.axis_x_min,
        y: config.axis_y_min,
        y2: config.axis_y2_min
      };
    }
  };

  Chart.prototype.axis.range = function (range) {
    if (arguments.length) {
      if (isDefined(range.max)) {
        this.axis.max(range.max);
      }

      if (isDefined(range.min)) {
        this.axis.min(range.min);
      }
    } else {
      return {
        max: this.axis.max(),
        min: this.axis.min()
      };
    }
  };

  Chart.prototype.category = function (i, category) {
    var $$ = this.internal,
        config = $$.config;

    if (arguments.length > 1) {
      config.axis_x_categories[i] = category;
      $$.redraw();
    }

    return config.axis_x_categories[i];
  };

  Chart.prototype.categories = function (categories) {
    var $$ = this.internal,
        config = $$.config;

    if (!arguments.length) {
      return config.axis_x_categories;
    }

    config.axis_x_categories = categories;
    $$.redraw();
    return config.axis_x_categories;
  };

  Chart.prototype.resize = function (size) {
    var $$ = this.internal,
        config = $$.config;
    config.size_width = size ? size.width : null;
    config.size_height = size ? size.height : null;
    this.flush();
  };

  Chart.prototype.flush = function () {
    var $$ = this.internal;
    $$.updateAndRedraw({
      withLegend: true,
      withTransition: false,
      withTransitionForTransform: false
    });
  };

  Chart.prototype.destroy = function () {
    var $$ = this.internal;
    window.clearInterval($$.intervalForObserveInserted);

    if ($$.resizeTimeout !== undefined) {
      window.clearTimeout($$.resizeTimeout);
    }

    if (window.detachEvent) {
      window.detachEvent('onresize', $$.resizeIfElementDisplayed);
    } else if (window.removeEventListener) {
      window.removeEventListener('resize', $$.resizeIfElementDisplayed);
    } else {
      var wrapper = window.onresize; // check if no one else removed our wrapper and remove our resizeFunction from it

      if (wrapper && wrapper.add && wrapper.remove) {
        wrapper.remove($$.resizeFunction);
      }
    } // remove the inner resize functions


    $$.resizeFunction.remove();
    $$.selectChart.classed('c3', false).html(""); // MEMO: this is needed because the reference of some elements will not be released, then memory leak will happen.

    Object.keys($$).forEach(function (key) {
      $$[key] = null;
    });
    return null;
  };

  Chart.prototype.color = function (id) {
    var $$ = this.internal;
    return $$.color(id); // more patterns
  };

  Chart.prototype.data = function (targetIds) {
    var targets = this.internal.data.targets;
    return typeof targetIds === 'undefined' ? targets : targets.filter(function (t) {
      return [].concat(targetIds).indexOf(t.id) >= 0;
    });
  };

  Chart.prototype.data.shown = function (targetIds) {
    return this.internal.filterTargetsToShow(this.data(targetIds));
  };

  Chart.prototype.data.values = function (targetId) {
    var targets,
        values = null;

    if (targetId) {
      targets = this.data(targetId);
      values = targets[0] ? targets[0].values.map(function (d) {
        return d.value;
      }) : null;
    }

    return values;
  };

  Chart.prototype.data.names = function (names) {
    this.internal.clearLegendItemTextBoxCache();
    return this.internal.updateDataAttributes('names', names);
  };

  Chart.prototype.data.colors = function (colors) {
    return this.internal.updateDataAttributes('colors', colors);
  };

  Chart.prototype.data.axes = function (axes) {
    return this.internal.updateDataAttributes('axes', axes);
  };

  Chart.prototype.flow = function (args) {
    var $$ = this.internal,
        targets,
        data,
        notfoundIds = [],
        orgDataCount = $$.getMaxDataCount(),
        dataCount,
        domain,
        baseTarget,
        baseValue,
        length = 0,
        tail = 0,
        diff,
        to;

    if (args.json) {
      data = $$.convertJsonToData(args.json, args.keys);
    } else if (args.rows) {
      data = $$.convertRowsToData(args.rows);
    } else if (args.columns) {
      data = $$.convertColumnsToData(args.columns);
    } else {
      return;
    }

    targets = $$.convertDataToTargets(data, true); // Update/Add data

    $$.data.targets.forEach(function (t) {
      var found = false,
          i,
          j;

      for (i = 0; i < targets.length; i++) {
        if (t.id === targets[i].id) {
          found = true;

          if (t.values[t.values.length - 1]) {
            tail = t.values[t.values.length - 1].index + 1;
          }

          length = targets[i].values.length;

          for (j = 0; j < length; j++) {
            targets[i].values[j].index = tail + j;

            if (!$$.isTimeSeries()) {
              targets[i].values[j].x = tail + j;
            }
          }

          t.values = t.values.concat(targets[i].values);
          targets.splice(i, 1);
          break;
        }
      }

      if (!found) {
        notfoundIds.push(t.id);
      }
    }); // Append null for not found targets

    $$.data.targets.forEach(function (t) {
      var i, j;

      for (i = 0; i < notfoundIds.length; i++) {
        if (t.id === notfoundIds[i]) {
          tail = t.values[t.values.length - 1].index + 1;

          for (j = 0; j < length; j++) {
            t.values.push({
              id: t.id,
              index: tail + j,
              x: $$.isTimeSeries() ? $$.getOtherTargetX(tail + j) : tail + j,
              value: null
            });
          }
        }
      }
    }); // Generate null values for new target

    if ($$.data.targets.length) {
      targets.forEach(function (t) {
        var i,
            missing = [];

        for (i = $$.data.targets[0].values[0].index; i < tail; i++) {
          missing.push({
            id: t.id,
            index: i,
            x: $$.isTimeSeries() ? $$.getOtherTargetX(i) : i,
            value: null
          });
        }

        t.values.forEach(function (v) {
          v.index += tail;

          if (!$$.isTimeSeries()) {
            v.x += tail;
          }
        });
        t.values = missing.concat(t.values);
      });
    }

    $$.data.targets = $$.data.targets.concat(targets); // add remained
    // check data count because behavior needs to change when it's only one

    dataCount = $$.getMaxDataCount();
    baseTarget = $$.data.targets[0];
    baseValue = baseTarget.values[0]; // Update length to flow if needed

    if (isDefined(args.to)) {
      length = 0;
      to = $$.isTimeSeries() ? $$.parseDate(args.to) : args.to;
      baseTarget.values.forEach(function (v) {
        if (v.x < to) {
          length++;
        }
      });
    } else if (isDefined(args.length)) {
      length = args.length;
    } // If only one data, update the domain to flow from left edge of the chart


    if (!orgDataCount) {
      if ($$.isTimeSeries()) {
        if (baseTarget.values.length > 1) {
          diff = baseTarget.values[baseTarget.values.length - 1].x - baseValue.x;
        } else {
          diff = baseValue.x - $$.getXDomain($$.data.targets)[0];
        }
      } else {
        diff = 1;
      }

      domain = [baseValue.x - diff, baseValue.x];
      $$.updateXDomain(null, true, true, false, domain);
    } else if (orgDataCount === 1) {
      if ($$.isTimeSeries()) {
        diff = (baseTarget.values[baseTarget.values.length - 1].x - baseValue.x) / 2;
        domain = [new Date(+baseValue.x - diff), new Date(+baseValue.x + diff)];
        $$.updateXDomain(null, true, true, false, domain);
      }
    } // Set targets


    $$.updateTargets($$.data.targets); // Redraw with new targets

    $$.redraw({
      flow: {
        index: baseValue.index,
        length: length,
        duration: isValue(args.duration) ? args.duration : $$.config.transition_duration,
        done: args.done,
        orgDataCount: orgDataCount
      },
      withLegend: true,
      withTransition: orgDataCount > 1,
      withTrimXDomain: false,
      withUpdateXAxis: true
    });
  };

  ChartInternal.prototype.generateFlow = function (args) {
    var $$ = this,
        config = $$.config,
        d3 = $$.d3;
    return function () {
      var targets = args.targets,
          flow = args.flow,
          drawBar = args.drawBar,
          drawLine = args.drawLine,
          drawArea = args.drawArea,
          cx = args.cx,
          cy = args.cy,
          xv = args.xv,
          xForText = args.xForText,
          yForText = args.yForText,
          duration = args.duration;

      var translateX,
          scaleX = 1,
          transform,
          flowIndex = flow.index,
          flowLength = flow.length,
          flowStart = $$.getValueOnIndex($$.data.targets[0].values, flowIndex),
          flowEnd = $$.getValueOnIndex($$.data.targets[0].values, flowIndex + flowLength),
          orgDomain = $$.x.domain(),
          domain,
          durationForFlow = flow.duration || duration,
          done = flow.done || function () {},
          wait = $$.generateWait();

      var xgrid, xgridLines, mainRegion, mainText, mainBar, mainLine, mainArea, mainCircle; // set flag

      $$.flowing = true; // remove head data after rendered

      $$.data.targets.forEach(function (d) {
        d.values.splice(0, flowLength);
      }); // update x domain to generate axis elements for flow

      domain = $$.updateXDomain(targets, true, true); // update elements related to x scale

      if ($$.updateXGrid) {
        $$.updateXGrid(true);
      }

      xgrid = $$.xgrid || d3.selectAll([]); // xgrid needs to be obtained after updateXGrid

      xgridLines = $$.xgridLines || d3.selectAll([]);
      mainRegion = $$.mainRegion || d3.selectAll([]);
      mainText = $$.mainText || d3.selectAll([]);
      mainBar = $$.mainBar || d3.selectAll([]);
      mainLine = $$.mainLine || d3.selectAll([]);
      mainArea = $$.mainArea || d3.selectAll([]);
      mainCircle = $$.mainCircle || d3.selectAll([]); // generate transform to flow

      if (!flow.orgDataCount) {
        // if empty
        if ($$.data.targets[0].values.length !== 1) {
          translateX = $$.x(orgDomain[0]) - $$.x(domain[0]);
        } else {
          if ($$.isTimeSeries()) {
            flowStart = $$.getValueOnIndex($$.data.targets[0].values, 0);
            flowEnd = $$.getValueOnIndex($$.data.targets[0].values, $$.data.targets[0].values.length - 1);
            translateX = $$.x(flowStart.x) - $$.x(flowEnd.x);
          } else {
            translateX = diffDomain(domain) / 2;
          }
        }
      } else if (flow.orgDataCount === 1 || (flowStart && flowStart.x) === (flowEnd && flowEnd.x)) {
        translateX = $$.x(orgDomain[0]) - $$.x(domain[0]);
      } else {
        if ($$.isTimeSeries()) {
          translateX = $$.x(orgDomain[0]) - $$.x(domain[0]);
        } else {
          translateX = $$.x(flowStart.x) - $$.x(flowEnd.x);
        }
      }

      scaleX = diffDomain(orgDomain) / diffDomain(domain);
      transform = 'translate(' + translateX + ',0) scale(' + scaleX + ',1)';
      $$.hideXGridFocus();
      var flowTransition = d3.transition().ease(d3.easeLinear).duration(durationForFlow);
      wait.add($$.xAxis($$.axes.x, flowTransition));
      wait.add(mainBar.transition(flowTransition).attr('transform', transform));
      wait.add(mainLine.transition(flowTransition).attr('transform', transform));
      wait.add(mainArea.transition(flowTransition).attr('transform', transform));
      wait.add(mainCircle.transition(flowTransition).attr('transform', transform));
      wait.add(mainText.transition(flowTransition).attr('transform', transform));
      wait.add(mainRegion.filter($$.isRegionOnX).transition(flowTransition).attr('transform', transform));
      wait.add(xgrid.transition(flowTransition).attr('transform', transform));
      wait.add(xgridLines.transition(flowTransition).attr('transform', transform));
      wait(function () {
        var i,
            shapes = [],
            texts = []; // remove flowed elements

        if (flowLength) {
          for (i = 0; i < flowLength; i++) {
            shapes.push('.' + CLASS.shape + '-' + (flowIndex + i));
            texts.push('.' + CLASS.text + '-' + (flowIndex + i));
          }

          $$.svg.selectAll('.' + CLASS.shapes).selectAll(shapes).remove();
          $$.svg.selectAll('.' + CLASS.texts).selectAll(texts).remove();
          $$.svg.select('.' + CLASS.xgrid).remove();
        } // draw again for removing flowed elements and reverting attr


        xgrid.attr('transform', null).attr('x1', $$.xgridAttr.x1).attr('x2', $$.xgridAttr.x2).attr('y1', $$.xgridAttr.y1).attr('y2', $$.xgridAttr.y2).style("opacity", $$.xgridAttr.opacity);
        xgridLines.attr('transform', null);
        xgridLines.select('line').attr("x1", config.axis_rotated ? 0 : xv).attr("x2", config.axis_rotated ? $$.width : xv);
        xgridLines.select('text').attr("x", config.axis_rotated ? $$.width : 0).attr("y", xv);
        mainBar.attr('transform', null).attr("d", drawBar);
        mainLine.attr('transform', null).attr("d", drawLine);
        mainArea.attr('transform', null).attr("d", drawArea);
        mainCircle.attr('transform', null).attr("cx", cx).attr("cy", cy);
        mainText.attr('transform', null).attr('x', xForText).attr('y', yForText).style('fill-opacity', $$.opacityForText.bind($$));
        mainRegion.attr('transform', null);
        mainRegion.filter($$.isRegionOnX).attr("x", $$.regionX.bind($$)).attr("width", $$.regionWidth.bind($$)); // callback for end of flow

        done();
        $$.flowing = false;
      });
    };
  };

  Chart.prototype.focus = function (targetIds) {
    var $$ = this.internal,
        candidates;
    targetIds = $$.mapToTargetIds(targetIds);
    candidates = $$.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))), this.revert();
    this.defocus();
    candidates.classed(CLASS.focused, true).classed(CLASS.defocused, false);

    if ($$.hasArcType()) {
      $$.expandArc(targetIds);
    }

    $$.toggleFocusLegend(targetIds, true);
    $$.focusedTargetIds = targetIds;
    $$.defocusedTargetIds = $$.defocusedTargetIds.filter(function (id) {
      return targetIds.indexOf(id) < 0;
    });
  };

  Chart.prototype.defocus = function (targetIds) {
    var $$ = this.internal,
        candidates;
    targetIds = $$.mapToTargetIds(targetIds);
    candidates = $$.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))), candidates.classed(CLASS.focused, false).classed(CLASS.defocused, true);

    if ($$.hasArcType()) {
      $$.unexpandArc(targetIds);
    }

    $$.toggleFocusLegend(targetIds, false);
    $$.focusedTargetIds = $$.focusedTargetIds.filter(function (id) {
      return targetIds.indexOf(id) < 0;
    });
    $$.defocusedTargetIds = targetIds;
  };

  Chart.prototype.revert = function (targetIds) {
    var $$ = this.internal,
        candidates;
    targetIds = $$.mapToTargetIds(targetIds);
    candidates = $$.svg.selectAll($$.selectorTargets(targetIds)); // should be for all targets

    candidates.classed(CLASS.focused, false).classed(CLASS.defocused, false);

    if ($$.hasArcType()) {
      $$.unexpandArc(targetIds);
    }

    if ($$.config.legend_show) {
      $$.showLegend(targetIds.filter($$.isLegendToShow.bind($$)));
      $$.legend.selectAll($$.selectorLegends(targetIds)).filter(function () {
        return $$.d3.select(this).classed(CLASS.legendItemFocused);
      }).classed(CLASS.legendItemFocused, false);
    }

    $$.focusedTargetIds = [];
    $$.defocusedTargetIds = [];
  };

  Chart.prototype.xgrids = function (grids) {
    var $$ = this.internal,
        config = $$.config;

    if (!grids) {
      return config.grid_x_lines;
    }

    config.grid_x_lines = grids;
    $$.redrawWithoutRescale();
    return config.grid_x_lines;
  };

  Chart.prototype.xgrids.add = function (grids) {
    var $$ = this.internal;
    return this.xgrids($$.config.grid_x_lines.concat(grids ? grids : []));
  };

  Chart.prototype.xgrids.remove = function (params) {
    // TODO: multiple
    var $$ = this.internal;
    $$.removeGridLines(params, true);
  };

  Chart.prototype.ygrids = function (grids) {
    var $$ = this.internal,
        config = $$.config;

    if (!grids) {
      return config.grid_y_lines;
    }

    config.grid_y_lines = grids;
    $$.redrawWithoutRescale();
    return config.grid_y_lines;
  };

  Chart.prototype.ygrids.add = function (grids) {
    var $$ = this.internal;
    return this.ygrids($$.config.grid_y_lines.concat(grids ? grids : []));
  };

  Chart.prototype.ygrids.remove = function (params) {
    // TODO: multiple
    var $$ = this.internal;
    $$.removeGridLines(params, false);
  };

  Chart.prototype.groups = function (groups) {
    var $$ = this.internal,
        config = $$.config;

    if (isUndefined(groups)) {
      return config.data_groups;
    }

    config.data_groups = groups;
    $$.redraw();
    return config.data_groups;
  };

  Chart.prototype.legend = function () {};

  Chart.prototype.legend.show = function (targetIds) {
    var $$ = this.internal;
    $$.showLegend($$.mapToTargetIds(targetIds));
    $$.updateAndRedraw({
      withLegend: true
    });
  };

  Chart.prototype.legend.hide = function (targetIds) {
    var $$ = this.internal;
    $$.hideLegend($$.mapToTargetIds(targetIds));
    $$.updateAndRedraw({
      withLegend: false
    });
  };

  Chart.prototype.load = function (args) {
    var $$ = this.internal,
        config = $$.config; // update xs if specified

    if (args.xs) {
      $$.addXs(args.xs);
    } // update names if exists


    if ('names' in args) {
      Chart.prototype.data.names.bind(this)(args.names);
    } // update classes if exists


    if ('classes' in args) {
      Object.keys(args.classes).forEach(function (id) {
        config.data_classes[id] = args.classes[id];
      });
    } // update categories if exists


    if ('categories' in args && $$.isCategorized()) {
      config.axis_x_categories = args.categories;
    } // update axes if exists


    if ('axes' in args) {
      Object.keys(args.axes).forEach(function (id) {
        config.data_axes[id] = args.axes[id];
      });
    } // update colors if exists


    if ('colors' in args) {
      Object.keys(args.colors).forEach(function (id) {
        config.data_colors[id] = args.colors[id];
      });
    } // use cache if exists


    if ('cacheIds' in args && $$.hasCaches(args.cacheIds)) {
      $$.load($$.getCaches(args.cacheIds), args.done);
      return;
    } // unload if needed


    if ('unload' in args) {
      // TODO: do not unload if target will load (included in url/rows/columns)
      $$.unload($$.mapToTargetIds(typeof args.unload === 'boolean' && args.unload ? null : args.unload), function () {
        $$.loadFromArgs(args);
      });
    } else {
      $$.loadFromArgs(args);
    }
  };

  Chart.prototype.unload = function (args) {
    var $$ = this.internal;
    args = args || {};

    if (args instanceof Array) {
      args = {
        ids: args
      };
    } else if (typeof args === 'string') {
      args = {
        ids: [args]
      };
    }

    $$.unload($$.mapToTargetIds(args.ids), function () {
      $$.redraw({
        withUpdateOrgXDomain: true,
        withUpdateXDomain: true,
        withLegend: true
      });

      if (args.done) {
        args.done();
      }
    });
  };

  Chart.prototype.regions = function (regions) {
    var $$ = this.internal,
        config = $$.config;

    if (!regions) {
      return config.regions;
    }

    config.regions = regions;
    $$.redrawWithoutRescale();
    return config.regions;
  };

  Chart.prototype.regions.add = function (regions) {
    var $$ = this.internal,
        config = $$.config;

    if (!regions) {
      return config.regions;
    }

    config.regions = config.regions.concat(regions);
    $$.redrawWithoutRescale();
    return config.regions;
  };

  Chart.prototype.regions.remove = function (options) {
    var $$ = this.internal,
        config = $$.config,
        duration,
        classes,
        regions;
    options = options || {};
    duration = $$.getOption(options, "duration", config.transition_duration);
    classes = $$.getOption(options, "classes", [CLASS.region]);
    regions = $$.main.select('.' + CLASS.regions).selectAll(classes.map(function (c) {
      return '.' + c;
    }));
    (duration ? regions.transition().duration(duration) : regions).style('opacity', 0).remove();
    config.regions = config.regions.filter(function (region) {
      var found = false;

      if (!region['class']) {
        return true;
      }

      region['class'].split(' ').forEach(function (c) {
        if (classes.indexOf(c) >= 0) {
          found = true;
        }
      });
      return !found;
    });
    return config.regions;
  };

  Chart.prototype.selected = function (targetId) {
    var $$ = this.internal,
        d3 = $$.d3;
    return d3.merge($$.main.selectAll('.' + CLASS.shapes + $$.getTargetSelectorSuffix(targetId)).selectAll('.' + CLASS.shape).filter(function () {
      return d3.select(this).classed(CLASS.SELECTED);
    }).map(function (d) {
      return d.map(function (d) {
        var data = d.__data__;
        return data.data ? data.data : data;
      });
    }));
  };

  Chart.prototype.select = function (ids, indices, resetOther) {
    var $$ = this.internal,
        d3 = $$.d3,
        config = $$.config;

    if (!config.data_selection_enabled) {
      return;
    }

    $$.main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) {
      var shape = d3.select(this),
          id = d.data ? d.data.id : d.id,
          toggle = $$.getToggle(this, d).bind($$),
          isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0,
          isTargetIndex = !indices || indices.indexOf(i) >= 0,
          isSelected = shape.classed(CLASS.SELECTED); // line/area selection not supported yet

      if (shape.classed(CLASS.line) || shape.classed(CLASS.area)) {
        return;
      }

      if (isTargetId && isTargetIndex) {
        if (config.data_selection_isselectable(d) && !isSelected) {
          toggle(true, shape.classed(CLASS.SELECTED, true), d, i);
        }
      } else if (isDefined(resetOther) && resetOther) {
        if (isSelected) {
          toggle(false, shape.classed(CLASS.SELECTED, false), d, i);
        }
      }
    });
  };

  Chart.prototype.unselect = function (ids, indices) {
    var $$ = this.internal,
        d3 = $$.d3,
        config = $$.config;

    if (!config.data_selection_enabled) {
      return;
    }

    $$.main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) {
      var shape = d3.select(this),
          id = d.data ? d.data.id : d.id,
          toggle = $$.getToggle(this, d).bind($$),
          isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0,
          isTargetIndex = !indices || indices.indexOf(i) >= 0,
          isSelected = shape.classed(CLASS.SELECTED); // line/area selection not supported yet

      if (shape.classed(CLASS.line) || shape.classed(CLASS.area)) {
        return;
      }

      if (isTargetId && isTargetIndex) {
        if (config.data_selection_isselectable(d)) {
          if (isSelected) {
            toggle(false, shape.classed(CLASS.SELECTED, false), d, i);
          }
        }
      }
    });
  };

  Chart.prototype.show = function (targetIds, options) {
    var $$ = this.internal,
        targets;
    targetIds = $$.mapToTargetIds(targetIds);
    options = options || {};
    $$.removeHiddenTargetIds(targetIds);
    targets = $$.svg.selectAll($$.selectorTargets(targetIds));
    targets.transition().style('display', 'initial', 'important').style('opacity', 1, 'important').call($$.endall, function () {
      targets.style('opacity', null).style('opacity', 1);
    });

    if (options.withLegend) {
      $$.showLegend(targetIds);
    }

    $$.redraw({
      withUpdateOrgXDomain: true,
      withUpdateXDomain: true,
      withLegend: true
    });
  };

  Chart.prototype.hide = function (targetIds, options) {
    var $$ = this.internal,
        targets;
    targetIds = $$.mapToTargetIds(targetIds);
    options = options || {};
    $$.addHiddenTargetIds(targetIds);
    targets = $$.svg.selectAll($$.selectorTargets(targetIds));
    targets.transition().style('opacity', 0, 'important').call($$.endall, function () {
      targets.style('opacity', null).style('opacity', 0);
      targets.style('display', 'none');
    });

    if (options.withLegend) {
      $$.hideLegend(targetIds);
    }

    $$.redraw({
      withUpdateOrgXDomain: true,
      withUpdateXDomain: true,
      withLegend: true
    });
  };

  Chart.prototype.toggle = function (targetIds, options) {
    var that = this,
        $$ = this.internal;
    $$.mapToTargetIds(targetIds).forEach(function (targetId) {
      $$.isTargetToShow(targetId) ? that.hide(targetId, options) : that.show(targetId, options);
    });
  };

  Chart.prototype.tooltip = function () {};

  Chart.prototype.tooltip.show = function (args) {
    var $$ = this.internal,
        targets,
        data,
        mouse = {}; // determine mouse position on the chart

    if (args.mouse) {
      mouse = args.mouse;
    } else {
      // determine focus data
      if (args.data) {
        data = args.data;
      } else if (typeof args.x !== 'undefined') {
        if (args.id) {
          targets = $$.data.targets.filter(function (t) {
            return t.id === args.id;
          });
        } else {
          targets = $$.data.targets;
        }

        data = $$.filterByX(targets, args.x).slice(0, 1)[0];
      }

      mouse = data ? $$.getMousePosition(data) : null;
    } // emulate mouse events to show


    $$.dispatchEvent('mousemove', mouse);
    $$.config.tooltip_onshow.call($$, data);
  };

  Chart.prototype.tooltip.hide = function () {
    // TODO: get target data by checking the state of focus
    this.internal.dispatchEvent('mouseout', 0);
    this.internal.config.tooltip_onhide.call(this);
  };

  Chart.prototype.transform = function (type, targetIds) {
    var $$ = this.internal,
        options = ['pie', 'donut'].indexOf(type) >= 0 ? {
      withTransform: true
    } : null;
    $$.transformTo(targetIds, type, options);
  };

  ChartInternal.prototype.transformTo = function (targetIds, type, optionsForRedraw) {
    var $$ = this,
        withTransitionForAxis = !$$.hasArcType(),
        options = optionsForRedraw || {
      withTransitionForAxis: withTransitionForAxis
    };
    options.withTransitionForTransform = false;
    $$.transiting = false;
    $$.setTargetType(targetIds, type);
    $$.updateTargets($$.data.targets); // this is needed when transforming to arc

    $$.updateAndRedraw(options);
  };

  Chart.prototype.x = function (x) {
    var $$ = this.internal;

    if (arguments.length) {
      $$.updateTargetX($$.data.targets, x);
      $$.redraw({
        withUpdateOrgXDomain: true,
        withUpdateXDomain: true
      });
    }

    return $$.data.xs;
  };

  Chart.prototype.xs = function (xs) {
    var $$ = this.internal;

    if (arguments.length) {
      $$.updateTargetXs($$.data.targets, xs);
      $$.redraw({
        withUpdateOrgXDomain: true,
        withUpdateXDomain: true
      });
    }

    return $$.data.xs;
  };

  Chart.prototype.zoom = function (domain) {
    var $$ = this.internal;

    if (domain) {
      if ($$.isTimeSeries()) {
        domain = domain.map(function (x) {
          return $$.parseDate(x);
        });
      }

      if ($$.config.subchart_show) {
        $$.brush.selectionAsValue(domain, true);
      } else {
        $$.updateXDomain(null, true, false, false, domain);
        $$.redraw({
          withY: $$.config.zoom_rescale,
          withSubchart: false
        });
      }

      $$.config.zoom_onzoom.call(this, $$.x.orgDomain());
      return domain;
    } else {
      return $$.x.domain();
    }
  };

  Chart.prototype.zoom.enable = function (enabled) {
    var $$ = this.internal;
    $$.config.zoom_enabled = enabled;
    $$.updateAndRedraw();
  };

  Chart.prototype.unzoom = function () {
    var $$ = this.internal;

    if ($$.config.subchart_show) {
      $$.brush.clear();
    } else {
      $$.updateXDomain(null, true, false, false, $$.subX.domain());
      $$.redraw({
        withY: $$.config.zoom_rescale,
        withSubchart: false
      });
    }
  };

  Chart.prototype.zoom.max = function (max) {
    var $$ = this.internal,
        config = $$.config,
        d3 = $$.d3;

    if (max === 0 || max) {
      config.zoom_x_max = d3.max([$$.orgXDomain[1], max]);
    } else {
      return config.zoom_x_max;
    }
  };

  Chart.prototype.zoom.min = function (min) {
    var $$ = this.internal,
        config = $$.config,
        d3 = $$.d3;

    if (min === 0 || min) {
      config.zoom_x_min = d3.min([$$.orgXDomain[0], min]);
    } else {
      return config.zoom_x_min;
    }
  };

  Chart.prototype.zoom.range = function (range) {
    if (arguments.length) {
      if (isDefined(range.max)) {
        this.domain.max(range.max);
      }

      if (isDefined(range.min)) {
        this.domain.min(range.min);
      }
    } else {
      return {
        max: this.domain.max(),
        min: this.domain.min()
      };
    }
  };

  ChartInternal.prototype.initPie = function () {
    var $$ = this,
        d3 = $$.d3;
    $$.pie = d3.pie().value(function (d) {
      return d.values.reduce(function (a, b) {
        return a + b.value;
      }, 0);
    });
    var orderFct = $$.getOrderFunction(); // we need to reverse the returned order if asc or desc to have the slice in expected order.

    if (orderFct && ($$.isOrderAsc() || $$.isOrderDesc())) {
      var defaultSort = orderFct;

      orderFct = function orderFct(t1, t2) {
        return defaultSort(t1, t2) * -1;
      };
    }

    $$.pie.sort(orderFct || null);
  };

  ChartInternal.prototype.updateRadius = function () {
    var $$ = this,
        config = $$.config,
        w = config.gauge_width || config.donut_width,
        gaugeArcWidth = $$.filterTargetsToShow($$.data.targets).length * $$.config.gauge_arcs_minWidth;
    $$.radiusExpanded = Math.min($$.arcWidth, $$.arcHeight) / 2 * ($$.hasType('gauge') ? 0.85 : 1);
    $$.radius = $$.radiusExpanded * 0.95;
    $$.innerRadiusRatio = w ? ($$.radius - w) / $$.radius : 0.6;
    $$.innerRadius = $$.hasType('donut') || $$.hasType('gauge') ? $$.radius * $$.innerRadiusRatio : 0;
    $$.gaugeArcWidth = w ? w : gaugeArcWidth <= $$.radius - $$.innerRadius ? $$.radius - $$.innerRadius : gaugeArcWidth <= $$.radius ? gaugeArcWidth : $$.radius;
  };

  ChartInternal.prototype.updateArc = function () {
    var $$ = this;
    $$.svgArc = $$.getSvgArc();
    $$.svgArcExpanded = $$.getSvgArcExpanded();
    $$.svgArcExpandedSub = $$.getSvgArcExpanded(0.98);
  };

  ChartInternal.prototype.updateAngle = function (d) {
    var $$ = this,
        config = $$.config,
        found = false,
        index = 0,
        gMin,
        gMax,
        gTic,
        gValue;

    if (!config) {
      return null;
    }

    $$.pie($$.filterTargetsToShow($$.data.targets)).forEach(function (t) {
      if (!found && t.data.id === d.data.id) {
        found = true;
        d = t;
        d.index = index;
      }

      index++;
    });

    if (isNaN(d.startAngle)) {
      d.startAngle = 0;
    }

    if (isNaN(d.endAngle)) {
      d.endAngle = d.startAngle;
    }

    if ($$.isGaugeType(d.data)) {
      gMin = config.gauge_min;
      gMax = config.gauge_max;
      gTic = Math.PI * (config.gauge_fullCircle ? 2 : 1) / (gMax - gMin);
      gValue = d.value < gMin ? 0 : d.value < gMax ? d.value - gMin : gMax - gMin;
      d.startAngle = config.gauge_startingAngle;
      d.endAngle = d.startAngle + gTic * gValue;
    }

    return found ? d : null;
  };

  ChartInternal.prototype.getSvgArc = function () {
    var $$ = this,
        hasGaugeType = $$.hasType('gauge'),
        singleArcWidth = $$.gaugeArcWidth / $$.filterTargetsToShow($$.data.targets).length,
        arc = $$.d3.arc().outerRadius(function (d) {
      return hasGaugeType ? $$.radius - singleArcWidth * d.index : $$.radius;
    }).innerRadius(function (d) {
      return hasGaugeType ? $$.radius - singleArcWidth * (d.index + 1) : $$.innerRadius;
    }),
        newArc = function newArc(d, withoutUpdate) {
      var updated;

      if (withoutUpdate) {
        return arc(d);
      } // for interpolate


      updated = $$.updateAngle(d);
      return updated ? arc(updated) : "M 0 0";
    }; // TODO: extends all function


    newArc.centroid = arc.centroid;
    return newArc;
  };

  ChartInternal.prototype.getSvgArcExpanded = function (rate) {
    rate = rate || 1;
    var $$ = this,
        hasGaugeType = $$.hasType('gauge'),
        singleArcWidth = $$.gaugeArcWidth / $$.filterTargetsToShow($$.data.targets).length,
        expandWidth = Math.min($$.radiusExpanded * rate - $$.radius, singleArcWidth * 0.8 - (1 - rate) * 100),
        arc = $$.d3.arc().outerRadius(function (d) {
      return hasGaugeType ? $$.radius - singleArcWidth * d.index + expandWidth : $$.radiusExpanded * rate;
    }).innerRadius(function (d) {
      return hasGaugeType ? $$.radius - singleArcWidth * (d.index + 1) : $$.innerRadius;
    });
    return function (d) {
      var updated = $$.updateAngle(d);
      return updated ? arc(updated) : "M 0 0";
    };
  };

  ChartInternal.prototype.getArc = function (d, withoutUpdate, force) {
    return force || this.isArcType(d.data) ? this.svgArc(d, withoutUpdate) : "M 0 0";
  };

  ChartInternal.prototype.transformForArcLabel = function (d) {
    var $$ = this,
        config = $$.config,
        updated = $$.updateAngle(d),
        c,
        x,
        y,
        h,
        ratio,
        translate = "",
        hasGauge = $$.hasType('gauge');

    if (updated && !hasGauge) {
      c = this.svgArc.centroid(updated);
      x = isNaN(c[0]) ? 0 : c[0];
      y = isNaN(c[1]) ? 0 : c[1];
      h = Math.sqrt(x * x + y * y);

      if ($$.hasType('donut') && config.donut_label_ratio) {
        ratio = isFunction(config.donut_label_ratio) ? config.donut_label_ratio(d, $$.radius, h) : config.donut_label_ratio;
      } else if ($$.hasType('pie') && config.pie_label_ratio) {
        ratio = isFunction(config.pie_label_ratio) ? config.pie_label_ratio(d, $$.radius, h) : config.pie_label_ratio;
      } else {
        ratio = $$.radius && h ? (36 / $$.radius > 0.375 ? 1.175 - 36 / $$.radius : 0.8) * $$.radius / h : 0;
      }

      translate = "translate(" + x * ratio + ',' + y * ratio + ")";
    } else if (updated && hasGauge && $$.filterTargetsToShow($$.data.targets).length > 1) {
      var y1 = Math.sin(updated.endAngle - Math.PI / 2);
      x = Math.cos(updated.endAngle - Math.PI / 2) * ($$.radiusExpanded + 25);
      y = y1 * ($$.radiusExpanded + 15 - Math.abs(y1 * 10)) + 3;
      translate = "translate(" + x + ',' + y + ")";
    }

    return translate;
  };

  ChartInternal.prototype.getArcRatio = function (d) {
    var $$ = this,
        config = $$.config,
        whole = Math.PI * ($$.hasType('gauge') && !config.gauge_fullCircle ? 1 : 2);
    return d ? (d.endAngle - d.startAngle) / whole : null;
  };

  ChartInternal.prototype.convertToArcData = function (d) {
    return this.addName({
      id: d.data.id,
      value: d.value,
      ratio: this.getArcRatio(d),
      index: d.index
    });
  };

  ChartInternal.prototype.textForArcLabel = function (d) {
    var $$ = this,
        updated,
        value,
        ratio,
        id,
        format;

    if (!$$.shouldShowArcLabel()) {
      return "";
    }

    updated = $$.updateAngle(d);
    value = updated ? updated.value : null;
    ratio = $$.getArcRatio(updated);
    id = d.data.id;

    if (!$$.hasType('gauge') && !$$.meetsArcLabelThreshold(ratio)) {
      return "";
    }

    format = $$.getArcLabelFormat();
    return format ? format(value, ratio, id) : $$.defaultArcValueFormat(value, ratio);
  };

  ChartInternal.prototype.textForGaugeMinMax = function (value, isMax) {
    var $$ = this,
        format = $$.getGaugeLabelExtents();
    return format ? format(value, isMax) : value;
  };

  ChartInternal.prototype.expandArc = function (targetIds) {
    var $$ = this,
        interval; // MEMO: avoid to cancel transition

    if ($$.transiting) {
      interval = window.setInterval(function () {
        if (!$$.transiting) {
          window.clearInterval(interval);

          if ($$.legend.selectAll('.c3-legend-item-focused').size() > 0) {
            $$.expandArc(targetIds);
          }
        }
      }, 10);
      return;
    }

    targetIds = $$.mapToTargetIds(targetIds);
    $$.svg.selectAll($$.selectorTargets(targetIds, '.' + CLASS.chartArc)).each(function (d) {
      if (!$$.shouldExpand(d.data.id)) {
        return;
      }

      $$.d3.select(this).selectAll('path').transition().duration($$.expandDuration(d.data.id)).attr("d", $$.svgArcExpanded).transition().duration($$.expandDuration(d.data.id) * 2).attr("d", $$.svgArcExpandedSub).each(function (d) {
        if ($$.isDonutType(d.data)) ;
      });
    });
  };

  ChartInternal.prototype.unexpandArc = function (targetIds) {
    var $$ = this;

    if ($$.transiting) {
      return;
    }

    targetIds = $$.mapToTargetIds(targetIds);
    $$.svg.selectAll($$.selectorTargets(targetIds, '.' + CLASS.chartArc)).selectAll('path').transition().duration(function (d) {
      return $$.expandDuration(d.data.id);
    }).attr("d", $$.svgArc);
    $$.svg.selectAll('.' + CLASS.arc);
  };

  ChartInternal.prototype.expandDuration = function (id) {
    var $$ = this,
        config = $$.config;

    if ($$.isDonutType(id)) {
      return config.donut_expand_duration;
    } else if ($$.isGaugeType(id)) {
      return config.gauge_expand_duration;
    } else if ($$.isPieType(id)) {
      return config.pie_expand_duration;
    } else {
      return 50;
    }
  };

  ChartInternal.prototype.shouldExpand = function (id) {
    var $$ = this,
        config = $$.config;
    return $$.isDonutType(id) && config.donut_expand || $$.isGaugeType(id) && config.gauge_expand || $$.isPieType(id) && config.pie_expand;
  };

  ChartInternal.prototype.shouldShowArcLabel = function () {
    var $$ = this,
        config = $$.config,
        shouldShow = true;

    if ($$.hasType('donut')) {
      shouldShow = config.donut_label_show;
    } else if ($$.hasType('pie')) {
      shouldShow = config.pie_label_show;
    } // when gauge, always true


    return shouldShow;
  };

  ChartInternal.prototype.meetsArcLabelThreshold = function (ratio) {
    var $$ = this,
        config = $$.config,
        threshold = $$.hasType('donut') ? config.donut_label_threshold : config.pie_label_threshold;
    return ratio >= threshold;
  };

  ChartInternal.prototype.getArcLabelFormat = function () {
    var $$ = this,
        config = $$.config,
        format = config.pie_label_format;

    if ($$.hasType('gauge')) {
      format = config.gauge_label_format;
    } else if ($$.hasType('donut')) {
      format = config.donut_label_format;
    }

    return format;
  };

  ChartInternal.prototype.getGaugeLabelExtents = function () {
    var $$ = this,
        config = $$.config;
    return config.gauge_label_extents;
  };

  ChartInternal.prototype.getArcTitle = function () {
    var $$ = this;
    return $$.hasType('donut') ? $$.config.donut_title : "";
  };

  ChartInternal.prototype.updateTargetsForArc = function (targets) {
    var $$ = this,
        main = $$.main,
        mainPies,
        mainPieEnter,
        classChartArc = $$.classChartArc.bind($$),
        classArcs = $$.classArcs.bind($$),
        classFocus = $$.classFocus.bind($$);
    mainPies = main.select('.' + CLASS.chartArcs).selectAll('.' + CLASS.chartArc).data($$.pie(targets)).attr("class", function (d) {
      return classChartArc(d) + classFocus(d.data);
    });
    mainPieEnter = mainPies.enter().append("g").attr("class", classChartArc);
    mainPieEnter.append('g').attr('class', classArcs);
    mainPieEnter.append("text").attr("dy", $$.hasType('gauge') ? "-.1em" : ".35em").style("opacity", 0).style("text-anchor", "middle").style("pointer-events", "none"); // MEMO: can not keep same color..., but not bad to update color in redraw
    //mainPieUpdate.exit().remove();
  };

  ChartInternal.prototype.initArc = function () {
    var $$ = this;
    $$.arcs = $$.main.select('.' + CLASS.chart).append("g").attr("class", CLASS.chartArcs).attr("transform", $$.getTranslate('arc'));
    $$.arcs.append('text').attr('class', CLASS.chartArcsTitle).style("text-anchor", "middle").text($$.getArcTitle());
  };

  ChartInternal.prototype.redrawArc = function (duration, durationForExit, withTransform) {
    var $$ = this,
        d3 = $$.d3,
        config = $$.config,
        main = $$.main,
        arcs,
        mainArc,
        arcLabelLines,
        mainArcLabelLine,
        hasGaugeType = $$.hasType('gauge');
    arcs = main.selectAll('.' + CLASS.arcs).selectAll('.' + CLASS.arc).data($$.arcData.bind($$));
    mainArc = arcs.enter().append('path').attr("class", $$.classArc.bind($$)).style("fill", function (d) {
      return $$.color(d.data);
    }).style("cursor", function (d) {
      return config.interaction_enabled && config.data_selection_isselectable(d) ? "pointer" : null;
    }).each(function (d) {
      if ($$.isGaugeType(d.data)) {
        d.startAngle = d.endAngle = config.gauge_startingAngle;
      }

      this._current = d;
    }).merge(arcs);

    if (hasGaugeType) {
      arcLabelLines = main.selectAll('.' + CLASS.arcs).selectAll('.' + CLASS.arcLabelLine).data($$.arcData.bind($$));
      mainArcLabelLine = arcLabelLines.enter().append('rect').attr("class", function (d) {
        return CLASS.arcLabelLine + ' ' + CLASS.target + ' ' + CLASS.target + '-' + d.data.id;
      }).merge(arcLabelLines);

      if ($$.filterTargetsToShow($$.data.targets).length === 1) {
        mainArcLabelLine.style("display", "none");
      } else {
        mainArcLabelLine.style("fill", function (d) {
          return config.color_pattern.length > 0 ? $$.levelColor(d.data.values[0].value) : $$.color(d.data);
        }).style("display", config.gauge_labelLine_show ? "" : "none").each(function (d) {
          var lineLength = 0,
              lineThickness = 2,
              x = 0,
              y = 0,
              transform = "";

          if ($$.hiddenTargetIds.indexOf(d.data.id) < 0) {
            var updated = $$.updateAngle(d),
                innerLineLength = $$.gaugeArcWidth / $$.filterTargetsToShow($$.data.targets).length * (updated.index + 1),
                lineAngle = updated.endAngle - Math.PI / 2,
                arcInnerRadius = $$.radius - innerLineLength,
                linePositioningAngle = lineAngle - (arcInnerRadius === 0 ? 0 : 1 / arcInnerRadius);
            lineLength = $$.radiusExpanded - $$.radius + innerLineLength;
            x = Math.cos(linePositioningAngle) * arcInnerRadius;
            y = Math.sin(linePositioningAngle) * arcInnerRadius;
            transform = "rotate(" + lineAngle * 180 / Math.PI + ", " + x + ", " + y + ")";
          }

          d3.select(this).attr('x', x).attr('y', y).attr('width', lineLength).attr('height', lineThickness).attr('transform', transform).style("stroke-dasharray", "0, " + (lineLength + lineThickness) + ", 0");
        });
      }
    }

    mainArc.attr("transform", function (d) {
      return !$$.isGaugeType(d.data) && withTransform ? "scale(0)" : "";
    }).on('mouseover', config.interaction_enabled ? function (d) {
      var updated, arcData;

      if ($$.transiting) {
        // skip while transiting
        return;
      }

      updated = $$.updateAngle(d);

      if (updated) {
        arcData = $$.convertToArcData(updated); // transitions

        $$.expandArc(updated.data.id);
        $$.api.focus(updated.data.id);
        $$.toggleFocusLegend(updated.data.id, true);
        $$.config.data_onmouseover(arcData, this);
      }
    } : null).on('mousemove', config.interaction_enabled ? function (d) {
      var updated = $$.updateAngle(d),
          arcData,
          selectedData;

      if (updated) {
        arcData = $$.convertToArcData(updated), selectedData = [arcData];
        $$.showTooltip(selectedData, this);
      }
    } : null).on('mouseout', config.interaction_enabled ? function (d) {
      var updated, arcData;

      if ($$.transiting) {
        // skip while transiting
        return;
      }

      updated = $$.updateAngle(d);

      if (updated) {
        arcData = $$.convertToArcData(updated); // transitions

        $$.unexpandArc(updated.data.id);
        $$.api.revert();
        $$.revertLegend();
        $$.hideTooltip();
        $$.config.data_onmouseout(arcData, this);
      }
    } : null).on('click', config.interaction_enabled ? function (d, i) {
      var updated = $$.updateAngle(d),
          arcData;

      if (updated) {
        arcData = $$.convertToArcData(updated);

        if ($$.toggleShape) {
          $$.toggleShape(this, arcData, i);
        }

        $$.config.data_onclick.call($$.api, arcData, this);
      }
    } : null).each(function () {
      $$.transiting = true;
    }).transition().duration(duration).attrTween("d", function (d) {
      var updated = $$.updateAngle(d),
          interpolate;

      if (!updated) {
        return function () {
          return "M 0 0";
        };
      } //                if (this._current === d) {
      //                    this._current = {
      //                        startAngle: Math.PI*2,
      //                        endAngle: Math.PI*2,
      //                    };
      //                }


      if (isNaN(this._current.startAngle)) {
        this._current.startAngle = 0;
      }

      if (isNaN(this._current.endAngle)) {
        this._current.endAngle = this._current.startAngle;
      }

      interpolate = d3.interpolate(this._current, updated);
      this._current = interpolate(0);
      return function (t) {
        var interpolated = interpolate(t);
        interpolated.data = d.data; // data.id will be updated by interporator

        return $$.getArc(interpolated, true);
      };
    }).attr("transform", withTransform ? "scale(1)" : "").style("fill", function (d) {
      return $$.levelColor ? $$.levelColor(d.data.values[0].value) : $$.color(d.data.id);
    }) // Where gauge reading color would receive customization.
    .call($$.endall, function () {
      $$.transiting = false;
    });
    arcs.exit().transition().duration(durationForExit).style('opacity', 0).remove();
    main.selectAll('.' + CLASS.chartArc).select('text').style("opacity", 0).attr('class', function (d) {
      return $$.isGaugeType(d.data) ? CLASS.gaugeValue : '';
    }).text($$.textForArcLabel.bind($$)).attr("transform", $$.transformForArcLabel.bind($$)).style('font-size', function (d) {
      return $$.isGaugeType(d.data) && $$.filterTargetsToShow($$.data.targets).length === 1 ? Math.round($$.radius / 5) + 'px' : '';
    }).transition().duration(duration).style("opacity", function (d) {
      return $$.isTargetToShow(d.data.id) && $$.isArcType(d.data) ? 1 : 0;
    });
    main.select('.' + CLASS.chartArcsTitle).style("opacity", $$.hasType('donut') || hasGaugeType ? 1 : 0);

    if (hasGaugeType) {
      var index = 0;
      var backgroundArc = $$.arcs.select('g.' + CLASS.chartArcsBackground).selectAll('path.' + CLASS.chartArcsBackground).data($$.data.targets);
      backgroundArc.enter().append("path").attr("class", function (d, i) {
        return CLASS.chartArcsBackground + ' ' + CLASS.chartArcsBackground + '-' + i;
      }).merge(backgroundArc).attr("d", function (d1) {
        if ($$.hiddenTargetIds.indexOf(d1.id) >= 0) {
          return "M 0 0";
        }

        var d = {
          data: [{
            value: config.gauge_max
          }],
          startAngle: config.gauge_startingAngle,
          endAngle: -1 * config.gauge_startingAngle * (config.gauge_fullCircle ? Math.PI : 1),
          index: index++
        };
        return $$.getArc(d, true, true);
      });
      backgroundArc.exit().remove();
      $$.arcs.select('.' + CLASS.chartArcsGaugeUnit).attr("dy", ".75em").text(config.gauge_label_show ? config.gauge_units : '');
      $$.arcs.select('.' + CLASS.chartArcsGaugeMin).attr("dx", -1 * ($$.innerRadius + ($$.radius - $$.innerRadius) / (config.gauge_fullCircle ? 1 : 2)) + "px").attr("dy", "1.2em").text(config.gauge_label_show ? $$.textForGaugeMinMax(config.gauge_min, false) : '');
      $$.arcs.select('.' + CLASS.chartArcsGaugeMax).attr("dx", $$.innerRadius + ($$.radius - $$.innerRadius) / (config.gauge_fullCircle ? 1 : 2) + "px").attr("dy", "1.2em").text(config.gauge_label_show ? $$.textForGaugeMinMax(config.gauge_max, true) : '');
    }
  };

  ChartInternal.prototype.initGauge = function () {
    var arcs = this.arcs;

    if (this.hasType('gauge')) {
      arcs.append('g').attr("class", CLASS.chartArcsBackground);
      arcs.append("text").attr("class", CLASS.chartArcsGaugeUnit).style("text-anchor", "middle").style("pointer-events", "none");
      arcs.append("text").attr("class", CLASS.chartArcsGaugeMin).style("text-anchor", "middle").style("pointer-events", "none");
      arcs.append("text").attr("class", CLASS.chartArcsGaugeMax).style("text-anchor", "middle").style("pointer-events", "none");
    }
  };

  ChartInternal.prototype.getGaugeLabelHeight = function () {
    return this.config.gauge_label_show ? 20 : 0;
  };

  ChartInternal.prototype.hasCaches = function (ids) {
    for (var i = 0; i < ids.length; i++) {
      if (!(ids[i] in this.cache)) {
        return false;
      }
    }

    return true;
  };

  ChartInternal.prototype.addCache = function (id, target) {
    this.cache[id] = this.cloneTarget(target);
  };

  ChartInternal.prototype.getCaches = function (ids) {
    var targets = [],
        i;

    for (i = 0; i < ids.length; i++) {
      if (ids[i] in this.cache) {
        targets.push(this.cloneTarget(this.cache[ids[i]]));
      }
    }

    return targets;
  };

  ChartInternal.prototype.categoryName = function (i) {
    var config = this.config;
    return i < config.axis_x_categories.length ? config.axis_x_categories[i] : i;
  };

  ChartInternal.prototype.generateTargetClass = function (targetId) {
    return targetId || targetId === 0 ? ('-' + targetId).replace(/\s/g, '-') : '';
  };

  ChartInternal.prototype.generateClass = function (prefix, targetId) {
    return " " + prefix + " " + prefix + this.generateTargetClass(targetId);
  };

  ChartInternal.prototype.classText = function (d) {
    return this.generateClass(CLASS.text, d.index);
  };

  ChartInternal.prototype.classTexts = function (d) {
    return this.generateClass(CLASS.texts, d.id);
  };

  ChartInternal.prototype.classShape = function (d) {
    return this.generateClass(CLASS.shape, d.index);
  };

  ChartInternal.prototype.classShapes = function (d) {
    return this.generateClass(CLASS.shapes, d.id);
  };

  ChartInternal.prototype.classLine = function (d) {
    return this.classShape(d) + this.generateClass(CLASS.line, d.id);
  };

  ChartInternal.prototype.classLines = function (d) {
    return this.classShapes(d) + this.generateClass(CLASS.lines, d.id);
  };

  ChartInternal.prototype.classCircle = function (d) {
    return this.classShape(d) + this.generateClass(CLASS.circle, d.index);
  };

  ChartInternal.prototype.classCircles = function (d) {
    return this.classShapes(d) + this.generateClass(CLASS.circles, d.id);
  };

  ChartInternal.prototype.classBar = function (d) {
    return this.classShape(d) + this.generateClass(CLASS.bar, d.index);
  };

  ChartInternal.prototype.classBars = function (d) {
    return this.classShapes(d) + this.generateClass(CLASS.bars, d.id);
  };

  ChartInternal.prototype.classArc = function (d) {
    return this.classShape(d.data) + this.generateClass(CLASS.arc, d.data.id);
  };

  ChartInternal.prototype.classArcs = function (d) {
    return this.classShapes(d.data) + this.generateClass(CLASS.arcs, d.data.id);
  };

  ChartInternal.prototype.classArea = function (d) {
    return this.classShape(d) + this.generateClass(CLASS.area, d.id);
  };

  ChartInternal.prototype.classAreas = function (d) {
    return this.classShapes(d) + this.generateClass(CLASS.areas, d.id);
  };

  ChartInternal.prototype.classRegion = function (d, i) {
    return this.generateClass(CLASS.region, i) + ' ' + ('class' in d ? d['class'] : '');
  };

  ChartInternal.prototype.classEvent = function (d) {
    return this.generateClass(CLASS.eventRect, d.index);
  };

  ChartInternal.prototype.classTarget = function (id) {
    var $$ = this;
    var additionalClassSuffix = $$.config.data_classes[id],
        additionalClass = '';

    if (additionalClassSuffix) {
      additionalClass = ' ' + CLASS.target + '-' + additionalClassSuffix;
    }

    return $$.generateClass(CLASS.target, id) + additionalClass;
  };

  ChartInternal.prototype.classFocus = function (d) {
    return this.classFocused(d) + this.classDefocused(d);
  };

  ChartInternal.prototype.classFocused = function (d) {
    return ' ' + (this.focusedTargetIds.indexOf(d.id) >= 0 ? CLASS.focused : '');
  };

  ChartInternal.prototype.classDefocused = function (d) {
    return ' ' + (this.defocusedTargetIds.indexOf(d.id) >= 0 ? CLASS.defocused : '');
  };

  ChartInternal.prototype.classChartText = function (d) {
    return CLASS.chartText + this.classTarget(d.id);
  };

  ChartInternal.prototype.classChartLine = function (d) {
    return CLASS.chartLine + this.classTarget(d.id);
  };

  ChartInternal.prototype.classChartBar = function (d) {
    return CLASS.chartBar + this.classTarget(d.id);
  };

  ChartInternal.prototype.classChartArc = function (d) {
    return CLASS.chartArc + this.classTarget(d.data.id);
  };

  ChartInternal.prototype.getTargetSelectorSuffix = function (targetId) {
    return this.generateTargetClass(targetId).replace(/([?!@#$%^&*()_=+,.<>'":;\[\]\/|~`{}\\])/g, '\\$1');
  };

  ChartInternal.prototype.selectorTarget = function (id, prefix) {
    return (prefix || '') + '.' + CLASS.target + this.getTargetSelectorSuffix(id);
  };

  ChartInternal.prototype.selectorTargets = function (ids, prefix) {
    var $$ = this;
    ids = ids || [];
    return ids.length ? ids.map(function (id) {
      return $$.selectorTarget(id, prefix);
    }) : null;
  };

  ChartInternal.prototype.selectorLegend = function (id) {
    return '.' + CLASS.legendItem + this.getTargetSelectorSuffix(id);
  };

  ChartInternal.prototype.selectorLegends = function (ids) {
    var $$ = this;
    return ids && ids.length ? ids.map(function (id) {
      return $$.selectorLegend(id);
    }) : null;
  };

  ChartInternal.prototype.getClipPath = function (id) {
    var isIE9 = window.navigator.appVersion.toLowerCase().indexOf("msie 9.") >= 0;
    return "url(" + (isIE9 ? "" : document.URL.split('#')[0]) + "#" + id + ")";
  };

  ChartInternal.prototype.appendClip = function (parent, id) {
    return parent.append("clipPath").attr("id", id).append("rect");
  };

  ChartInternal.prototype.getAxisClipX = function (forHorizontal) {
    // axis line width + padding for left
    var left = Math.max(30, this.margin.left);
    return forHorizontal ? -(1 + left) : -(left - 1);
  };

  ChartInternal.prototype.getAxisClipY = function (forHorizontal) {
    return forHorizontal ? -20 : -this.margin.top;
  };

  ChartInternal.prototype.getXAxisClipX = function () {
    var $$ = this;
    return $$.getAxisClipX(!$$.config.axis_rotated);
  };

  ChartInternal.prototype.getXAxisClipY = function () {
    var $$ = this;
    return $$.getAxisClipY(!$$.config.axis_rotated);
  };

  ChartInternal.prototype.getYAxisClipX = function () {
    var $$ = this;
    return $$.config.axis_y_inner ? -1 : $$.getAxisClipX($$.config.axis_rotated);
  };

  ChartInternal.prototype.getYAxisClipY = function () {
    var $$ = this;
    return $$.getAxisClipY($$.config.axis_rotated);
  };

  ChartInternal.prototype.getAxisClipWidth = function (forHorizontal) {
    var $$ = this,
        left = Math.max(30, $$.margin.left),
        right = Math.max(30, $$.margin.right); // width + axis line width + padding for left/right

    return forHorizontal ? $$.width + 2 + left + right : $$.margin.left + 20;
  };

  ChartInternal.prototype.getAxisClipHeight = function (forHorizontal) {
    // less than 20 is not enough to show the axis label 'outer' without legend
    return (forHorizontal ? this.margin.bottom : this.margin.top + this.height) + 20;
  };

  ChartInternal.prototype.getXAxisClipWidth = function () {
    var $$ = this;
    return $$.getAxisClipWidth(!$$.config.axis_rotated);
  };

  ChartInternal.prototype.getXAxisClipHeight = function () {
    var $$ = this;
    return $$.getAxisClipHeight(!$$.config.axis_rotated);
  };

  ChartInternal.prototype.getYAxisClipWidth = function () {
    var $$ = this;
    return $$.getAxisClipWidth($$.config.axis_rotated) + ($$.config.axis_y_inner ? 20 : 0);
  };

  ChartInternal.prototype.getYAxisClipHeight = function () {
    var $$ = this;
    return $$.getAxisClipHeight($$.config.axis_rotated);
  };

  ChartInternal.prototype.generateColor = function () {
    var $$ = this,
        config = $$.config,
        d3 = $$.d3,
        colors = config.data_colors,
        pattern = notEmpty(config.color_pattern) ? config.color_pattern : d3.schemeCategory10,
        callback = config.data_color,
        ids = [];
    return function (d) {
      var id = d.id || d.data && d.data.id || d,
          color; // if callback function is provided

      if (colors[id] instanceof Function) {
        color = colors[id](d);
      } // if specified, choose that color
      else if (colors[id]) {
          color = colors[id];
        } // if not specified, choose from pattern
        else {
            if (ids.indexOf(id) < 0) {
              ids.push(id);
            }

            color = pattern[ids.indexOf(id) % pattern.length];
            colors[id] = color;
          }

      return callback instanceof Function ? callback(color, d) : color;
    };
  };

  ChartInternal.prototype.generateLevelColor = function () {
    var $$ = this,
        config = $$.config,
        colors = config.color_pattern,
        threshold = config.color_threshold,
        asValue = threshold.unit === 'value',
        values = threshold.values && threshold.values.length ? threshold.values : [],
        max = threshold.max || 100;
    return notEmpty(config.color_threshold) ? function (value) {
      var i,
          v,
          color = colors[colors.length - 1];

      for (i = 0; i < values.length; i++) {
        v = asValue ? value : value * 100 / max;

        if (v < values[i]) {
          color = colors[i];
          break;
        }
      }

      return color;
    } : null;
  };

  ChartInternal.prototype.getDefaultConfig = function () {
    var config = {
      bindto: '#chart',
      svg_classname: undefined,
      size_width: undefined,
      size_height: undefined,
      padding_left: undefined,
      padding_right: undefined,
      padding_top: undefined,
      padding_bottom: undefined,
      resize_auto: true,
      zoom_enabled: false,
      zoom_initialRange: undefined,
      zoom_type: 'scroll',
      zoom_disableDefaultBehavior: false,
      zoom_privileged: false,
      zoom_rescale: false,
      zoom_onzoom: function zoom_onzoom() {},
      zoom_onzoomstart: function zoom_onzoomstart() {},
      zoom_onzoomend: function zoom_onzoomend() {},
      zoom_x_min: undefined,
      zoom_x_max: undefined,
      interaction_brighten: true,
      interaction_enabled: true,
      onmouseover: function onmouseover() {},
      onmouseout: function onmouseout() {},
      onresize: function onresize() {},
      onresized: function onresized() {},
      oninit: function oninit() {},
      onrendered: function onrendered() {},
      transition_duration: 350,
      data_x: undefined,
      data_xs: {},
      data_xFormat: '%Y-%m-%d',
      data_xLocaltime: true,
      data_xSort: true,
      data_idConverter: function data_idConverter(id) {
        return id;
      },
      data_names: {},
      data_classes: {},
      data_groups: [],
      data_axes: {},
      data_type: undefined,
      data_types: {},
      data_labels: {},
      data_order: 'desc',
      data_regions: {},
      data_color: undefined,
      data_colors: {},
      data_hide: false,
      data_filter: undefined,
      data_selection_enabled: false,
      data_selection_grouped: false,
      data_selection_isselectable: function data_selection_isselectable() {
        return true;
      },
      data_selection_multiple: true,
      data_selection_draggable: false,
      data_onclick: function data_onclick() {},
      data_onmouseover: function data_onmouseover() {},
      data_onmouseout: function data_onmouseout() {},
      data_onselected: function data_onselected() {},
      data_onunselected: function data_onunselected() {},
      data_url: undefined,
      data_headers: undefined,
      data_json: undefined,
      data_rows: undefined,
      data_columns: undefined,
      data_mimeType: undefined,
      data_keys: undefined,
      // configuration for no plot-able data supplied.
      data_empty_label_text: "",
      // subchart
      subchart_show: false,
      subchart_size_height: 60,
      subchart_axis_x_show: true,
      subchart_onbrush: function subchart_onbrush() {},
      // color
      color_pattern: [],
      color_threshold: {},
      // legend
      legend_show: true,
      legend_hide: false,
      legend_position: 'bottom',
      legend_inset_anchor: 'top-left',
      legend_inset_x: 10,
      legend_inset_y: 0,
      legend_inset_step: undefined,
      legend_item_onclick: undefined,
      legend_item_onmouseover: undefined,
      legend_item_onmouseout: undefined,
      legend_equally: false,
      legend_padding: 0,
      legend_item_tile_width: 10,
      legend_item_tile_height: 10,
      // axis
      axis_rotated: false,
      axis_x_show: true,
      axis_x_type: 'indexed',
      axis_x_localtime: true,
      axis_x_categories: [],
      axis_x_tick_centered: false,
      axis_x_tick_format: undefined,
      axis_x_tick_culling: {},
      axis_x_tick_culling_max: 10,
      axis_x_tick_count: undefined,
      axis_x_tick_fit: true,
      axis_x_tick_values: null,
      axis_x_tick_rotate: 0,
      axis_x_tick_outer: true,
      axis_x_tick_multiline: true,
      axis_x_tick_multilineMax: 0,
      axis_x_tick_width: null,
      axis_x_max: undefined,
      axis_x_min: undefined,
      axis_x_padding: {},
      axis_x_height: undefined,
      axis_x_selection: undefined,
      axis_x_label: {},
      axis_x_inner: undefined,
      axis_y_show: true,
      axis_y_type: undefined,
      axis_y_max: undefined,
      axis_y_min: undefined,
      axis_y_inverted: false,
      axis_y_center: undefined,
      axis_y_inner: undefined,
      axis_y_label: {},
      axis_y_tick_format: undefined,
      axis_y_tick_outer: true,
      axis_y_tick_values: null,
      axis_y_tick_rotate: 0,
      axis_y_tick_count: undefined,
      axis_y_tick_time_type: undefined,
      axis_y_tick_time_interval: undefined,
      axis_y_padding: {},
      axis_y_default: undefined,
      axis_y2_show: false,
      axis_y2_max: undefined,
      axis_y2_min: undefined,
      axis_y2_inverted: false,
      axis_y2_center: undefined,
      axis_y2_inner: undefined,
      axis_y2_label: {},
      axis_y2_tick_format: undefined,
      axis_y2_tick_outer: true,
      axis_y2_tick_values: null,
      axis_y2_tick_count: undefined,
      axis_y2_padding: {},
      axis_y2_default: undefined,
      // grid
      grid_x_show: false,
      grid_x_type: 'tick',
      grid_x_lines: [],
      grid_y_show: false,
      // not used
      // grid_y_type: 'tick',
      grid_y_lines: [],
      grid_y_ticks: 10,
      grid_focus_show: true,
      grid_lines_front: true,
      // point - point of each data
      point_show: true,
      point_r: 2.5,
      point_sensitivity: 10,
      point_focus_expand_enabled: true,
      point_focus_expand_r: undefined,
      point_select_r: undefined,
      // line
      line_connectNull: false,
      line_step_type: 'step',
      // bar
      bar_width: undefined,
      bar_width_ratio: 0.6,
      bar_width_max: undefined,
      bar_zerobased: true,
      bar_space: 0,
      // area
      area_zerobased: true,
      area_above: false,
      // pie
      pie_label_show: true,
      pie_label_format: undefined,
      pie_label_threshold: 0.05,
      pie_label_ratio: undefined,
      pie_expand: {},
      pie_expand_duration: 50,
      // gauge
      gauge_fullCircle: false,
      gauge_label_show: true,
      gauge_labelLine_show: true,
      gauge_label_format: undefined,
      gauge_min: 0,
      gauge_max: 100,
      gauge_startingAngle: -1 * Math.PI / 2,
      gauge_label_extents: undefined,
      gauge_units: undefined,
      gauge_width: undefined,
      gauge_arcs_minWidth: 5,
      gauge_expand: {},
      gauge_expand_duration: 50,
      // donut
      donut_label_show: true,
      donut_label_format: undefined,
      donut_label_threshold: 0.05,
      donut_label_ratio: undefined,
      donut_width: undefined,
      donut_title: "",
      donut_expand: {},
      donut_expand_duration: 50,
      // spline
      spline_interpolation_type: 'cardinal',
      // region - region to change style
      regions: [],
      // tooltip - show when mouseover on each data
      tooltip_show: true,
      tooltip_grouped: true,
      tooltip_order: undefined,
      tooltip_format_title: undefined,
      tooltip_format_name: undefined,
      tooltip_format_value: undefined,
      tooltip_position: undefined,
      tooltip_contents: function tooltip_contents(d, defaultTitleFormat, defaultValueFormat, color) {
        return this.getTooltipContent ? this.getTooltipContent(d, defaultTitleFormat, defaultValueFormat, color) : '';
      },
      tooltip_init_show: false,
      tooltip_init_x: 0,
      tooltip_init_position: {
        top: '0px',
        left: '50px'
      },
      tooltip_onshow: function tooltip_onshow() {},
      tooltip_onhide: function tooltip_onhide() {},
      // title
      title_text: undefined,
      title_padding: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
      },
      title_position: 'top-center'
    };
    Object.keys(this.additionalConfig).forEach(function (key) {
      config[key] = this.additionalConfig[key];
    }, this);
    return config;
  };

  ChartInternal.prototype.additionalConfig = {};

  ChartInternal.prototype.loadConfig = function (config) {
    var this_config = this.config,
        target,
        keys,
        read;

    function find() {
      var key = keys.shift(); //        console.log("key =>", key, ", target =>", target);

      if (key && target && _typeof(target) === 'object' && key in target) {
        target = target[key];
        return find();
      } else if (!key) {
        return target;
      } else {
        return undefined;
      }
    }

    Object.keys(this_config).forEach(function (key) {
      target = config;
      keys = key.split('_');
      read = find(); //        console.log("CONFIG : ", key, read);

      if (isDefined(read)) {
        this_config[key] = read;
      }
    });
  };

  ChartInternal.prototype.convertUrlToData = function (url, mimeType, headers, keys, done) {
    var $$ = this,
        type = mimeType ? mimeType : 'csv',
        f,
        converter;

    if (type === 'json') {
      f = $$.d3.json;
      converter = $$.convertJsonToData;
    } else if (type === 'tsv') {
      f = $$.d3.tsv;
      converter = $$.convertXsvToData;
    } else {
      f = $$.d3.csv;
      converter = $$.convertXsvToData;
    }

    f(url, headers).then(function (data) {
      done.call($$, converter.call($$, data, keys));
    }).catch(function (error) {
      throw error;
    });
  };

  ChartInternal.prototype.convertXsvToData = function (xsv) {
    var keys = xsv.columns,
        rows = xsv;

    if (rows.length === 0) {
      return {
        keys: keys,
        rows: [keys.reduce(function (row, key) {
          return Object.assign(row, _defineProperty({}, key, null));
        }, {})]
      };
    } else {
      // [].concat() is to convert result into a plain array otherwise
      // test is not happy because rows have properties.
      return {
        keys: keys,
        rows: [].concat(xsv)
      };
    }
  };

  ChartInternal.prototype.convertJsonToData = function (json, keys) {
    var $$ = this,
        new_rows = [],
        targetKeys,
        data;

    if (keys) {
      // when keys specified, json would be an array that includes objects
      if (keys.x) {
        targetKeys = keys.value.concat(keys.x);
        $$.config.data_x = keys.x;
      } else {
        targetKeys = keys.value;
      }

      new_rows.push(targetKeys);
      json.forEach(function (o) {
        var new_row = [];
        targetKeys.forEach(function (key) {
          // convert undefined to null because undefined data will be removed in convertDataToTargets()
          var v = $$.findValueInJson(o, key);

          if (isUndefined(v)) {
            v = null;
          }

          new_row.push(v);
        });
        new_rows.push(new_row);
      });
      data = $$.convertRowsToData(new_rows);
    } else {
      Object.keys(json).forEach(function (key) {
        new_rows.push([key].concat(json[key]));
      });
      data = $$.convertColumnsToData(new_rows);
    }

    return data;
  };

  ChartInternal.prototype.findValueInJson = function (object, path) {
    path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties (replace [] with .)

    path = path.replace(/^\./, ''); // strip a leading dot

    var pathArray = path.split('.');

    for (var i = 0; i < pathArray.length; ++i) {
      var k = pathArray[i];

      if (k in object) {
        object = object[k];
      } else {
        return;
      }
    }

    return object;
  };
  /**
   * Converts the rows to normalized data.
   * @param {any[][]} rows The row data
   * @return {Object}
   */


  ChartInternal.prototype.convertRowsToData = function (rows) {
    var newRows = [];
    var keys = rows[0];

    for (var i = 1; i < rows.length; i++) {
      var newRow = {};

      for (var j = 0; j < rows[i].length; j++) {
        if (isUndefined(rows[i][j])) {
          throw new Error("Source data is missing a component at (" + i + "," + j + ")!");
        }

        newRow[keys[j]] = rows[i][j];
      }

      newRows.push(newRow);
    }

    return {
      keys: keys,
      rows: newRows
    };
  };
  /**
   * Converts the columns to normalized data.
   * @param {any[][]} columns The column data
   * @return {Object}
   */


  ChartInternal.prototype.convertColumnsToData = function (columns) {
    var newRows = [];
    var keys = [];

    for (var i = 0; i < columns.length; i++) {
      var key = columns[i][0];

      for (var j = 1; j < columns[i].length; j++) {
        if (isUndefined(newRows[j - 1])) {
          newRows[j - 1] = {};
        }

        if (isUndefined(columns[i][j])) {
          throw new Error("Source data is missing a component at (" + i + "," + j + ")!");
        }

        newRows[j - 1][key] = columns[i][j];
      }

      keys.push(key);
    }

    return {
      keys: keys,
      rows: newRows
    };
  };
  /**
   * Converts the data format into the target format.
   * @param {!Object} data
   * @param {!Array} data.keys Ordered list of target IDs.
   * @param {!Array} data.rows Rows of data to convert.
   * @param {boolean} appendXs True to append to $$.data.xs, False to replace.
   * @return {!Array}
   */


  ChartInternal.prototype.convertDataToTargets = function (data, appendXs) {
    var $$ = this,
        config = $$.config,
        targets,
        ids,
        xs,
        keys; // handles format where keys are not orderly provided

    if (isArray(data)) {
      keys = Object.keys(data[0]);
    } else {
      keys = data.keys;
      data = data.rows;
    }

    ids = keys.filter($$.isNotX, $$);
    xs = keys.filter($$.isX, $$); // save x for update data by load when custom x and c3.x API

    ids.forEach(function (id) {
      var xKey = $$.getXKey(id);

      if ($$.isCustomX() || $$.isTimeSeries()) {
        // if included in input data
        if (xs.indexOf(xKey) >= 0) {
          $$.data.xs[id] = (appendXs && $$.data.xs[id] ? $$.data.xs[id] : []).concat(data.map(function (d) {
            return d[xKey];
          }).filter(isValue).map(function (rawX, i) {
            return $$.generateTargetX(rawX, id, i);
          }));
        } // if not included in input data, find from preloaded data of other id's x
        else if (config.data_x) {
            $$.data.xs[id] = $$.getOtherTargetXs();
          } // if not included in input data, find from preloaded data
          else if (notEmpty(config.data_xs)) {
              $$.data.xs[id] = $$.getXValuesOfXKey(xKey, $$.data.targets);
            } // MEMO: if no x included, use same x of current will be used

      } else {
        $$.data.xs[id] = data.map(function (d, i) {
          return i;
        });
      }
    }); // check x is defined

    ids.forEach(function (id) {
      if (!$$.data.xs[id]) {
        throw new Error('x is not defined for id = "' + id + '".');
      }
    }); // convert to target

    targets = ids.map(function (id, index) {
      var convertedId = config.data_idConverter(id);
      return {
        id: convertedId,
        id_org: id,
        values: data.map(function (d, i) {
          var xKey = $$.getXKey(id),
              rawX = d[xKey],
              value = d[id] !== null && !isNaN(d[id]) ? +d[id] : null,
              x; // use x as categories if custom x and categorized

          if ($$.isCustomX() && $$.isCategorized() && !isUndefined(rawX)) {
            if (index === 0 && i === 0) {
              config.axis_x_categories = [];
            }

            x = config.axis_x_categories.indexOf(rawX);

            if (x === -1) {
              x = config.axis_x_categories.length;
              config.axis_x_categories.push(rawX);
            }
          } else {
            x = $$.generateTargetX(rawX, id, i);
          } // mark as x = undefined if value is undefined and filter to remove after mapped


          if (isUndefined(d[id]) || $$.data.xs[id].length <= i) {
            x = undefined;
          }

          return {
            x: x,
            value: value,
            id: convertedId
          };
        }).filter(function (v) {
          return isDefined(v.x);
        })
      };
    }); // finish targets

    targets.forEach(function (t) {
      var i; // sort values by its x

      if (config.data_xSort) {
        t.values = t.values.sort(function (v1, v2) {
          var x1 = v1.x || v1.x === 0 ? v1.x : Infinity,
              x2 = v2.x || v2.x === 0 ? v2.x : Infinity;
          return x1 - x2;
        });
      } // indexing each value


      i = 0;
      t.values.forEach(function (v) {
        v.index = i++;
      }); // this needs to be sorted because its index and value.index is identical

      $$.data.xs[t.id].sort(function (v1, v2) {
        return v1 - v2;
      });
    }); // cache information about values

    $$.hasNegativeValue = $$.hasNegativeValueInTargets(targets);
    $$.hasPositiveValue = $$.hasPositiveValueInTargets(targets); // set target types

    if (config.data_type) {
      $$.setTargetType($$.mapToIds(targets).filter(function (id) {
        return !(id in config.data_types);
      }), config.data_type);
    } // cache as original id keyed


    targets.forEach(function (d) {
      $$.addCache(d.id_org, d);
    });
    return targets;
  };

  ChartInternal.prototype.isX = function (key) {
    var $$ = this,
        config = $$.config;
    return config.data_x && key === config.data_x || notEmpty(config.data_xs) && hasValue(config.data_xs, key);
  };

  ChartInternal.prototype.isNotX = function (key) {
    return !this.isX(key);
  };

  ChartInternal.prototype.getXKey = function (id) {
    var $$ = this,
        config = $$.config;
    return config.data_x ? config.data_x : notEmpty(config.data_xs) ? config.data_xs[id] : null;
  };

  ChartInternal.prototype.getXValuesOfXKey = function (key, targets) {
    var $$ = this,
        xValues,
        ids = targets && notEmpty(targets) ? $$.mapToIds(targets) : [];
    ids.forEach(function (id) {
      if ($$.getXKey(id) === key) {
        xValues = $$.data.xs[id];
      }
    });
    return xValues;
  };

  ChartInternal.prototype.getXValue = function (id, i) {
    var $$ = this;
    return id in $$.data.xs && $$.data.xs[id] && isValue($$.data.xs[id][i]) ? $$.data.xs[id][i] : i;
  };

  ChartInternal.prototype.getOtherTargetXs = function () {
    var $$ = this,
        idsForX = Object.keys($$.data.xs);
    return idsForX.length ? $$.data.xs[idsForX[0]] : null;
  };

  ChartInternal.prototype.getOtherTargetX = function (index) {
    var xs = this.getOtherTargetXs();
    return xs && index < xs.length ? xs[index] : null;
  };

  ChartInternal.prototype.addXs = function (xs) {
    var $$ = this;
    Object.keys(xs).forEach(function (id) {
      $$.config.data_xs[id] = xs[id];
    });
  };

  ChartInternal.prototype.addName = function (data) {
    var $$ = this,
        name;

    if (data) {
      name = $$.config.data_names[data.id];
      data.name = name !== undefined ? name : data.id;
    }

    return data;
  };

  ChartInternal.prototype.getValueOnIndex = function (values, index) {
    var valueOnIndex = values.filter(function (v) {
      return v.index === index;
    });
    return valueOnIndex.length ? valueOnIndex[0] : null;
  };

  ChartInternal.prototype.updateTargetX = function (targets, x) {
    var $$ = this;
    targets.forEach(function (t) {
      t.values.forEach(function (v, i) {
        v.x = $$.generateTargetX(x[i], t.id, i);
      });
      $$.data.xs[t.id] = x;
    });
  };

  ChartInternal.prototype.updateTargetXs = function (targets, xs) {
    var $$ = this;
    targets.forEach(function (t) {
      if (xs[t.id]) {
        $$.updateTargetX([t], xs[t.id]);
      }
    });
  };

  ChartInternal.prototype.generateTargetX = function (rawX, id, index) {
    var $$ = this,
        x;

    if ($$.isTimeSeries()) {
      x = rawX ? $$.parseDate(rawX) : $$.parseDate($$.getXValue(id, index));
    } else if ($$.isCustomX() && !$$.isCategorized()) {
      x = isValue(rawX) ? +rawX : $$.getXValue(id, index);
    } else {
      x = index;
    }

    return x;
  };

  ChartInternal.prototype.cloneTarget = function (target) {
    return {
      id: target.id,
      id_org: target.id_org,
      values: target.values.map(function (d) {
        return {
          x: d.x,
          value: d.value,
          id: d.id
        };
      })
    };
  };

  ChartInternal.prototype.getMaxDataCount = function () {
    var $$ = this;
    return $$.d3.max($$.data.targets, function (t) {
      return t.values.length;
    });
  };

  ChartInternal.prototype.mapToIds = function (targets) {
    return targets.map(function (d) {
      return d.id;
    });
  };

  ChartInternal.prototype.mapToTargetIds = function (ids) {
    var $$ = this;
    return ids ? [].concat(ids) : $$.mapToIds($$.data.targets);
  };

  ChartInternal.prototype.hasTarget = function (targets, id) {
    var ids = this.mapToIds(targets),
        i;

    for (i = 0; i < ids.length; i++) {
      if (ids[i] === id) {
        return true;
      }
    }

    return false;
  };

  ChartInternal.prototype.isTargetToShow = function (targetId) {
    return this.hiddenTargetIds.indexOf(targetId) < 0;
  };

  ChartInternal.prototype.isLegendToShow = function (targetId) {
    return this.hiddenLegendIds.indexOf(targetId) < 0;
  };

  ChartInternal.prototype.filterTargetsToShow = function (targets) {
    var $$ = this;
    return targets.filter(function (t) {
      return $$.isTargetToShow(t.id);
    });
  };

  ChartInternal.prototype.mapTargetsToUniqueXs = function (targets) {
    var $$ = this;
    var xs = $$.d3.set($$.d3.merge(targets.map(function (t) {
      return t.values.map(function (v) {
        return +v.x;
      });
    }))).values();
    xs = $$.isTimeSeries() ? xs.map(function (x) {
      return new Date(+x);
    }) : xs.map(function (x) {
      return +x;
    });
    return xs.sort(function (a, b) {
      return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
    });
  };

  ChartInternal.prototype.addHiddenTargetIds = function (targetIds) {
    targetIds = targetIds instanceof Array ? targetIds : new Array(targetIds);

    for (var i = 0; i < targetIds.length; i++) {
      if (this.hiddenTargetIds.indexOf(targetIds[i]) < 0) {
        this.hiddenTargetIds = this.hiddenTargetIds.concat(targetIds[i]);
      }
    }
  };

  ChartInternal.prototype.removeHiddenTargetIds = function (targetIds) {
    this.hiddenTargetIds = this.hiddenTargetIds.filter(function (id) {
      return targetIds.indexOf(id) < 0;
    });
  };

  ChartInternal.prototype.addHiddenLegendIds = function (targetIds) {
    targetIds = targetIds instanceof Array ? targetIds : new Array(targetIds);

    for (var i = 0; i < targetIds.length; i++) {
      if (this.hiddenLegendIds.indexOf(targetIds[i]) < 0) {
        this.hiddenLegendIds = this.hiddenLegendIds.concat(targetIds[i]);
      }
    }
  };

  ChartInternal.prototype.removeHiddenLegendIds = function (targetIds) {
    this.hiddenLegendIds = this.hiddenLegendIds.filter(function (id) {
      return targetIds.indexOf(id) < 0;
    });
  };

  ChartInternal.prototype.getValuesAsIdKeyed = function (targets) {
    var ys = {};
    targets.forEach(function (t) {
      ys[t.id] = [];
      t.values.forEach(function (v) {
        ys[t.id].push(v.value);
      });
    });
    return ys;
  };

  ChartInternal.prototype.checkValueInTargets = function (targets, checker) {
    var ids = Object.keys(targets),
        i,
        j,
        values;

    for (i = 0; i < ids.length; i++) {
      values = targets[ids[i]].values;

      for (j = 0; j < values.length; j++) {
        if (checker(values[j].value)) {
          return true;
        }
      }
    }

    return false;
  };

  ChartInternal.prototype.hasNegativeValueInTargets = function (targets) {
    return this.checkValueInTargets(targets, function (v) {
      return v < 0;
    });
  };

  ChartInternal.prototype.hasPositiveValueInTargets = function (targets) {
    return this.checkValueInTargets(targets, function (v) {
      return v > 0;
    });
  };

  ChartInternal.prototype.isOrderDesc = function () {
    var config = this.config;
    return typeof config.data_order === 'string' && config.data_order.toLowerCase() === 'desc';
  };

  ChartInternal.prototype.isOrderAsc = function () {
    var config = this.config;
    return typeof config.data_order === 'string' && config.data_order.toLowerCase() === 'asc';
  };

  ChartInternal.prototype.getOrderFunction = function () {
    var $$ = this,
        config = $$.config,
        orderAsc = $$.isOrderAsc(),
        orderDesc = $$.isOrderDesc();

    if (orderAsc || orderDesc) {
      var reducer = function reducer(p, c) {
        return p + Math.abs(c.value);
      };

      return function (t1, t2) {
        var t1Sum = t1.values.reduce(reducer, 0),
            t2Sum = t2.values.reduce(reducer, 0);
        return orderAsc ? t2Sum - t1Sum : t1Sum - t2Sum;
      };
    } else if (isFunction(config.data_order)) {
      return config.data_order;
    } else if (isArray(config.data_order)) {
      var order = config.data_order;
      return function (t1, t2) {
        return order.indexOf(t1.id) - order.indexOf(t2.id);
      };
    }
  };

  ChartInternal.prototype.orderTargets = function (targets) {
    var fct = this.getOrderFunction();

    if (fct) {
      targets.sort(fct);
    }

    return targets;
  };

  ChartInternal.prototype.filterByX = function (targets, x) {
    return this.d3.merge(targets.map(function (t) {
      return t.values;
    })).filter(function (v) {
      return v.x - x === 0;
    });
  };

  ChartInternal.prototype.filterRemoveNull = function (data) {
    return data.filter(function (d) {
      return isValue(d.value);
    });
  };

  ChartInternal.prototype.filterByXDomain = function (targets, xDomain) {
    return targets.map(function (t) {
      return {
        id: t.id,
        id_org: t.id_org,
        values: t.values.filter(function (v) {
          return xDomain[0] <= v.x && v.x <= xDomain[1];
        })
      };
    });
  };

  ChartInternal.prototype.hasDataLabel = function () {
    var config = this.config;

    if (typeof config.data_labels === 'boolean' && config.data_labels) {
      return true;
    } else if (_typeof(config.data_labels) === 'object' && notEmpty(config.data_labels)) {
      return true;
    }

    return false;
  };

  ChartInternal.prototype.getDataLabelLength = function (min, max, key) {
    var $$ = this,
        lengths = [0, 0],
        paddingCoef = 1.3;
    $$.selectChart.select('svg').selectAll('.dummy').data([min, max]).enter().append('text').text(function (d) {
      return $$.dataLabelFormat(d.id)(d);
    }).each(function (d, i) {
      lengths[i] = this.getBoundingClientRect()[key] * paddingCoef;
    }).remove();
    return lengths;
  };
  /**
   * Returns true if the given data point is not arc type, otherwise false.
   * @param {Object} d The data point
   * @return {boolean}
   */


  ChartInternal.prototype.isNoneArc = function (d) {
    return this.hasTarget(this.data.targets, d.id);
  };
  /**
   * Returns true if the given data point is arc type, otherwise false.
   * @param {Object} d The data point
   * @return {boolean}
   */


  ChartInternal.prototype.isArc = function (d) {
    return 'data' in d && this.hasTarget(this.data.targets, d.data.id);
  };

  ChartInternal.prototype.findClosestFromTargets = function (targets, pos) {
    var $$ = this,
        candidates; // map to array of closest points of each target

    candidates = targets.map(function (target) {
      return $$.findClosest(target.values, pos);
    }); // decide closest point and return

    return $$.findClosest(candidates, pos);
  };

  ChartInternal.prototype.findClosest = function (values, pos) {
    var $$ = this,
        minDist = $$.config.point_sensitivity,
        closest; // find mouseovering bar

    values.filter(function (v) {
      return v && $$.isBarType(v.id);
    }).forEach(function (v) {
      var shape = $$.main.select('.' + CLASS.bars + $$.getTargetSelectorSuffix(v.id) + ' .' + CLASS.bar + '-' + v.index).node();

      if (!closest && $$.isWithinBar($$.d3.mouse(shape), shape)) {
        closest = v;
      }
    }); // find closest point from non-bar

    values.filter(function (v) {
      return v && !$$.isBarType(v.id);
    }).forEach(function (v) {
      var d = $$.dist(v, pos);

      if (d < minDist) {
        minDist = d;
        closest = v;
      }
    });
    return closest;
  };

  ChartInternal.prototype.dist = function (data, pos) {
    var $$ = this,
        config = $$.config,
        xIndex = config.axis_rotated ? 1 : 0,
        yIndex = config.axis_rotated ? 0 : 1,
        y = $$.circleY(data, data.index),
        x = $$.x(data.x);
    return Math.sqrt(Math.pow(x - pos[xIndex], 2) + Math.pow(y - pos[yIndex], 2));
  };

  ChartInternal.prototype.convertValuesToStep = function (values) {
    var converted = [].concat(values),
        i;

    if (!this.isCategorized()) {
      return values;
    }

    for (i = values.length + 1; 0 < i; i--) {
      converted[i] = converted[i - 1];
    }

    converted[0] = {
      x: converted[0].x - 1,
      value: converted[0].value,
      id: converted[0].id
    };
    converted[values.length + 1] = {
      x: converted[values.length].x + 1,
      value: converted[values.length].value,
      id: converted[values.length].id
    };
    return converted;
  };

  ChartInternal.prototype.updateDataAttributes = function (name, attrs) {
    var $$ = this,
        config = $$.config,
        current = config['data_' + name];

    if (typeof attrs === 'undefined') {
      return current;
    }

    Object.keys(attrs).forEach(function (id) {
      current[id] = attrs[id];
    });
    $$.redraw({
      withLegend: true
    });
    return current;
  };

  ChartInternal.prototype.load = function (targets, args) {
    var $$ = this;

    if (targets) {
      // filter loading targets if needed
      if (args.filter) {
        targets = targets.filter(args.filter);
      } // set type if args.types || args.type specified


      if (args.type || args.types) {
        targets.forEach(function (t) {
          var type = args.types && args.types[t.id] ? args.types[t.id] : args.type;
          $$.setTargetType(t.id, type);
        });
      } // Update/Add data


      $$.data.targets.forEach(function (d) {
        for (var i = 0; i < targets.length; i++) {
          if (d.id === targets[i].id) {
            d.values = targets[i].values;
            targets.splice(i, 1);
            break;
          }
        }
      });
      $$.data.targets = $$.data.targets.concat(targets); // add remained
    } // Set targets


    $$.updateTargets($$.data.targets); // Redraw with new targets

    $$.redraw({
      withUpdateOrgXDomain: true,
      withUpdateXDomain: true,
      withLegend: true
    });

    if (args.done) {
      args.done();
    }
  };

  ChartInternal.prototype.loadFromArgs = function (args) {
    var $$ = this;

    if (args.data) {
      $$.load($$.convertDataToTargets(args.data), args);
    } else if (args.url) {
      $$.convertUrlToData(args.url, args.mimeType, args.headers, args.keys, function (data) {
        $$.load($$.convertDataToTargets(data), args);
      });
    } else if (args.json) {
      $$.load($$.convertDataToTargets($$.convertJsonToData(args.json, args.keys)), args);
    } else if (args.rows) {
      $$.load($$.convertDataToTargets($$.convertRowsToData(args.rows)), args);
    } else if (args.columns) {
      $$.load($$.convertDataToTargets($$.convertColumnsToData(args.columns)), args);
    } else {
      $$.load(null, args);
    }
  };

  ChartInternal.prototype.unload = function (targetIds, done) {
    var $$ = this;

    if (!done) {
      done = function done() {};
    } // filter existing target


    targetIds = targetIds.filter(function (id) {
      return $$.hasTarget($$.data.targets, id);
    }); // If no target, call done and return

    if (!targetIds || targetIds.length === 0) {
      done();
      return;
    }

    $$.svg.selectAll(targetIds.map(function (id) {
      return $$.selectorTarget(id);
    })).transition().style('opacity', 0).remove().call($$.endall, done);
    targetIds.forEach(function (id) {
      // Reset fadein for future load
      $$.withoutFadeIn[id] = false; // Remove target's elements

      if ($$.legend) {
        $$.legend.selectAll('.' + CLASS.legendItem + $$.getTargetSelectorSuffix(id)).remove();
      } // Remove target


      $$.data.targets = $$.data.targets.filter(function (t) {
        return t.id !== id;
      });
    });
  };

  ChartInternal.prototype.getYDomainMin = function (targets) {
    var $$ = this,
        config = $$.config,
        ids = $$.mapToIds(targets),
        ys = $$.getValuesAsIdKeyed(targets),
        j,
        k,
        baseId,
        idsInGroup,
        id,
        hasNegativeValue;

    if (config.data_groups.length > 0) {
      hasNegativeValue = $$.hasNegativeValueInTargets(targets);

      for (j = 0; j < config.data_groups.length; j++) {
        // Determine baseId
        idsInGroup = config.data_groups[j].filter(function (id) {
          return ids.indexOf(id) >= 0;
        });

        if (idsInGroup.length === 0) {
          continue;
        }

        baseId = idsInGroup[0]; // Consider negative values

        if (hasNegativeValue && ys[baseId]) {
          ys[baseId].forEach(function (v, i) {
            ys[baseId][i] = v < 0 ? v : 0;
          });
        } // Compute min


        for (k = 1; k < idsInGroup.length; k++) {
          id = idsInGroup[k];

          if (!ys[id]) {
            continue;
          }

          ys[id].forEach(function (v, i) {
            if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasNegativeValue && +v > 0)) {
              ys[baseId][i] += +v;
            }
          });
        }
      }
    }

    return $$.d3.min(Object.keys(ys).map(function (key) {
      return $$.d3.min(ys[key]);
    }));
  };

  ChartInternal.prototype.getYDomainMax = function (targets) {
    var $$ = this,
        config = $$.config,
        ids = $$.mapToIds(targets),
        ys = $$.getValuesAsIdKeyed(targets),
        j,
        k,
        baseId,
        idsInGroup,
        id,
        hasPositiveValue;

    if (config.data_groups.length > 0) {
      hasPositiveValue = $$.hasPositiveValueInTargets(targets);

      for (j = 0; j < config.data_groups.length; j++) {
        // Determine baseId
        idsInGroup = config.data_groups[j].filter(function (id) {
          return ids.indexOf(id) >= 0;
        });

        if (idsInGroup.length === 0) {
          continue;
        }

        baseId = idsInGroup[0]; // Consider positive values

        if (hasPositiveValue && ys[baseId]) {
          ys[baseId].forEach(function (v, i) {
            ys[baseId][i] = v > 0 ? v : 0;
          });
        } // Compute max


        for (k = 1; k < idsInGroup.length; k++) {
          id = idsInGroup[k];

          if (!ys[id]) {
            continue;
          }

          ys[id].forEach(function (v, i) {
            if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasPositiveValue && +v < 0)) {
              ys[baseId][i] += +v;
            }
          });
        }
      }
    }

    return $$.d3.max(Object.keys(ys).map(function (key) {
      return $$.d3.max(ys[key]);
    }));
  };

  ChartInternal.prototype.getYDomain = function (targets, axisId, xDomain) {
    var $$ = this,
        config = $$.config,
        targetsByAxisId = targets.filter(function (t) {
      return $$.axis.getId(t.id) === axisId;
    }),
        yTargets = xDomain ? $$.filterByXDomain(targetsByAxisId, xDomain) : targetsByAxisId,
        yMin = axisId === 'y2' ? config.axis_y2_min : config.axis_y_min,
        yMax = axisId === 'y2' ? config.axis_y2_max : config.axis_y_max,
        yDomainMin = $$.getYDomainMin(yTargets),
        yDomainMax = $$.getYDomainMax(yTargets),
        domain,
        domainLength,
        padding,
        padding_top,
        padding_bottom,
        center = axisId === 'y2' ? config.axis_y2_center : config.axis_y_center,
        yDomainAbs,
        lengths,
        diff,
        ratio,
        isAllPositive,
        isAllNegative,
        isZeroBased = $$.hasType('bar', yTargets) && config.bar_zerobased || $$.hasType('area', yTargets) && config.area_zerobased,
        isInverted = axisId === 'y2' ? config.axis_y2_inverted : config.axis_y_inverted,
        showHorizontalDataLabel = $$.hasDataLabel() && config.axis_rotated,
        showVerticalDataLabel = $$.hasDataLabel() && !config.axis_rotated; // MEMO: avoid inverting domain unexpectedly

    yDomainMin = isValue(yMin) ? yMin : isValue(yMax) ? yDomainMin < yMax ? yDomainMin : yMax - 10 : yDomainMin;
    yDomainMax = isValue(yMax) ? yMax : isValue(yMin) ? yMin < yDomainMax ? yDomainMax : yMin + 10 : yDomainMax;

    if (yTargets.length === 0) {
      // use current domain if target of axisId is none
      return axisId === 'y2' ? $$.y2.domain() : $$.y.domain();
    }

    if (isNaN(yDomainMin)) {
      // set minimum to zero when not number
      yDomainMin = 0;
    }

    if (isNaN(yDomainMax)) {
      // set maximum to have same value as yDomainMin
      yDomainMax = yDomainMin;
    }

    if (yDomainMin === yDomainMax) {
      yDomainMin < 0 ? yDomainMax = 0 : yDomainMin = 0;
    }

    isAllPositive = yDomainMin >= 0 && yDomainMax >= 0;
    isAllNegative = yDomainMin <= 0 && yDomainMax <= 0; // Cancel zerobased if axis_*_min / axis_*_max specified

    if (isValue(yMin) && isAllPositive || isValue(yMax) && isAllNegative) {
      isZeroBased = false;
    } // Bar/Area chart should be 0-based if all positive|negative


    if (isZeroBased) {
      if (isAllPositive) {
        yDomainMin = 0;
      }

      if (isAllNegative) {
        yDomainMax = 0;
      }
    }

    domainLength = Math.abs(yDomainMax - yDomainMin);
    padding = padding_top = padding_bottom = domainLength * 0.1;

    if (typeof center !== 'undefined') {
      yDomainAbs = Math.max(Math.abs(yDomainMin), Math.abs(yDomainMax));
      yDomainMax = center + yDomainAbs;
      yDomainMin = center - yDomainAbs;
    } // add padding for data label


    if (showHorizontalDataLabel) {
      lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'width');
      diff = diffDomain($$.y.range());
      ratio = [lengths[0] / diff, lengths[1] / diff];
      padding_top += domainLength * (ratio[1] / (1 - ratio[0] - ratio[1]));
      padding_bottom += domainLength * (ratio[0] / (1 - ratio[0] - ratio[1]));
    } else if (showVerticalDataLabel) {
      lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'height');
      padding_top += $$.axis.convertPixelsToAxisPadding(lengths[1], domainLength);
      padding_bottom += $$.axis.convertPixelsToAxisPadding(lengths[0], domainLength);
    }

    if (axisId === 'y' && notEmpty(config.axis_y_padding)) {
      padding_top = $$.axis.getPadding(config.axis_y_padding, 'top', padding_top, domainLength);
      padding_bottom = $$.axis.getPadding(config.axis_y_padding, 'bottom', padding_bottom, domainLength);
    }

    if (axisId === 'y2' && notEmpty(config.axis_y2_padding)) {
      padding_top = $$.axis.getPadding(config.axis_y2_padding, 'top', padding_top, domainLength);
      padding_bottom = $$.axis.getPadding(config.axis_y2_padding, 'bottom', padding_bottom, domainLength);
    } // Bar/Area chart should be 0-based if all positive|negative


    if (isZeroBased) {
      if (isAllPositive) {
        padding_bottom = yDomainMin;
      }

      if (isAllNegative) {
        padding_top = -yDomainMax;
      }
    }

    domain = [yDomainMin - padding_bottom, yDomainMax + padding_top];
    return isInverted ? domain.reverse() : domain;
  };

  ChartInternal.prototype.getXDomainMin = function (targets) {
    var $$ = this,
        config = $$.config;
    return isDefined(config.axis_x_min) ? $$.isTimeSeries() ? this.parseDate(config.axis_x_min) : config.axis_x_min : $$.d3.min(targets, function (t) {
      return $$.d3.min(t.values, function (v) {
        return v.x;
      });
    });
  };

  ChartInternal.prototype.getXDomainMax = function (targets) {
    var $$ = this,
        config = $$.config;
    return isDefined(config.axis_x_max) ? $$.isTimeSeries() ? this.parseDate(config.axis_x_max) : config.axis_x_max : $$.d3.max(targets, function (t) {
      return $$.d3.max(t.values, function (v) {
        return v.x;
      });
    });
  };

  ChartInternal.prototype.getXDomainPadding = function (domain) {
    var $$ = this,
        config = $$.config,
        diff = domain[1] - domain[0],
        maxDataCount,
        padding,
        paddingLeft,
        paddingRight;

    if ($$.isCategorized()) {
      padding = 0;
    } else if ($$.hasType('bar')) {
      maxDataCount = $$.getMaxDataCount();
      padding = maxDataCount > 1 ? diff / (maxDataCount - 1) / 2 : 0.5;
    } else {
      padding = diff * 0.01;
    }

    if (_typeof(config.axis_x_padding) === 'object' && notEmpty(config.axis_x_padding)) {
      paddingLeft = isValue(config.axis_x_padding.left) ? config.axis_x_padding.left : padding;
      paddingRight = isValue(config.axis_x_padding.right) ? config.axis_x_padding.right : padding;
    } else if (typeof config.axis_x_padding === 'number') {
      paddingLeft = paddingRight = config.axis_x_padding;
    } else {
      paddingLeft = paddingRight = padding;
    }

    return {
      left: paddingLeft,
      right: paddingRight
    };
  };

  ChartInternal.prototype.getXDomain = function (targets) {
    var $$ = this,
        xDomain = [$$.getXDomainMin(targets), $$.getXDomainMax(targets)],
        firstX = xDomain[0],
        lastX = xDomain[1],
        padding = $$.getXDomainPadding(xDomain),
        min = 0,
        max = 0; // show center of x domain if min and max are the same

    if (firstX - lastX === 0 && !$$.isCategorized()) {
      if ($$.isTimeSeries()) {
        firstX = new Date(firstX.getTime() * 0.5);
        lastX = new Date(lastX.getTime() * 1.5);
      } else {
        firstX = firstX === 0 ? 1 : firstX * 0.5;
        lastX = lastX === 0 ? -1 : lastX * 1.5;
      }
    }

    if (firstX || firstX === 0) {
      min = $$.isTimeSeries() ? new Date(firstX.getTime() - padding.left) : firstX - padding.left;
    }

    if (lastX || lastX === 0) {
      max = $$.isTimeSeries() ? new Date(lastX.getTime() + padding.right) : lastX + padding.right;
    }

    return [min, max];
  };

  ChartInternal.prototype.updateXDomain = function (targets, withUpdateXDomain, withUpdateOrgXDomain, withTrim, domain) {
    var $$ = this,
        config = $$.config;

    if (withUpdateOrgXDomain) {
      $$.x.domain(domain ? domain : $$.d3.extent($$.getXDomain(targets)));
      $$.orgXDomain = $$.x.domain();

      if (config.zoom_enabled) {
        $$.zoom.update();
      }

      $$.subX.domain($$.x.domain());

      if ($$.brush) {
        $$.brush.updateScale($$.subX);
      }
    }

    if (withUpdateXDomain) {
      $$.x.domain(domain ? domain : !$$.brush || $$.brush.empty() ? $$.orgXDomain : $$.brush.selectionAsValue());
    } // Trim domain when too big by zoom mousemove event


    if (withTrim) {
      $$.x.domain($$.trimXDomain($$.x.orgDomain()));
    }

    return $$.x.domain();
  };

  ChartInternal.prototype.trimXDomain = function (domain) {
    var zoomDomain = this.getZoomDomain(),
        min = zoomDomain[0],
        max = zoomDomain[1];

    if (domain[0] <= min) {
      domain[1] = +domain[1] + (min - domain[0]);
      domain[0] = min;
    }

    if (max <= domain[1]) {
      domain[0] = +domain[0] - (domain[1] - max);
      domain[1] = max;
    }

    return domain;
  };

  ChartInternal.prototype.drag = function (mouse) {
    var $$ = this,
        config = $$.config,
        main = $$.main,
        d3 = $$.d3;
    var sx, sy, mx, my, minX, maxX, minY, maxY;

    if ($$.hasArcType()) {
      return;
    }

    if (!config.data_selection_enabled) {
      return;
    } // do nothing if not selectable


    if (!config.data_selection_multiple) {
      return;
    } // skip when single selection because drag is used for multiple selection


    sx = $$.dragStart[0];
    sy = $$.dragStart[1];
    mx = mouse[0];
    my = mouse[1];
    minX = Math.min(sx, mx);
    maxX = Math.max(sx, mx);
    minY = config.data_selection_grouped ? $$.margin.top : Math.min(sy, my);
    maxY = config.data_selection_grouped ? $$.height : Math.max(sy, my);
    main.select('.' + CLASS.dragarea).attr('x', minX).attr('y', minY).attr('width', maxX - minX).attr('height', maxY - minY); // TODO: binary search when multiple xs

    main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).filter(function (d) {
      return config.data_selection_isselectable(d);
    }).each(function (d, i) {
      var shape = d3.select(this),
          isSelected = shape.classed(CLASS.SELECTED),
          isIncluded = shape.classed(CLASS.INCLUDED),
          _x,
          _y,
          _w,
          _h,
          toggle,
          isWithin = false,
          box;

      if (shape.classed(CLASS.circle)) {
        _x = shape.attr("cx") * 1;
        _y = shape.attr("cy") * 1;
        toggle = $$.togglePoint;
        isWithin = minX < _x && _x < maxX && minY < _y && _y < maxY;
      } else if (shape.classed(CLASS.bar)) {
        box = getPathBox(this);
        _x = box.x;
        _y = box.y;
        _w = box.width;
        _h = box.height;
        toggle = $$.togglePath;
        isWithin = !(maxX < _x || _x + _w < minX) && !(maxY < _y || _y + _h < minY);
      } else {
        // line/area selection not supported yet
        return;
      }

      if (isWithin ^ isIncluded) {
        shape.classed(CLASS.INCLUDED, !isIncluded); // TODO: included/unincluded callback here

        shape.classed(CLASS.SELECTED, !isSelected);
        toggle.call($$, !isSelected, shape, d, i);
      }
    });
  };

  ChartInternal.prototype.dragstart = function (mouse) {
    var $$ = this,
        config = $$.config;

    if ($$.hasArcType()) {
      return;
    }

    if (!config.data_selection_enabled) {
      return;
    } // do nothing if not selectable


    $$.dragStart = mouse;
    $$.main.select('.' + CLASS.chart).append('rect').attr('class', CLASS.dragarea).style('opacity', 0.1);
    $$.dragging = true;
  };

  ChartInternal.prototype.dragend = function () {
    var $$ = this,
        config = $$.config;

    if ($$.hasArcType()) {
      return;
    }

    if (!config.data_selection_enabled) {
      return;
    } // do nothing if not selectable


    $$.main.select('.' + CLASS.dragarea).transition().duration(100).style('opacity', 0).remove();
    $$.main.selectAll('.' + CLASS.shape).classed(CLASS.INCLUDED, false);
    $$.dragging = false;
  };

  ChartInternal.prototype.getYFormat = function (forArc) {
    var $$ = this,
        formatForY = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.yFormat,
        formatForY2 = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.y2Format;
    return function (v, ratio, id) {
      var format = $$.axis.getId(id) === 'y2' ? formatForY2 : formatForY;
      return format.call($$, v, ratio);
    };
  };

  ChartInternal.prototype.yFormat = function (v) {
    var $$ = this,
        config = $$.config,
        format = config.axis_y_tick_format ? config.axis_y_tick_format : $$.defaultValueFormat;
    return format(v);
  };

  ChartInternal.prototype.y2Format = function (v) {
    var $$ = this,
        config = $$.config,
        format = config.axis_y2_tick_format ? config.axis_y2_tick_format : $$.defaultValueFormat;
    return format(v);
  };

  ChartInternal.prototype.defaultValueFormat = function (v) {
    return isValue(v) ? +v : "";
  };

  ChartInternal.prototype.defaultArcValueFormat = function (v, ratio) {
    return (ratio * 100).toFixed(1) + '%';
  };

  ChartInternal.prototype.dataLabelFormat = function (targetId) {
    var $$ = this,
        data_labels = $$.config.data_labels,
        format,
        defaultFormat = function defaultFormat(v) {
      return isValue(v) ? +v : "";
    }; // find format according to axis id


    if (typeof data_labels.format === 'function') {
      format = data_labels.format;
    } else if (_typeof(data_labels.format) === 'object') {
      if (data_labels.format[targetId]) {
        format = data_labels.format[targetId] === true ? defaultFormat : data_labels.format[targetId];
      } else {
        format = function format() {
          return '';
        };
      }
    } else {
      format = defaultFormat;
    }

    return format;
  };

  ChartInternal.prototype.initGrid = function () {
    var $$ = this,
        config = $$.config,
        d3 = $$.d3;
    $$.grid = $$.main.append('g').attr("clip-path", $$.clipPathForGrid).attr('class', CLASS.grid);

    if (config.grid_x_show) {
      $$.grid.append("g").attr("class", CLASS.xgrids);
    }

    if (config.grid_y_show) {
      $$.grid.append('g').attr('class', CLASS.ygrids);
    }

    if (config.grid_focus_show) {
      $$.grid.append('g').attr("class", CLASS.xgridFocus).append('line').attr('class', CLASS.xgridFocus);
    }

    $$.xgrid = d3.selectAll([]);

    if (!config.grid_lines_front) {
      $$.initGridLines();
    }
  };

  ChartInternal.prototype.initGridLines = function () {
    var $$ = this,
        d3 = $$.d3;
    $$.gridLines = $$.main.append('g').attr("clip-path", $$.clipPathForGrid).attr('class', CLASS.grid + ' ' + CLASS.gridLines);
    $$.gridLines.append('g').attr("class", CLASS.xgridLines);
    $$.gridLines.append('g').attr('class', CLASS.ygridLines);
    $$.xgridLines = d3.selectAll([]);
  };

  ChartInternal.prototype.updateXGrid = function (withoutUpdate) {
    var $$ = this,
        config = $$.config,
        d3 = $$.d3,
        xgridData = $$.generateGridData(config.grid_x_type, $$.x),
        tickOffset = $$.isCategorized() ? $$.xAxis.tickOffset() : 0;
    $$.xgridAttr = config.axis_rotated ? {
      'x1': 0,
      'x2': $$.width,
      'y1': function y1(d) {
        return $$.x(d) - tickOffset;
      },
      'y2': function y2(d) {
        return $$.x(d) - tickOffset;
      }
    } : {
      'x1': function x1(d) {
        return $$.x(d) + tickOffset;
      },
      'x2': function x2(d) {
        return $$.x(d) + tickOffset;
      },
      'y1': 0,
      'y2': $$.height
    };

    $$.xgridAttr.opacity = function () {
      var pos = +d3.select(this).attr(config.axis_rotated ? 'y1' : 'x1');
      return pos === (config.axis_rotated ? $$.height : 0) ? 0 : 1;
    };

    var xgrid = $$.main.select('.' + CLASS.xgrids).selectAll('.' + CLASS.xgrid).data(xgridData);
    var xgridEnter = xgrid.enter().append('line').attr("class", CLASS.xgrid).attr('x1', $$.xgridAttr.x1).attr('x2', $$.xgridAttr.x2).attr('y1', $$.xgridAttr.y1).attr('y2', $$.xgridAttr.y2).style("opacity", 0);
    $$.xgrid = xgridEnter.merge(xgrid);

    if (!withoutUpdate) {
      $$.xgrid.attr('x1', $$.xgridAttr.x1).attr('x2', $$.xgridAttr.x2).attr('y1', $$.xgridAttr.y1).attr('y2', $$.xgridAttr.y2).style("opacity", $$.xgridAttr.opacity);
    }

    xgrid.exit().remove();
  };

  ChartInternal.prototype.updateYGrid = function () {
    var $$ = this,
        config = $$.config,
        gridValues = $$.yAxis.tickValues() || $$.y.ticks(config.grid_y_ticks);
    var ygrid = $$.main.select('.' + CLASS.ygrids).selectAll('.' + CLASS.ygrid).data(gridValues);
    var ygridEnter = ygrid.enter().append('line') // TODO: x1, x2, y1, y2, opacity need to be set here maybe
    .attr('class', CLASS.ygrid);
    $$.ygrid = ygridEnter.merge(ygrid);
    $$.ygrid.attr("x1", config.axis_rotated ? $$.y : 0).attr("x2", config.axis_rotated ? $$.y : $$.width).attr("y1", config.axis_rotated ? 0 : $$.y).attr("y2", config.axis_rotated ? $$.height : $$.y);
    ygrid.exit().remove();
    $$.smoothLines($$.ygrid, 'grid');
  };

  ChartInternal.prototype.gridTextAnchor = function (d) {
    return d.position ? d.position : "end";
  };

  ChartInternal.prototype.gridTextDx = function (d) {
    return d.position === 'start' ? 4 : d.position === 'middle' ? 0 : -4;
  };

  ChartInternal.prototype.xGridTextX = function (d) {
    return d.position === 'start' ? -this.height : d.position === 'middle' ? -this.height / 2 : 0;
  };

  ChartInternal.prototype.yGridTextX = function (d) {
    return d.position === 'start' ? 0 : d.position === 'middle' ? this.width / 2 : this.width;
  };

  ChartInternal.prototype.updateGrid = function (duration) {
    var $$ = this,
        main = $$.main,
        config = $$.config,
        xgridLine,
        xgridLineEnter,
        ygridLine,
        ygridLineEnter,
        xv = $$.xv.bind($$),
        yv = $$.yv.bind($$),
        xGridTextX = $$.xGridTextX.bind($$),
        yGridTextX = $$.yGridTextX.bind($$); // hide if arc type

    $$.grid.style('visibility', $$.hasArcType() ? 'hidden' : 'visible');
    main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden");

    if (config.grid_x_show) {
      $$.updateXGrid();
    }

    xgridLine = main.select('.' + CLASS.xgridLines).selectAll('.' + CLASS.xgridLine).data(config.grid_x_lines); // enter

    xgridLineEnter = xgridLine.enter().append('g').attr("class", function (d) {
      return CLASS.xgridLine + (d['class'] ? ' ' + d['class'] : '');
    });
    xgridLineEnter.append('line').attr("x1", config.axis_rotated ? 0 : xv).attr("x2", config.axis_rotated ? $$.width : xv).attr("y1", config.axis_rotated ? xv : 0).attr("y2", config.axis_rotated ? xv : $$.height).style("opacity", 0);
    xgridLineEnter.append('text').attr("text-anchor", $$.gridTextAnchor).attr("transform", config.axis_rotated ? "" : "rotate(-90)").attr("x", config.axis_rotated ? yGridTextX : xGridTextX).attr("y", xv).attr('dx', $$.gridTextDx).attr('dy', -5).style("opacity", 0); // udpate

    $$.xgridLines = xgridLineEnter.merge(xgridLine); // done in d3.transition() of the end of this function
    // exit

    xgridLine.exit().transition().duration(duration).style("opacity", 0).remove(); // Y-Grid

    if (config.grid_y_show) {
      $$.updateYGrid();
    }

    ygridLine = main.select('.' + CLASS.ygridLines).selectAll('.' + CLASS.ygridLine).data(config.grid_y_lines); // enter

    ygridLineEnter = ygridLine.enter().append('g').attr("class", function (d) {
      return CLASS.ygridLine + (d['class'] ? ' ' + d['class'] : '');
    });
    ygridLineEnter.append('line').attr("x1", config.axis_rotated ? yv : 0).attr("x2", config.axis_rotated ? yv : $$.width).attr("y1", config.axis_rotated ? 0 : yv).attr("y2", config.axis_rotated ? $$.height : yv).style("opacity", 0);
    ygridLineEnter.append('text').attr("text-anchor", $$.gridTextAnchor).attr("transform", config.axis_rotated ? "rotate(-90)" : "").attr("x", config.axis_rotated ? xGridTextX : yGridTextX).attr("y", yv).attr('dx', $$.gridTextDx).attr('dy', -5).style("opacity", 0); // update

    $$.ygridLines = ygridLineEnter.merge(ygridLine);
    $$.ygridLines.select('line').transition().duration(duration).attr("x1", config.axis_rotated ? yv : 0).attr("x2", config.axis_rotated ? yv : $$.width).attr("y1", config.axis_rotated ? 0 : yv).attr("y2", config.axis_rotated ? $$.height : yv).style("opacity", 1);
    $$.ygridLines.select('text').transition().duration(duration).attr("x", config.axis_rotated ? $$.xGridTextX.bind($$) : $$.yGridTextX.bind($$)).attr("y", yv).text(function (d) {
      return d.text;
    }).style("opacity", 1); // exit

    ygridLine.exit().transition().duration(duration).style("opacity", 0).remove();
  };

  ChartInternal.prototype.redrawGrid = function (withTransition, transition) {
    var $$ = this,
        config = $$.config,
        xv = $$.xv.bind($$),
        lines = $$.xgridLines.select('line'),
        texts = $$.xgridLines.select('text');
    return [(withTransition ? lines.transition(transition) : lines).attr("x1", config.axis_rotated ? 0 : xv).attr("x2", config.axis_rotated ? $$.width : xv).attr("y1", config.axis_rotated ? xv : 0).attr("y2", config.axis_rotated ? xv : $$.height).style("opacity", 1), (withTransition ? texts.transition(transition) : texts).attr("x", config.axis_rotated ? $$.yGridTextX.bind($$) : $$.xGridTextX.bind($$)).attr("y", xv).text(function (d) {
      return d.text;
    }).style("opacity", 1)];
  };

  ChartInternal.prototype.showXGridFocus = function (selectedData) {
    var $$ = this,
        config = $$.config,
        dataToShow = selectedData.filter(function (d) {
      return d && isValue(d.value);
    }),
        focusEl = $$.main.selectAll('line.' + CLASS.xgridFocus),
        xx = $$.xx.bind($$);

    if (!config.tooltip_show) {
      return;
    } // Hide when scatter plot exists


    if ($$.hasType('scatter') || $$.hasArcType()) {
      return;
    }

    focusEl.style("visibility", "visible").data([dataToShow[0]]).attr(config.axis_rotated ? 'y1' : 'x1', xx).attr(config.axis_rotated ? 'y2' : 'x2', xx);
    $$.smoothLines(focusEl, 'grid');
  };

  ChartInternal.prototype.hideXGridFocus = function () {
    this.main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden");
  };

  ChartInternal.prototype.updateXgridFocus = function () {
    var $$ = this,
        config = $$.config;
    $$.main.select('line.' + CLASS.xgridFocus).attr("x1", config.axis_rotated ? 0 : -10).attr("x2", config.axis_rotated ? $$.width : -10).attr("y1", config.axis_rotated ? -10 : 0).attr("y2", config.axis_rotated ? -10 : $$.height);
  };

  ChartInternal.prototype.generateGridData = function (type, scale) {
    var $$ = this,
        gridData = [],
        xDomain,
        firstYear,
        lastYear,
        i,
        tickNum = $$.main.select("." + CLASS.axisX).selectAll('.tick').size();

    if (type === 'year') {
      xDomain = $$.getXDomain();
      firstYear = xDomain[0].getFullYear();
      lastYear = xDomain[1].getFullYear();

      for (i = firstYear; i <= lastYear; i++) {
        gridData.push(new Date(i + '-01-01 00:00:00'));
      }
    } else {
      gridData = scale.ticks(10);

      if (gridData.length > tickNum) {
        // use only int
        gridData = gridData.filter(function (d) {
          return ("" + d).indexOf('.') < 0;
        });
      }
    }

    return gridData;
  };

  ChartInternal.prototype.getGridFilterToRemove = function (params) {
    return params ? function (line) {
      var found = false;
      [].concat(params).forEach(function (param) {
        if ('value' in param && line.value === param.value || 'class' in param && line['class'] === param['class']) {
          found = true;
        }
      });
      return found;
    } : function () {
      return true;
    };
  };

  ChartInternal.prototype.removeGridLines = function (params, forX) {
    var $$ = this,
        config = $$.config,
        toRemove = $$.getGridFilterToRemove(params),
        toShow = function toShow(line) {
      return !toRemove(line);
    },
        classLines = forX ? CLASS.xgridLines : CLASS.ygridLines,
        classLine = forX ? CLASS.xgridLine : CLASS.ygridLine;

    $$.main.select('.' + classLines).selectAll('.' + classLine).filter(toRemove).transition().duration(config.transition_duration).style('opacity', 0).remove();

    if (forX) {
      config.grid_x_lines = config.grid_x_lines.filter(toShow);
    } else {
      config.grid_y_lines = config.grid_y_lines.filter(toShow);
    }
  };

  ChartInternal.prototype.initEventRect = function () {
    var $$ = this,
        config = $$.config;
    $$.main.select('.' + CLASS.chart).append("g").attr("class", CLASS.eventRects).style('fill-opacity', 0);
    $$.eventRect = $$.main.select('.' + CLASS.eventRects).append('rect').attr('class', CLASS.eventRect); // event rect handle zoom event as well

    if (config.zoom_enabled && $$.zoom) {
      $$.eventRect.call($$.zoom).on("dblclick.zoom", null);

      if (config.zoom_initialRange) {
        // WORKAROUND: Add transition to apply transform immediately when no subchart
        $$.eventRect.transition().duration(0).call($$.zoom.transform, $$.zoomTransform(config.zoom_initialRange));
      }
    }
  };

  ChartInternal.prototype.redrawEventRect = function () {
    var $$ = this,
        d3 = $$.d3,
        config = $$.config,
        x,
        y,
        w,
        h; // TODO: rotated not supported yet

    x = 0;
    y = 0;
    w = $$.width;
    h = $$.height;

    function mouseout() {
      $$.svg.select('.' + CLASS.eventRect).style('cursor', null);
      $$.hideXGridFocus();
      $$.hideTooltip();
      $$.unexpandCircles();
      $$.unexpandBars();
    } // rects for mouseover


    $$.main.select('.' + CLASS.eventRects).style('cursor', config.zoom_enabled ? config.axis_rotated ? 'ns-resize' : 'ew-resize' : null);
    $$.eventRect.attr('x', x).attr('y', y).attr('width', w).attr('height', h).on('mouseout', config.interaction_enabled ? function () {
      if (!config) {
        return;
      } // chart is destroyed


      if ($$.hasArcType()) {
        return;
      }

      mouseout();
    } : null).on('mousemove', config.interaction_enabled ? function () {
      var targetsToShow, mouse, closest, sameXData, selectedData;

      if ($$.dragging) {
        return;
      } // do nothing when dragging


      if ($$.hasArcType(targetsToShow)) {
        return;
      }

      targetsToShow = $$.filterTargetsToShow($$.data.targets);
      mouse = d3.mouse(this);
      closest = $$.findClosestFromTargets(targetsToShow, mouse);

      if ($$.mouseover && (!closest || closest.id !== $$.mouseover.id)) {
        config.data_onmouseout.call($$.api, $$.mouseover);
        $$.mouseover = undefined;
      }

      if (!closest) {
        mouseout();
        return;
      }

      if ($$.isScatterType(closest) || !config.tooltip_grouped) {
        sameXData = [closest];
      } else {
        sameXData = $$.filterByX(targetsToShow, closest.x);
      } // show tooltip when cursor is close to some point


      selectedData = sameXData.map(function (d) {
        return $$.addName(d);
      });
      $$.showTooltip(selectedData, this); // expand points

      if (config.point_focus_expand_enabled) {
        $$.unexpandCircles();
        selectedData.forEach(function (d) {
          $$.expandCircles(d.index, d.id, false);
        });
      }

      $$.expandBars(closest.index, closest.id, true); // Show xgrid focus line

      $$.showXGridFocus(selectedData); // Show cursor as pointer if point is close to mouse position

      if ($$.isBarType(closest.id) || $$.dist(closest, mouse) < config.point_sensitivity) {
        $$.svg.select('.' + CLASS.eventRect).style('cursor', 'pointer');

        if (!$$.mouseover) {
          config.data_onmouseover.call($$.api, closest);
          $$.mouseover = closest;
        }
      }
    } : null).on('click', config.interaction_enabled ? function () {
      var targetsToShow, mouse, closest, sameXData;

      if ($$.hasArcType(targetsToShow)) {
        return;
      }

      targetsToShow = $$.filterTargetsToShow($$.data.targets);
      mouse = d3.mouse(this);
      closest = $$.findClosestFromTargets(targetsToShow, mouse);

      if (!closest) {
        return;
      } // select if selection enabled


      if ($$.isBarType(closest.id) || $$.dist(closest, mouse) < config.point_sensitivity) {
        if ($$.isScatterType(closest) || !config.data_selection_grouped) {
          sameXData = [closest];
        } else {
          sameXData = $$.filterByX(targetsToShow, closest.x);
        }

        sameXData.forEach(function (d) {
          $$.main.selectAll('.' + CLASS.shapes + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.shape + '-' + d.index).each(function () {
            if (config.data_selection_grouped || $$.isWithinShape(this, d)) {
              $$.toggleShape(this, d, d.index);
              config.data_onclick.call($$.api, d, this);
            }
          });
        });
      }
    } : null).call(config.interaction_enabled && config.data_selection_draggable && $$.drag ? d3.drag().on('drag', function () {
      $$.drag(d3.mouse(this));
    }).on('start', function () {
      $$.dragstart(d3.mouse(this));
    }).on('end', function () {
      $$.dragend();
    }) : function () {});
  };

  ChartInternal.prototype.getMousePosition = function (data) {
    var $$ = this;
    return [$$.x(data.x), $$.getYScale(data.id)(data.value)];
  };

  ChartInternal.prototype.dispatchEvent = function (type, mouse) {
    var $$ = this,
        selector = '.' + CLASS.eventRect,
        eventRect = $$.main.select(selector).node(),
        box = eventRect.getBoundingClientRect(),
        x = box.left + (mouse ? mouse[0] : 0),
        y = box.top + (mouse ? mouse[1] : 0),
        event = document.createEvent("MouseEvents");
    event.initMouseEvent(type, true, true, window, 0, x, y, x, y, false, false, false, false, 0, null);
    eventRect.dispatchEvent(event);
  };

  ChartInternal.prototype.initLegend = function () {
    var $$ = this;
    $$.legendItemTextBox = {};
    $$.legendHasRendered = false;
    $$.legend = $$.svg.append("g").attr("transform", $$.getTranslate('legend'));

    if (!$$.config.legend_show) {
      $$.legend.style('visibility', 'hidden');
      $$.hiddenLegendIds = $$.mapToIds($$.data.targets);
      return;
    } // MEMO: call here to update legend box and tranlate for all
    // MEMO: translate will be upated by this, so transform not needed in updateLegend()


    $$.updateLegendWithDefaults();
  };

  ChartInternal.prototype.updateLegendWithDefaults = function () {
    var $$ = this;
    $$.updateLegend($$.mapToIds($$.data.targets), {
      withTransform: false,
      withTransitionForTransform: false,
      withTransition: false
    });
  };

  ChartInternal.prototype.updateSizeForLegend = function (legendHeight, legendWidth) {
    var $$ = this,
        config = $$.config,
        insetLegendPosition = {
      top: $$.isLegendTop ? $$.getCurrentPaddingTop() + config.legend_inset_y + 5.5 : $$.currentHeight - legendHeight - $$.getCurrentPaddingBottom() - config.legend_inset_y,
      left: $$.isLegendLeft ? $$.getCurrentPaddingLeft() + config.legend_inset_x + 0.5 : $$.currentWidth - legendWidth - $$.getCurrentPaddingRight() - config.legend_inset_x + 0.5
    };
    $$.margin3 = {
      top: $$.isLegendRight ? 0 : $$.isLegendInset ? insetLegendPosition.top : $$.currentHeight - legendHeight,
      right: NaN,
      bottom: 0,
      left: $$.isLegendRight ? $$.currentWidth - legendWidth : $$.isLegendInset ? insetLegendPosition.left : 0
    };
  };

  ChartInternal.prototype.transformLegend = function (withTransition) {
    var $$ = this;
    (withTransition ? $$.legend.transition() : $$.legend).attr("transform", $$.getTranslate('legend'));
  };

  ChartInternal.prototype.updateLegendStep = function (step) {
    this.legendStep = step;
  };

  ChartInternal.prototype.updateLegendItemWidth = function (w) {
    this.legendItemWidth = w;
  };

  ChartInternal.prototype.updateLegendItemHeight = function (h) {
    this.legendItemHeight = h;
  };

  ChartInternal.prototype.getLegendWidth = function () {
    var $$ = this;
    return $$.config.legend_show ? $$.isLegendRight || $$.isLegendInset ? $$.legendItemWidth * ($$.legendStep + 1) : $$.currentWidth : 0;
  };

  ChartInternal.prototype.getLegendHeight = function () {
    var $$ = this,
        h = 0;

    if ($$.config.legend_show) {
      if ($$.isLegendRight) {
        h = $$.currentHeight;
      } else {
        h = Math.max(20, $$.legendItemHeight) * ($$.legendStep + 1);
      }
    }

    return h;
  };

  ChartInternal.prototype.opacityForLegend = function (legendItem) {
    return legendItem.classed(CLASS.legendItemHidden) ? null : 1;
  };

  ChartInternal.prototype.opacityForUnfocusedLegend = function (legendItem) {
    return legendItem.classed(CLASS.legendItemHidden) ? null : 0.3;
  };

  ChartInternal.prototype.toggleFocusLegend = function (targetIds, focus) {
    var $$ = this;
    targetIds = $$.mapToTargetIds(targetIds);
    $$.legend.selectAll('.' + CLASS.legendItem).filter(function (id) {
      return targetIds.indexOf(id) >= 0;
    }).classed(CLASS.legendItemFocused, focus).transition().duration(100).style('opacity', function () {
      var opacity = focus ? $$.opacityForLegend : $$.opacityForUnfocusedLegend;
      return opacity.call($$, $$.d3.select(this));
    });
  };

  ChartInternal.prototype.revertLegend = function () {
    var $$ = this,
        d3 = $$.d3;
    $$.legend.selectAll('.' + CLASS.legendItem).classed(CLASS.legendItemFocused, false).transition().duration(100).style('opacity', function () {
      return $$.opacityForLegend(d3.select(this));
    });
  };

  ChartInternal.prototype.showLegend = function (targetIds) {
    var $$ = this,
        config = $$.config;

    if (!config.legend_show) {
      config.legend_show = true;
      $$.legend.style('visibility', 'visible');

      if (!$$.legendHasRendered) {
        $$.updateLegendWithDefaults();
      }
    }

    $$.removeHiddenLegendIds(targetIds);
    $$.legend.selectAll($$.selectorLegends(targetIds)).style('visibility', 'visible').transition().style('opacity', function () {
      return $$.opacityForLegend($$.d3.select(this));
    });
  };

  ChartInternal.prototype.hideLegend = function (targetIds) {
    var $$ = this,
        config = $$.config;

    if (config.legend_show && isEmpty(targetIds)) {
      config.legend_show = false;
      $$.legend.style('visibility', 'hidden');
    }

    $$.addHiddenLegendIds(targetIds);
    $$.legend.selectAll($$.selectorLegends(targetIds)).style('opacity', 0).style('visibility', 'hidden');
  };

  ChartInternal.prototype.clearLegendItemTextBoxCache = function () {
    this.legendItemTextBox = {};
  };

  ChartInternal.prototype.updateLegend = function (targetIds, options, transitions) {
    var $$ = this,
        config = $$.config;
    var xForLegend, xForLegendText, xForLegendRect, yForLegend, yForLegendText, yForLegendRect, x1ForLegendTile, x2ForLegendTile, yForLegendTile;
    var paddingTop = 4,
        paddingRight = 10,
        maxWidth = 0,
        maxHeight = 0,
        posMin = 10,
        tileWidth = config.legend_item_tile_width + 5;
    var l,
        totalLength = 0,
        offsets = {},
        widths = {},
        heights = {},
        margins = [0],
        steps = {},
        step = 0;
    var withTransition, withTransitionForTransform;
    var texts, rects, tiles, background; // Skip elements when their name is set to null

    targetIds = targetIds.filter(function (id) {
      return !isDefined(config.data_names[id]) || config.data_names[id] !== null;
    });
    options = options || {};
    withTransition = getOption(options, "withTransition", true);
    withTransitionForTransform = getOption(options, "withTransitionForTransform", true);

    function getTextBox(textElement, id) {
      if (!$$.legendItemTextBox[id]) {
        $$.legendItemTextBox[id] = $$.getTextRect(textElement.textContent, CLASS.legendItem, textElement);
      }

      return $$.legendItemTextBox[id];
    }

    function updatePositions(textElement, id, index) {
      var reset = index === 0,
          isLast = index === targetIds.length - 1,
          box = getTextBox(textElement, id),
          itemWidth = box.width + tileWidth + (isLast && !($$.isLegendRight || $$.isLegendInset) ? 0 : paddingRight) + config.legend_padding,
          itemHeight = box.height + paddingTop,
          itemLength = $$.isLegendRight || $$.isLegendInset ? itemHeight : itemWidth,
          areaLength = $$.isLegendRight || $$.isLegendInset ? $$.getLegendHeight() : $$.getLegendWidth(),
          margin,
          maxLength; // MEMO: care about condifion of step, totalLength

      function updateValues(id, withoutStep) {
        if (!withoutStep) {
          margin = (areaLength - totalLength - itemLength) / 2;

          if (margin < posMin) {
            margin = (areaLength - itemLength) / 2;
            totalLength = 0;
            step++;
          }
        }

        steps[id] = step;
        margins[step] = $$.isLegendInset ? 10 : margin;
        offsets[id] = totalLength;
        totalLength += itemLength;
      }

      if (reset) {
        totalLength = 0;
        step = 0;
        maxWidth = 0;
        maxHeight = 0;
      }

      if (config.legend_show && !$$.isLegendToShow(id)) {
        widths[id] = heights[id] = steps[id] = offsets[id] = 0;
        return;
      }

      widths[id] = itemWidth;
      heights[id] = itemHeight;

      if (!maxWidth || itemWidth >= maxWidth) {
        maxWidth = itemWidth;
      }

      if (!maxHeight || itemHeight >= maxHeight) {
        maxHeight = itemHeight;
      }

      maxLength = $$.isLegendRight || $$.isLegendInset ? maxHeight : maxWidth;

      if (config.legend_equally) {
        Object.keys(widths).forEach(function (id) {
          widths[id] = maxWidth;
        });
        Object.keys(heights).forEach(function (id) {
          heights[id] = maxHeight;
        });
        margin = (areaLength - maxLength * targetIds.length) / 2;

        if (margin < posMin) {
          totalLength = 0;
          step = 0;
          targetIds.forEach(function (id) {
            updateValues(id);
          });
        } else {
          updateValues(id, true);
        }
      } else {
        updateValues(id);
      }
    }

    if ($$.isLegendInset) {
      step = config.legend_inset_step ? config.legend_inset_step : targetIds.length;
      $$.updateLegendStep(step);
    }

    if ($$.isLegendRight) {
      xForLegend = function xForLegend(id) {
        return maxWidth * steps[id];
      };

      yForLegend = function yForLegend(id) {
        return margins[steps[id]] + offsets[id];
      };
    } else if ($$.isLegendInset) {
      xForLegend = function xForLegend(id) {
        return maxWidth * steps[id] + 10;
      };

      yForLegend = function yForLegend(id) {
        return margins[steps[id]] + offsets[id];
      };
    } else {
      xForLegend = function xForLegend(id) {
        return margins[steps[id]] + offsets[id];
      };

      yForLegend = function yForLegend(id) {
        return maxHeight * steps[id];
      };
    }

    xForLegendText = function xForLegendText(id, i) {
      return xForLegend(id, i) + 4 + config.legend_item_tile_width;
    };

    yForLegendText = function yForLegendText(id, i) {
      return yForLegend(id, i) + 9;
    };

    xForLegendRect = function xForLegendRect(id, i) {
      return xForLegend(id, i);
    };

    yForLegendRect = function yForLegendRect(id, i) {
      return yForLegend(id, i) - 5;
    };

    x1ForLegendTile = function x1ForLegendTile(id, i) {
      return xForLegend(id, i) - 2;
    };

    x2ForLegendTile = function x2ForLegendTile(id, i) {
      return xForLegend(id, i) - 2 + config.legend_item_tile_width;
    };

    yForLegendTile = function yForLegendTile(id, i) {
      return yForLegend(id, i) + 4;
    }; // Define g for legend area


    l = $$.legend.selectAll('.' + CLASS.legendItem).data(targetIds).enter().append('g').attr('class', function (id) {
      return $$.generateClass(CLASS.legendItem, id);
    }).style('visibility', function (id) {
      return $$.isLegendToShow(id) ? 'visible' : 'hidden';
    }).style('cursor', 'pointer').on('click', function (id) {
      if (config.legend_item_onclick) {
        config.legend_item_onclick.call($$, id);
      } else {
        if ($$.d3.event.altKey) {
          $$.api.hide();
          $$.api.show(id);
        } else {
          $$.api.toggle(id);
          $$.isTargetToShow(id) ? $$.api.focus(id) : $$.api.revert();
        }
      }
    }).on('mouseover', function (id) {
      if (config.legend_item_onmouseover) {
        config.legend_item_onmouseover.call($$, id);
      } else {
        $$.d3.select(this).classed(CLASS.legendItemFocused, true);

        if (!$$.transiting && $$.isTargetToShow(id)) {
          $$.api.focus(id);
        }
      }
    }).on('mouseout', function (id) {
      if (config.legend_item_onmouseout) {
        config.legend_item_onmouseout.call($$, id);
      } else {
        $$.d3.select(this).classed(CLASS.legendItemFocused, false);
        $$.api.revert();
      }
    });
    l.append('text').text(function (id) {
      return isDefined(config.data_names[id]) ? config.data_names[id] : id;
    }).each(function (id, i) {
      updatePositions(this, id, i);
    }).style("pointer-events", "none").attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendText : -200).attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendText);
    l.append('rect').attr("class", CLASS.legendItemEvent).style('fill-opacity', 0).attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendRect : -200).attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendRect);
    l.append('line').attr('class', CLASS.legendItemTile).style('stroke', $$.color).style("pointer-events", "none").attr('x1', $$.isLegendRight || $$.isLegendInset ? x1ForLegendTile : -200).attr('y1', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendTile).attr('x2', $$.isLegendRight || $$.isLegendInset ? x2ForLegendTile : -200).attr('y2', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendTile).attr('stroke-width', config.legend_item_tile_height); // Set background for inset legend

    background = $$.legend.select('.' + CLASS.legendBackground + ' rect');

    if ($$.isLegendInset && maxWidth > 0 && background.size() === 0) {
      background = $$.legend.insert('g', '.' + CLASS.legendItem).attr("class", CLASS.legendBackground).append('rect');
    }

    texts = $$.legend.selectAll('text').data(targetIds).text(function (id) {
      return isDefined(config.data_names[id]) ? config.data_names[id] : id;
    }) // MEMO: needed for update
    .each(function (id, i) {
      updatePositions(this, id, i);
    });
    (withTransition ? texts.transition() : texts).attr('x', xForLegendText).attr('y', yForLegendText);
    rects = $$.legend.selectAll('rect.' + CLASS.legendItemEvent).data(targetIds);
    (withTransition ? rects.transition() : rects).attr('width', function (id) {
      return widths[id];
    }).attr('height', function (id) {
      return heights[id];
    }).attr('x', xForLegendRect).attr('y', yForLegendRect);
    tiles = $$.legend.selectAll('line.' + CLASS.legendItemTile).data(targetIds);
    (withTransition ? tiles.transition() : tiles).style('stroke', $$.levelColor ? function (id) {
      return $$.levelColor($$.cache[id].values[0].value);
    } : $$.color).attr('x1', x1ForLegendTile).attr('y1', yForLegendTile).attr('x2', x2ForLegendTile).attr('y2', yForLegendTile);

    if (background) {
      (withTransition ? background.transition() : background).attr('height', $$.getLegendHeight() - 12).attr('width', maxWidth * (step + 1) + 10);
    } // toggle legend state


    $$.legend.selectAll('.' + CLASS.legendItem).classed(CLASS.legendItemHidden, function (id) {
      return !$$.isTargetToShow(id);
    }); // Update all to reflect change of legend

    $$.updateLegendItemWidth(maxWidth);
    $$.updateLegendItemHeight(maxHeight);
    $$.updateLegendStep(step); // Update size and scale

    $$.updateSizes();
    $$.updateScales();
    $$.updateSvgSize(); // Update g positions

    $$.transformAll(withTransitionForTransform, transitions);
    $$.legendHasRendered = true;
  };

  ChartInternal.prototype.initRegion = function () {
    var $$ = this;
    $$.region = $$.main.append('g').attr("clip-path", $$.clipPath).attr("class", CLASS.regions);
  };

  ChartInternal.prototype.updateRegion = function (duration) {
    var $$ = this,
        config = $$.config; // hide if arc type

    $$.region.style('visibility', $$.hasArcType() ? 'hidden' : 'visible');
    var mainRegion = $$.main.select('.' + CLASS.regions).selectAll('.' + CLASS.region).data(config.regions);
    var mainRegionEnter = mainRegion.enter().append('rect').attr("x", $$.regionX.bind($$)).attr("y", $$.regionY.bind($$)).attr("width", $$.regionWidth.bind($$)).attr("height", $$.regionHeight.bind($$)).style("fill-opacity", 0);
    $$.mainRegion = mainRegionEnter.merge(mainRegion).attr('class', $$.classRegion.bind($$));
    mainRegion.exit().transition().duration(duration).style("opacity", 0).remove();
  };

  ChartInternal.prototype.redrawRegion = function (withTransition, transition) {
    var $$ = this,
        regions = $$.mainRegion;
    return [(withTransition ? regions.transition(transition) : regions).attr("x", $$.regionX.bind($$)).attr("y", $$.regionY.bind($$)).attr("width", $$.regionWidth.bind($$)).attr("height", $$.regionHeight.bind($$)).style("fill-opacity", function (d) {
      return isValue(d.opacity) ? d.opacity : 0.1;
    })];
  };

  ChartInternal.prototype.regionX = function (d) {
    var $$ = this,
        config = $$.config,
        xPos,
        yScale = d.axis === 'y' ? $$.y : $$.y2;

    if (d.axis === 'y' || d.axis === 'y2') {
      xPos = config.axis_rotated ? 'start' in d ? yScale(d.start) : 0 : 0;
    } else {
      xPos = config.axis_rotated ? 0 : 'start' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.start) : d.start) : 0;
    }

    return xPos;
  };

  ChartInternal.prototype.regionY = function (d) {
    var $$ = this,
        config = $$.config,
        yPos,
        yScale = d.axis === 'y' ? $$.y : $$.y2;

    if (d.axis === 'y' || d.axis === 'y2') {
      yPos = config.axis_rotated ? 0 : 'end' in d ? yScale(d.end) : 0;
    } else {
      yPos = config.axis_rotated ? 'start' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.start) : d.start) : 0 : 0;
    }

    return yPos;
  };

  ChartInternal.prototype.regionWidth = function (d) {
    var $$ = this,
        config = $$.config,
        start = $$.regionX(d),
        end,
        yScale = d.axis === 'y' ? $$.y : $$.y2;

    if (d.axis === 'y' || d.axis === 'y2') {
      end = config.axis_rotated ? 'end' in d ? yScale(d.end) : $$.width : $$.width;
    } else {
      end = config.axis_rotated ? $$.width : 'end' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.end) : d.end) : $$.width;
    }

    return end < start ? 0 : end - start;
  };

  ChartInternal.prototype.regionHeight = function (d) {
    var $$ = this,
        config = $$.config,
        start = this.regionY(d),
        end,
        yScale = d.axis === 'y' ? $$.y : $$.y2;

    if (d.axis === 'y' || d.axis === 'y2') {
      end = config.axis_rotated ? $$.height : 'start' in d ? yScale(d.start) : $$.height;
    } else {
      end = config.axis_rotated ? 'end' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.end) : d.end) : $$.height : $$.height;
    }

    return end < start ? 0 : end - start;
  };

  ChartInternal.prototype.isRegionOnX = function (d) {
    return !d.axis || d.axis === 'x';
  };

  ChartInternal.prototype.getScale = function (min, max, forTimeseries) {
    return (forTimeseries ? this.d3.scaleTime() : this.d3.scaleLinear()).range([min, max]);
  };

  ChartInternal.prototype.getX = function (min, max, domain, offset) {
    var $$ = this,
        scale = $$.getScale(min, max, $$.isTimeSeries()),
        _scale = domain ? scale.domain(domain) : scale,
        key; // Define customized scale if categorized axis


    if ($$.isCategorized()) {
      offset = offset || function () {
        return 0;
      };

      scale = function scale(d, raw) {
        var v = _scale(d) + offset(d);
        return raw ? v : Math.ceil(v);
      };
    } else {
      scale = function scale(d, raw) {
        var v = _scale(d);

        return raw ? v : Math.ceil(v);
      };
    } // define functions


    for (key in _scale) {
      scale[key] = _scale[key];
    }

    scale.orgDomain = function () {
      return _scale.domain();
    }; // define custom domain() for categorized axis


    if ($$.isCategorized()) {
      scale.domain = function (domain) {
        if (!arguments.length) {
          domain = this.orgDomain();
          return [domain[0], domain[1] + 1];
        }

        _scale.domain(domain);

        return scale;
      };
    }

    return scale;
  };

  ChartInternal.prototype.getY = function (min, max, domain) {
    var scale = this.getScale(min, max, this.isTimeSeriesY());

    if (domain) {
      scale.domain(domain);
    }

    return scale;
  };

  ChartInternal.prototype.getYScale = function (id) {
    return this.axis.getId(id) === 'y2' ? this.y2 : this.y;
  };

  ChartInternal.prototype.getSubYScale = function (id) {
    return this.axis.getId(id) === 'y2' ? this.subY2 : this.subY;
  };

  ChartInternal.prototype.updateScales = function () {
    var $$ = this,
        config = $$.config,
        forInit = !$$.x; // update edges

    $$.xMin = config.axis_rotated ? 1 : 0;
    $$.xMax = config.axis_rotated ? $$.height : $$.width;
    $$.yMin = config.axis_rotated ? 0 : $$.height;
    $$.yMax = config.axis_rotated ? $$.width : 1;
    $$.subXMin = $$.xMin;
    $$.subXMax = $$.xMax;
    $$.subYMin = config.axis_rotated ? 0 : $$.height2;
    $$.subYMax = config.axis_rotated ? $$.width2 : 1; // update scales

    $$.x = $$.getX($$.xMin, $$.xMax, forInit ? undefined : $$.x.orgDomain(), function () {
      return $$.xAxis.tickOffset();
    });
    $$.y = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y_default : $$.y.domain());
    $$.y2 = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y2_default : $$.y2.domain());
    $$.subX = $$.getX($$.xMin, $$.xMax, $$.orgXDomain, function (d) {
      return d % 1 ? 0 : $$.subXAxis.tickOffset();
    });
    $$.subY = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y_default : $$.subY.domain());
    $$.subY2 = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y2_default : $$.subY2.domain()); // update axes

    $$.xAxisTickFormat = $$.axis.getXAxisTickFormat();
    $$.xAxisTickValues = $$.axis.getXAxisTickValues();
    $$.yAxisTickValues = $$.axis.getYAxisTickValues();
    $$.y2AxisTickValues = $$.axis.getY2AxisTickValues();
    $$.xAxis = $$.axis.getXAxis($$.x, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer);
    $$.subXAxis = $$.axis.getXAxis($$.subX, $$.subXOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer);
    $$.yAxis = $$.axis.getYAxis($$.y, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues, config.axis_y_tick_outer);
    $$.y2Axis = $$.axis.getYAxis($$.y2, $$.y2Orient, config.axis_y2_tick_format, $$.y2AxisTickValues, config.axis_y2_tick_outer); // Set initialized scales to brush and zoom

    if (!forInit) {
      if ($$.brush) {
        $$.brush.updateScale($$.subX);
      }
    } // update for arc


    if ($$.updateArc) {
      $$.updateArc();
    }
  };

  ChartInternal.prototype.selectPoint = function (target, d, i) {
    var $$ = this,
        config = $$.config,
        cx = (config.axis_rotated ? $$.circleY : $$.circleX).bind($$),
        cy = (config.axis_rotated ? $$.circleX : $$.circleY).bind($$),
        r = $$.pointSelectR.bind($$);
    config.data_onselected.call($$.api, d, target.node()); // add selected-circle on low layer g

    $$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i).data([d]).enter().append('circle').attr("class", function () {
      return $$.generateClass(CLASS.selectedCircle, i);
    }).attr("cx", cx).attr("cy", cy).attr("stroke", function () {
      return $$.color(d);
    }).attr("r", function (d) {
      return $$.pointSelectR(d) * 1.4;
    }).transition().duration(100).attr("r", r);
  };

  ChartInternal.prototype.unselectPoint = function (target, d, i) {
    var $$ = this;
    $$.config.data_onunselected.call($$.api, d, target.node()); // remove selected-circle from low layer g

    $$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i).transition().duration(100).attr('r', 0).remove();
  };

  ChartInternal.prototype.togglePoint = function (selected, target, d, i) {
    selected ? this.selectPoint(target, d, i) : this.unselectPoint(target, d, i);
  };

  ChartInternal.prototype.selectPath = function (target, d) {
    var $$ = this;
    $$.config.data_onselected.call($$, d, target.node());

    if ($$.config.interaction_brighten) {
      target.transition().duration(100).style("fill", function () {
        return $$.d3.rgb($$.color(d)).brighter(0.75);
      });
    }
  };

  ChartInternal.prototype.unselectPath = function (target, d) {
    var $$ = this;
    $$.config.data_onunselected.call($$, d, target.node());

    if ($$.config.interaction_brighten) {
      target.transition().duration(100).style("fill", function () {
        return $$.color(d);
      });
    }
  };

  ChartInternal.prototype.togglePath = function (selected, target, d, i) {
    selected ? this.selectPath(target, d, i) : this.unselectPath(target, d, i);
  };

  ChartInternal.prototype.getToggle = function (that, d) {
    var $$ = this,
        toggle;

    if (that.nodeName === 'circle') {
      if ($$.isStepType(d)) {
        // circle is hidden in step chart, so treat as within the click area
        toggle = function toggle() {}; // TODO: how to select step chart?

      } else {
        toggle = $$.togglePoint;
      }
    } else if (that.nodeName === 'path') {
      toggle = $$.togglePath;
    }

    return toggle;
  };

  ChartInternal.prototype.toggleShape = function (that, d, i) {
    var $$ = this,
        d3 = $$.d3,
        config = $$.config,
        shape = d3.select(that),
        isSelected = shape.classed(CLASS.SELECTED),
        toggle = $$.getToggle(that, d).bind($$);

    if (config.data_selection_enabled && config.data_selection_isselectable(d)) {
      if (!config.data_selection_multiple) {
        $$.main.selectAll('.' + CLASS.shapes + (config.data_selection_grouped ? $$.getTargetSelectorSuffix(d.id) : "")).selectAll('.' + CLASS.shape).each(function (d, i) {
          var shape = d3.select(this);

          if (shape.classed(CLASS.SELECTED)) {
            toggle(false, shape.classed(CLASS.SELECTED, false), d, i);
          }
        });
      }

      shape.classed(CLASS.SELECTED, !isSelected);
      toggle(!isSelected, shape, d, i);
    }
  };

  ChartInternal.prototype.initBar = function () {
    var $$ = this;
    $$.main.select('.' + CLASS.chart).append("g").attr("class", CLASS.chartBars);
  };

  ChartInternal.prototype.updateTargetsForBar = function (targets) {
    var $$ = this,
        config = $$.config,
        mainBars,
        mainBarEnter,
        classChartBar = $$.classChartBar.bind($$),
        classBars = $$.classBars.bind($$),
        classFocus = $$.classFocus.bind($$);
    mainBars = $$.main.select('.' + CLASS.chartBars).selectAll('.' + CLASS.chartBar).data(targets).attr('class', function (d) {
      return classChartBar(d) + classFocus(d);
    });
    mainBarEnter = mainBars.enter().append('g').attr('class', classChartBar).style("pointer-events", "none"); // Bars for each data

    mainBarEnter.append('g').attr("class", classBars).style("cursor", function (d) {
      return config.data_selection_isselectable(d) ? "pointer" : null;
    });
  };

  ChartInternal.prototype.updateBar = function (durationForExit) {
    var $$ = this,
        barData = $$.barData.bind($$),
        classBar = $$.classBar.bind($$),
        initialOpacity = $$.initialOpacity.bind($$),
        color = function color(d) {
      return $$.color(d.id);
    };

    var mainBar = $$.main.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar).data(barData);
    var mainBarEnter = mainBar.enter().append('path').attr("class", classBar).style("stroke", color).style("fill", color);
    $$.mainBar = mainBarEnter.merge(mainBar).style("opacity", initialOpacity);
    mainBar.exit().transition().duration(durationForExit).style("opacity", 0);
  };

  ChartInternal.prototype.redrawBar = function (drawBar, withTransition, transition) {
    return [(withTransition ? this.mainBar.transition(transition) : this.mainBar).attr('d', drawBar).style("stroke", this.color).style("fill", this.color).style("opacity", 1)];
  };

  ChartInternal.prototype.getBarW = function (axis, barTargetsNum) {
    var $$ = this,
        config = $$.config,
        w = typeof config.bar_width === 'number' ? config.bar_width : barTargetsNum ? axis.tickInterval() * config.bar_width_ratio / barTargetsNum : 0;
    return config.bar_width_max && w > config.bar_width_max ? config.bar_width_max : w;
  };

  ChartInternal.prototype.getBars = function (i, id) {
    var $$ = this;
    return (id ? $$.main.selectAll('.' + CLASS.bars + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.bar + (isValue(i) ? '-' + i : ''));
  };

  ChartInternal.prototype.expandBars = function (i, id, reset) {
    var $$ = this;

    if (reset) {
      $$.unexpandBars();
    }

    $$.getBars(i, id).classed(CLASS.EXPANDED, true);
  };

  ChartInternal.prototype.unexpandBars = function (i) {
    var $$ = this;
    $$.getBars(i).classed(CLASS.EXPANDED, false);
  };

  ChartInternal.prototype.generateDrawBar = function (barIndices, isSub) {
    var $$ = this,
        config = $$.config,
        getPoints = $$.generateGetBarPoints(barIndices, isSub);
    return function (d, i) {
      // 4 points that make a bar
      var points = getPoints(d, i); // switch points if axis is rotated, not applicable for sub chart

      var indexX = config.axis_rotated ? 1 : 0;
      var indexY = config.axis_rotated ? 0 : 1;
      var path = 'M ' + points[0][indexX] + ',' + points[0][indexY] + ' ' + 'L' + points[1][indexX] + ',' + points[1][indexY] + ' ' + 'L' + points[2][indexX] + ',' + points[2][indexY] + ' ' + 'L' + points[3][indexX] + ',' + points[3][indexY] + ' ' + 'z';
      return path;
    };
  };

  ChartInternal.prototype.generateGetBarPoints = function (barIndices, isSub) {
    var $$ = this,
        axis = isSub ? $$.subXAxis : $$.xAxis,
        barTargetsNum = barIndices.__max__ + 1,
        barW = $$.getBarW(axis, barTargetsNum),
        barX = $$.getShapeX(barW, barTargetsNum, barIndices, !!isSub),
        barY = $$.getShapeY(!!isSub),
        barOffset = $$.getShapeOffset($$.isBarType, barIndices, !!isSub),
        barSpaceOffset = barW * ($$.config.bar_space / 2),
        yScale = isSub ? $$.getSubYScale : $$.getYScale;
    return function (d, i) {
      var y0 = yScale.call($$, d.id)(0),
          offset = barOffset(d, i) || y0,
          // offset is for stacked bar chart
      posX = barX(d),
          posY = barY(d); // fix posY not to overflow opposite quadrant

      if ($$.config.axis_rotated) {
        if (0 < d.value && posY < y0 || d.value < 0 && y0 < posY) {
          posY = y0;
        }
      } // 4 points that make a bar


      return [[posX + barSpaceOffset, offset], [posX + barSpaceOffset, posY - (y0 - offset)], [posX + barW - barSpaceOffset, posY - (y0 - offset)], [posX + barW - barSpaceOffset, offset]];
    };
  };

  ChartInternal.prototype.isWithinBar = function (mouse, that) {
    var box = that.getBoundingClientRect(),
        seg0 = that.pathSegList.getItem(0),
        seg1 = that.pathSegList.getItem(1),
        x = Math.min(seg0.x, seg1.x),
        y = Math.min(seg0.y, seg1.y),
        w = box.width,
        h = box.height,
        offset = 2,
        sx = x - offset,
        ex = x + w + offset,
        sy = y + h + offset,
        ey = y - offset;
    return sx < mouse[0] && mouse[0] < ex && ey < mouse[1] && mouse[1] < sy;
  };

  ChartInternal.prototype.getShapeIndices = function (typeFilter) {
    var $$ = this,
        config = $$.config,
        indices = {},
        i = 0,
        j,
        k;
    $$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$)).forEach(function (d) {
      for (j = 0; j < config.data_groups.length; j++) {
        if (config.data_groups[j].indexOf(d.id) < 0) {
          continue;
        }

        for (k = 0; k < config.data_groups[j].length; k++) {
          if (config.data_groups[j][k] in indices) {
            indices[d.id] = indices[config.data_groups[j][k]];
            break;
          }
        }
      }

      if (isUndefined(indices[d.id])) {
        indices[d.id] = i++;
      }
    });
    indices.__max__ = i - 1;
    return indices;
  };

  ChartInternal.prototype.getShapeX = function (offset, targetsNum, indices, isSub) {
    var $$ = this,
        scale = isSub ? $$.subX : $$.x;
    return function (d) {
      var index = d.id in indices ? indices[d.id] : 0;
      return d.x || d.x === 0 ? scale(d.x) - offset * (targetsNum / 2 - index) : 0;
    };
  };

  ChartInternal.prototype.getShapeY = function (isSub) {
    var $$ = this;
    return function (d) {
      var scale = isSub ? $$.getSubYScale(d.id) : $$.getYScale(d.id);
      return scale(d.value);
    };
  };

  ChartInternal.prototype.getShapeOffset = function (typeFilter, indices, isSub) {
    var $$ = this,
        targets = $$.orderTargets($$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$))),
        targetIds = targets.map(function (t) {
      return t.id;
    });
    return function (d, i) {
      var scale = isSub ? $$.getSubYScale(d.id) : $$.getYScale(d.id),
          y0 = scale(0),
          offset = y0;
      targets.forEach(function (t) {
        var values = $$.isStepType(d) ? $$.convertValuesToStep(t.values) : t.values;

        if (t.id === d.id || indices[t.id] !== indices[d.id]) {
          return;
        }

        if (targetIds.indexOf(t.id) < targetIds.indexOf(d.id)) {
          // check if the x values line up
          if (typeof values[i] === 'undefined' || +values[i].x !== +d.x) {
            // "+" for timeseries
            // if not, try to find the value that does line up
            i = -1;
            values.forEach(function (v, j) {
              if (v.x === d.x) {
                i = j;
              }
            });
          }

          if (i in values && values[i].value * d.value >= 0) {
            offset += scale(values[i].value) - y0;
          }
        }
      });
      return offset;
    };
  };

  ChartInternal.prototype.isWithinShape = function (that, d) {
    var $$ = this,
        shape = $$.d3.select(that),
        isWithin;

    if (!$$.isTargetToShow(d.id)) {
      isWithin = false;
    } else if (that.nodeName === 'circle') {
      isWithin = $$.isStepType(d) ? $$.isWithinStep(that, $$.getYScale(d.id)(d.value)) : $$.isWithinCircle(that, $$.pointSelectR(d) * 1.5);
    } else if (that.nodeName === 'path') {
      isWithin = shape.classed(CLASS.bar) ? $$.isWithinBar($$.d3.mouse(that), that) : true;
    }

    return isWithin;
  };

  ChartInternal.prototype.getInterpolate = function (d) {
    var $$ = this,
        d3 = $$.d3,
        types = {
      'linear': d3.curveLinear,
      'linear-closed': d3.curveLinearClosed,
      'basis': d3.curveBasis,
      'basis-open': d3.curveBasisOpen,
      'basis-closed': d3.curveBasisClosed,
      'bundle': d3.curveBundle,
      'cardinal': d3.curveCardinal,
      'cardinal-open': d3.curveCardinalOpen,
      'cardinal-closed': d3.curveCardinalClosed,
      'monotone': d3.curveMonotoneX,
      'step': d3.curveStep,
      'step-before': d3.curveStepBefore,
      'step-after': d3.curveStepAfter
    },
        type;

    if ($$.isSplineType(d)) {
      type = types[$$.config.spline_interpolation_type] || types.cardinal;
    } else if ($$.isStepType(d)) {
      type = types[$$.config.line_step_type];
    } else {
      type = types.linear;
    }

    return type;
  };

  ChartInternal.prototype.initLine = function () {
    var $$ = this;
    $$.main.select('.' + CLASS.chart).append("g").attr("class", CLASS.chartLines);
  };

  ChartInternal.prototype.updateTargetsForLine = function (targets) {
    var $$ = this,
        config = $$.config,
        mainLines,
        mainLineEnter,
        classChartLine = $$.classChartLine.bind($$),
        classLines = $$.classLines.bind($$),
        classAreas = $$.classAreas.bind($$),
        classCircles = $$.classCircles.bind($$),
        classFocus = $$.classFocus.bind($$);
    mainLines = $$.main.select('.' + CLASS.chartLines).selectAll('.' + CLASS.chartLine).data(targets).attr('class', function (d) {
      return classChartLine(d) + classFocus(d);
    });
    mainLineEnter = mainLines.enter().append('g').attr('class', classChartLine).style('opacity', 0).style("pointer-events", "none"); // Lines for each data

    mainLineEnter.append('g').attr("class", classLines); // Areas

    mainLineEnter.append('g').attr('class', classAreas); // Circles for each data point on lines

    mainLineEnter.append('g').attr("class", function (d) {
      return $$.generateClass(CLASS.selectedCircles, d.id);
    });
    mainLineEnter.append('g').attr("class", classCircles).style("cursor", function (d) {
      return config.data_selection_isselectable(d) ? "pointer" : null;
    }); // Update date for selected circles

    targets.forEach(function (t) {
      $$.main.selectAll('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(t.id)).selectAll('.' + CLASS.selectedCircle).each(function (d) {
        d.value = t.values[d.index].value;
      });
    }); // MEMO: can not keep same color...
    //mainLineUpdate.exit().remove();
  };

  ChartInternal.prototype.updateLine = function (durationForExit) {
    var $$ = this;
    var mainLine = $$.main.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line).data($$.lineData.bind($$));
    var mainLineEnter = mainLine.enter().append('path').attr('class', $$.classLine.bind($$)).style("stroke", $$.color);
    $$.mainLine = mainLineEnter.merge(mainLine).style("opacity", $$.initialOpacity.bind($$)).style('shape-rendering', function (d) {
      return $$.isStepType(d) ? 'crispEdges' : '';
    }).attr('transform', null);
    mainLine.exit().transition().duration(durationForExit).style('opacity', 0);
  };

  ChartInternal.prototype.redrawLine = function (drawLine, withTransition, transition) {
    return [(withTransition ? this.mainLine.transition(transition) : this.mainLine).attr("d", drawLine).style("stroke", this.color).style("opacity", 1)];
  };

  ChartInternal.prototype.generateDrawLine = function (lineIndices, isSub) {
    var $$ = this,
        config = $$.config,
        line = $$.d3.line(),
        getPoints = $$.generateGetLinePoints(lineIndices, isSub),
        yScaleGetter = isSub ? $$.getSubYScale : $$.getYScale,
        xValue = function xValue(d) {
      return (isSub ? $$.subxx : $$.xx).call($$, d);
    },
        yValue = function yValue(d, i) {
      return config.data_groups.length > 0 ? getPoints(d, i)[0][1] : yScaleGetter.call($$, d.id)(d.value);
    };

    line = config.axis_rotated ? line.x(yValue).y(xValue) : line.x(xValue).y(yValue);

    if (!config.line_connectNull) {
      line = line.defined(function (d) {
        return d.value != null;
      });
    }

    return function (d) {
      var values = config.line_connectNull ? $$.filterRemoveNull(d.values) : d.values,
          x = isSub ? $$.subX : $$.x,
          y = yScaleGetter.call($$, d.id),
          x0 = 0,
          y0 = 0,
          path;

      if ($$.isLineType(d)) {
        if (config.data_regions[d.id]) {
          path = $$.lineWithRegions(values, x, y, config.data_regions[d.id]);
        } else {
          if ($$.isStepType(d)) {
            values = $$.convertValuesToStep(values);
          }

          path = line.curve($$.getInterpolate(d))(values);
        }
      } else {
        if (values[0]) {
          x0 = x(values[0].x);
          y0 = y(values[0].value);
        }

        path = config.axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0;
      }

      return path ? path : "M 0 0";
    };
  };

  ChartInternal.prototype.generateGetLinePoints = function (lineIndices, isSub) {
    // partial duplication of generateGetBarPoints
    var $$ = this,
        config = $$.config,
        lineTargetsNum = lineIndices.__max__ + 1,
        x = $$.getShapeX(0, lineTargetsNum, lineIndices, !!isSub),
        y = $$.getShapeY(!!isSub),
        lineOffset = $$.getShapeOffset($$.isLineType, lineIndices, !!isSub),
        yScale = isSub ? $$.getSubYScale : $$.getYScale;
    return function (d, i) {
      var y0 = yScale.call($$, d.id)(0),
          offset = lineOffset(d, i) || y0,
          // offset is for stacked area chart
      posX = x(d),
          posY = y(d); // fix posY not to overflow opposite quadrant

      if (config.axis_rotated) {
        if (0 < d.value && posY < y0 || d.value < 0 && y0 < posY) {
          posY = y0;
        }
      } // 1 point that marks the line position


      return [[posX, posY - (y0 - offset)], [posX, posY - (y0 - offset)], // needed for compatibility
      [posX, posY - (y0 - offset)], // needed for compatibility
      [posX, posY - (y0 - offset)] // needed for compatibility
      ];
    };
  };

  ChartInternal.prototype.lineWithRegions = function (d, x, y, _regions) {
    var $$ = this,
        config = $$.config,
        prev = -1,
        i,
        j,
        s = "M",
        sWithRegion,
        xp,
        yp,
        dx,
        dy,
        dd,
        diff,
        diffx2,
        xOffset = $$.isCategorized() ? 0.5 : 0,
        xValue,
        yValue,
        regions = [];

    function isWithinRegions(x, regions) {
      var i;

      for (i = 0; i < regions.length; i++) {
        if (regions[i].start < x && x <= regions[i].end) {
          return true;
        }
      }

      return false;
    } // Check start/end of regions


    if (isDefined(_regions)) {
      for (i = 0; i < _regions.length; i++) {
        regions[i] = {};

        if (isUndefined(_regions[i].start)) {
          regions[i].start = d[0].x;
        } else {
          regions[i].start = $$.isTimeSeries() ? $$.parseDate(_regions[i].start) : _regions[i].start;
        }

        if (isUndefined(_regions[i].end)) {
          regions[i].end = d[d.length - 1].x;
        } else {
          regions[i].end = $$.isTimeSeries() ? $$.parseDate(_regions[i].end) : _regions[i].end;
        }
      }
    } // Set scales


    xValue = config.axis_rotated ? function (d) {
      return y(d.value);
    } : function (d) {
      return x(d.x);
    };
    yValue = config.axis_rotated ? function (d) {
      return x(d.x);
    } : function (d) {
      return y(d.value);
    }; // Define svg generator function for region

    function generateM(points) {
      return 'M' + points[0][0] + ' ' + points[0][1] + ' ' + points[1][0] + ' ' + points[1][1];
    }

    if ($$.isTimeSeries()) {
      sWithRegion = function sWithRegion(d0, d1, j, diff) {
        var x0 = d0.x.getTime(),
            x_diff = d1.x - d0.x,
            xv0 = new Date(x0 + x_diff * j),
            xv1 = new Date(x0 + x_diff * (j + diff)),
            points;

        if (config.axis_rotated) {
          points = [[y(yp(j)), x(xv0)], [y(yp(j + diff)), x(xv1)]];
        } else {
          points = [[x(xv0), y(yp(j))], [x(xv1), y(yp(j + diff))]];
        }

        return generateM(points);
      };
    } else {
      sWithRegion = function sWithRegion(d0, d1, j, diff) {
        var points;

        if (config.axis_rotated) {
          points = [[y(yp(j), true), x(xp(j))], [y(yp(j + diff), true), x(xp(j + diff))]];
        } else {
          points = [[x(xp(j), true), y(yp(j))], [x(xp(j + diff), true), y(yp(j + diff))]];
        }

        return generateM(points);
      };
    } // Generate


    for (i = 0; i < d.length; i++) {
      // Draw as normal
      if (isUndefined(regions) || !isWithinRegions(d[i].x, regions)) {
        s += " " + xValue(d[i]) + " " + yValue(d[i]);
      } // Draw with region // TODO: Fix for horizotal charts
      else {
          xp = $$.getScale(d[i - 1].x + xOffset, d[i].x + xOffset, $$.isTimeSeries());
          yp = $$.getScale(d[i - 1].value, d[i].value);
          dx = x(d[i].x) - x(d[i - 1].x);
          dy = y(d[i].value) - y(d[i - 1].value);
          dd = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
          diff = 2 / dd;
          diffx2 = diff * 2;

          for (j = diff; j <= 1; j += diffx2) {
            s += sWithRegion(d[i - 1], d[i], j, diff);
          }
        }

      prev = d[i].x;
    }

    return s;
  };

  ChartInternal.prototype.updateArea = function (durationForExit) {
    var $$ = this,
        d3 = $$.d3;
    var mainArea = $$.main.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area).data($$.lineData.bind($$));
    var mainAreaEnter = mainArea.enter().append('path').attr("class", $$.classArea.bind($$)).style("fill", $$.color).style("opacity", function () {
      $$.orgAreaOpacity = +d3.select(this).style('opacity');
      return 0;
    });
    $$.mainArea = mainAreaEnter.merge(mainArea).style("opacity", $$.orgAreaOpacity);
    mainArea.exit().transition().duration(durationForExit).style('opacity', 0);
  };

  ChartInternal.prototype.redrawArea = function (drawArea, withTransition, transition) {
    return [(withTransition ? this.mainArea.transition(transition) : this.mainArea).attr("d", drawArea).style("fill", this.color).style("opacity", this.orgAreaOpacity)];
  };

  ChartInternal.prototype.generateDrawArea = function (areaIndices, isSub) {
    var $$ = this,
        config = $$.config,
        area = $$.d3.area(),
        getPoints = $$.generateGetAreaPoints(areaIndices, isSub),
        yScaleGetter = isSub ? $$.getSubYScale : $$.getYScale,
        xValue = function xValue(d) {
      return (isSub ? $$.subxx : $$.xx).call($$, d);
    },
        value0 = function value0(d, i) {
      return config.data_groups.length > 0 ? getPoints(d, i)[0][1] : yScaleGetter.call($$, d.id)($$.getAreaBaseValue(d.id));
    },
        value1 = function value1(d, i) {
      return config.data_groups.length > 0 ? getPoints(d, i)[1][1] : yScaleGetter.call($$, d.id)(d.value);
    };

    area = config.axis_rotated ? area.x0(value0).x1(value1).y(xValue) : area.x(xValue).y0(config.area_above ? 0 : value0).y1(value1);

    if (!config.line_connectNull) {
      area = area.defined(function (d) {
        return d.value !== null;
      });
    }

    return function (d) {
      var values = config.line_connectNull ? $$.filterRemoveNull(d.values) : d.values,
          x0 = 0,
          y0 = 0,
          path;

      if ($$.isAreaType(d)) {
        if ($$.isStepType(d)) {
          values = $$.convertValuesToStep(values);
        }

        path = area.curve($$.getInterpolate(d))(values);
      } else {
        if (values[0]) {
          x0 = $$.x(values[0].x);
          y0 = $$.getYScale(d.id)(values[0].value);
        }

        path = config.axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0;
      }

      return path ? path : "M 0 0";
    };
  };

  ChartInternal.prototype.getAreaBaseValue = function () {
    return 0;
  };

  ChartInternal.prototype.generateGetAreaPoints = function (areaIndices, isSub) {
    // partial duplication of generateGetBarPoints
    var $$ = this,
        config = $$.config,
        areaTargetsNum = areaIndices.__max__ + 1,
        x = $$.getShapeX(0, areaTargetsNum, areaIndices, !!isSub),
        y = $$.getShapeY(!!isSub),
        areaOffset = $$.getShapeOffset($$.isAreaType, areaIndices, !!isSub),
        yScale = isSub ? $$.getSubYScale : $$.getYScale;
    return function (d, i) {
      var y0 = yScale.call($$, d.id)(0),
          offset = areaOffset(d, i) || y0,
          // offset is for stacked area chart
      posX = x(d),
          posY = y(d); // fix posY not to overflow opposite quadrant

      if (config.axis_rotated) {
        if (0 < d.value && posY < y0 || d.value < 0 && y0 < posY) {
          posY = y0;
        }
      } // 1 point that marks the area position


      return [[posX, offset], [posX, posY - (y0 - offset)], [posX, posY - (y0 - offset)], // needed for compatibility
      [posX, offset] // needed for compatibility
      ];
    };
  };

  ChartInternal.prototype.updateCircle = function (cx, cy) {
    var $$ = this;
    var mainCircle = $$.main.selectAll('.' + CLASS.circles).selectAll('.' + CLASS.circle).data($$.lineOrScatterData.bind($$));
    var mainCircleEnter = mainCircle.enter().append("circle").attr("class", $$.classCircle.bind($$)).attr("cx", cx).attr("cy", cy).attr("r", $$.pointR.bind($$)).style("fill", $$.color);
    $$.mainCircle = mainCircleEnter.merge(mainCircle).style("opacity", $$.initialOpacityForCircle.bind($$));
    mainCircle.exit().style("opacity", 0);
  };

  ChartInternal.prototype.redrawCircle = function (cx, cy, withTransition, transition) {
    var $$ = this,
        selectedCircles = $$.main.selectAll('.' + CLASS.selectedCircle);
    return [(withTransition ? $$.mainCircle.transition(transition) : $$.mainCircle).style('opacity', this.opacityForCircle.bind($$)).style("fill", $$.color).attr("cx", cx).attr("cy", cy), (withTransition ? selectedCircles.transition(transition) : selectedCircles).attr("cx", cx).attr("cy", cy)];
  };

  ChartInternal.prototype.circleX = function (d) {
    return d.x || d.x === 0 ? this.x(d.x) : null;
  };

  ChartInternal.prototype.updateCircleY = function () {
    var $$ = this,
        lineIndices,
        getPoints;

    if ($$.config.data_groups.length > 0) {
      lineIndices = $$.getShapeIndices($$.isLineType), getPoints = $$.generateGetLinePoints(lineIndices);

      $$.circleY = function (d, i) {
        return getPoints(d, i)[0][1];
      };
    } else {
      $$.circleY = function (d) {
        return $$.getYScale(d.id)(d.value);
      };
    }
  };

  ChartInternal.prototype.getCircles = function (i, id) {
    var $$ = this;
    return (id ? $$.main.selectAll('.' + CLASS.circles + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.circle + (isValue(i) ? '-' + i : ''));
  };

  ChartInternal.prototype.expandCircles = function (i, id, reset) {
    var $$ = this,
        r = $$.pointExpandedR.bind($$);

    if (reset) {
      $$.unexpandCircles();
    }

    $$.getCircles(i, id).classed(CLASS.EXPANDED, true).attr('r', r);
  };

  ChartInternal.prototype.unexpandCircles = function (i) {
    var $$ = this,
        r = $$.pointR.bind($$);
    $$.getCircles(i).filter(function () {
      return $$.d3.select(this).classed(CLASS.EXPANDED);
    }).classed(CLASS.EXPANDED, false).attr('r', r);
  };

  ChartInternal.prototype.pointR = function (d) {
    var $$ = this,
        config = $$.config;
    return $$.isStepType(d) ? 0 : isFunction(config.point_r) ? config.point_r(d) : config.point_r;
  };

  ChartInternal.prototype.pointExpandedR = function (d) {
    var $$ = this,
        config = $$.config;

    if (config.point_focus_expand_enabled) {
      return isFunction(config.point_focus_expand_r) ? config.point_focus_expand_r(d) : config.point_focus_expand_r ? config.point_focus_expand_r : $$.pointR(d) * 1.75;
    } else {
      return $$.pointR(d);
    }
  };

  ChartInternal.prototype.pointSelectR = function (d) {
    var $$ = this,
        config = $$.config;
    return isFunction(config.point_select_r) ? config.point_select_r(d) : config.point_select_r ? config.point_select_r : $$.pointR(d) * 4;
  };

  ChartInternal.prototype.isWithinCircle = function (that, r) {
    var d3 = this.d3,
        mouse = d3.mouse(that),
        d3_this = d3.select(that),
        cx = +d3_this.attr("cx"),
        cy = +d3_this.attr("cy");
    return Math.sqrt(Math.pow(cx - mouse[0], 2) + Math.pow(cy - mouse[1], 2)) < r;
  };

  ChartInternal.prototype.isWithinStep = function (that, y) {
    return Math.abs(y - this.d3.mouse(that)[1]) < 30;
  };

  ChartInternal.prototype.getCurrentWidth = function () {
    var $$ = this,
        config = $$.config;
    return config.size_width ? config.size_width : $$.getParentWidth();
  };

  ChartInternal.prototype.getCurrentHeight = function () {
    var $$ = this,
        config = $$.config,
        h = config.size_height ? config.size_height : $$.getParentHeight();
    return h > 0 ? h : 320 / ($$.hasType('gauge') && !config.gauge_fullCircle ? 2 : 1);
  };

  ChartInternal.prototype.getCurrentPaddingTop = function () {
    var $$ = this,
        config = $$.config,
        padding = isValue(config.padding_top) ? config.padding_top : 0;

    if ($$.title && $$.title.node()) {
      padding += $$.getTitlePadding();
    }

    return padding;
  };

  ChartInternal.prototype.getCurrentPaddingBottom = function () {
    var config = this.config;
    return isValue(config.padding_bottom) ? config.padding_bottom : 0;
  };

  ChartInternal.prototype.getCurrentPaddingLeft = function (withoutRecompute) {
    var $$ = this,
        config = $$.config;

    if (isValue(config.padding_left)) {
      return config.padding_left;
    } else if (config.axis_rotated) {
      return !config.axis_x_show || config.axis_x_inner ? 1 : Math.max(ceil10($$.getAxisWidthByAxisId('x', withoutRecompute)), 40);
    } else if (!config.axis_y_show || config.axis_y_inner) {
      // && !config.axis_rotated
      return $$.axis.getYAxisLabelPosition().isOuter ? 30 : 1;
    } else {
      return ceil10($$.getAxisWidthByAxisId('y', withoutRecompute));
    }
  };

  ChartInternal.prototype.getCurrentPaddingRight = function () {
    var $$ = this,
        config = $$.config,
        defaultPadding = 10,
        legendWidthOnRight = $$.isLegendRight ? $$.getLegendWidth() + 20 : 0;

    if (isValue(config.padding_right)) {
      return config.padding_right + 1; // 1 is needed not to hide tick line
    } else if (config.axis_rotated) {
      return defaultPadding + legendWidthOnRight;
    } else if (!config.axis_y2_show || config.axis_y2_inner) {
      // && !config.axis_rotated
      return 2 + legendWidthOnRight + ($$.axis.getY2AxisLabelPosition().isOuter ? 20 : 0);
    } else {
      return ceil10($$.getAxisWidthByAxisId('y2')) + legendWidthOnRight;
    }
  };

  ChartInternal.prototype.getParentRectValue = function (key) {
    var parent = this.selectChart.node(),
        v;

    while (parent && parent.tagName !== 'BODY') {
      try {
        v = parent.getBoundingClientRect()[key];
      } catch (e) {
        if (key === 'width') {
          // In IE in certain cases getBoundingClientRect
          // will cause an "unspecified error"
          v = parent.offsetWidth;
        }
      }

      if (v) {
        break;
      }

      parent = parent.parentNode;
    }

    return v;
  };

  ChartInternal.prototype.getParentWidth = function () {
    return this.getParentRectValue('width');
  };

  ChartInternal.prototype.getParentHeight = function () {
    var h = this.selectChart.style('height');
    return h.indexOf('px') > 0 ? +h.replace('px', '') : 0;
  };

  ChartInternal.prototype.getSvgLeft = function (withoutRecompute) {
    var $$ = this,
        config = $$.config,
        hasLeftAxisRect = config.axis_rotated || !config.axis_rotated && !config.axis_y_inner,
        leftAxisClass = config.axis_rotated ? CLASS.axisX : CLASS.axisY,
        leftAxis = $$.main.select('.' + leftAxisClass).node(),
        svgRect = leftAxis && hasLeftAxisRect ? leftAxis.getBoundingClientRect() : {
      right: 0
    },
        chartRect = $$.selectChart.node().getBoundingClientRect(),
        hasArc = $$.hasArcType(),
        svgLeft = svgRect.right - chartRect.left - (hasArc ? 0 : $$.getCurrentPaddingLeft(withoutRecompute));
    return svgLeft > 0 ? svgLeft : 0;
  };

  ChartInternal.prototype.getAxisWidthByAxisId = function (id, withoutRecompute) {
    var $$ = this,
        position = $$.axis.getLabelPositionById(id);
    return $$.axis.getMaxTickWidth(id, withoutRecompute) + (position.isInner ? 20 : 40);
  };

  ChartInternal.prototype.getHorizontalAxisHeight = function (axisId) {
    var $$ = this,
        config = $$.config,
        h = 30;

    if (axisId === 'x' && !config.axis_x_show) {
      return 8;
    }

    if (axisId === 'x' && config.axis_x_height) {
      return config.axis_x_height;
    }

    if (axisId === 'y' && !config.axis_y_show) {
      return config.legend_show && !$$.isLegendRight && !$$.isLegendInset ? 10 : 1;
    }

    if (axisId === 'y2' && !config.axis_y2_show) {
      return $$.rotated_padding_top;
    } // Calculate x axis height when tick rotated


    if (axisId === 'x' && !config.axis_rotated && config.axis_x_tick_rotate) {
      h = 30 + $$.axis.getMaxTickWidth(axisId) * Math.cos(Math.PI * (90 - Math.abs(config.axis_x_tick_rotate)) / 180);
    } // Calculate y axis height when tick rotated


    if (axisId === 'y' && config.axis_rotated && config.axis_y_tick_rotate) {
      h = 30 + $$.axis.getMaxTickWidth(axisId) * Math.cos(Math.PI * (90 - Math.abs(config.axis_y_tick_rotate)) / 180);
    }

    return h + ($$.axis.getLabelPositionById(axisId).isInner ? 0 : 10) + (axisId === 'y2' ? -10 : 0);
  };

  ChartInternal.prototype.initBrush = function (scale) {
    var $$ = this,
        d3 = $$.d3; // TODO: dynamically change brushY/brushX according to axis_rotated.

    $$.brush = ($$.config.axis_rotated ? d3.brushY() : d3.brushX()).on("brush", function () {
      var event = d3.event.sourceEvent;

      if (event && event.type === "zoom") {
        return;
      }

      $$.redrawForBrush();
    }).on("end", function () {
      var event = d3.event.sourceEvent;

      if (event && event.type === "zoom") {
        return;
      }

      if ($$.brush.empty() && event && event.type !== 'end') {
        $$.brush.clear();
      }
    });

    $$.brush.updateExtent = function () {
      var range = this.scale.range(),
          extent;

      if ($$.config.axis_rotated) {
        extent = [[0, range[0]], [$$.width2, range[1]]];
      } else {
        extent = [[range[0], 0], [range[1], $$.height2]];
      }

      this.extent(extent);
      return this;
    };

    $$.brush.updateScale = function (scale) {
      this.scale = scale;
      return this;
    };

    $$.brush.update = function (scale) {
      this.updateScale(scale || $$.subX).updateExtent();
      $$.context.select('.' + CLASS.brush).call(this);
    };

    $$.brush.clear = function () {
      $$.context.select('.' + CLASS.brush).call($$.brush.move, null);
    };

    $$.brush.selection = function () {
      return d3.brushSelection($$.context.select('.' + CLASS.brush).node());
    };

    $$.brush.selectionAsValue = function (selectionAsValue, withTransition) {
      var selection, brush;

      if (selectionAsValue) {
        if ($$.context) {
          selection = [this.scale(selectionAsValue[0]), this.scale(selectionAsValue[1])];
          brush = $$.context.select('.' + CLASS.brush);

          if (withTransition) {
            brush = brush.transition();
          }

          $$.brush.move(brush, selection);
        }

        return [];
      }

      selection = $$.brush.selection() || [0, 0];
      return [this.scale.invert(selection[0]), this.scale.invert(selection[1])];
    };

    $$.brush.empty = function () {
      var selection = $$.brush.selection();
      return !selection || selection[0] === selection[1];
    };

    return $$.brush.updateScale(scale);
  };

  ChartInternal.prototype.initSubchart = function () {
    var $$ = this,
        config = $$.config,
        context = $$.context = $$.svg.append("g").attr("transform", $$.getTranslate('context')),
        visibility = config.subchart_show ? 'visible' : 'hidden'; // set style

    context.style('visibility', visibility); // Define g for chart area

    context.append('g').attr("clip-path", $$.clipPathForSubchart).attr('class', CLASS.chart); // Define g for bar chart area

    context.select('.' + CLASS.chart).append("g").attr("class", CLASS.chartBars); // Define g for line chart area

    context.select('.' + CLASS.chart).append("g").attr("class", CLASS.chartLines); // Add extent rect for Brush

    context.append("g").attr("clip-path", $$.clipPath).attr("class", CLASS.brush); // ATTENTION: This must be called AFTER chart added
    // Add Axis

    $$.axes.subx = context.append("g").attr("class", CLASS.axisX).attr("transform", $$.getTranslate('subx')).attr("clip-path", config.axis_rotated ? "" : $$.clipPathForXAxis);
  };

  ChartInternal.prototype.initSubchartBrush = function () {
    var $$ = this; // Add extent rect for Brush

    $$.initBrush($$.subX).updateExtent();
    $$.context.select('.' + CLASS.brush).call($$.brush);
  };

  ChartInternal.prototype.updateTargetsForSubchart = function (targets) {
    var $$ = this,
        context = $$.context,
        config = $$.config,
        contextLineEnter,
        contextLine,
        contextBarEnter,
        contextBar,
        classChartBar = $$.classChartBar.bind($$),
        classBars = $$.classBars.bind($$),
        classChartLine = $$.classChartLine.bind($$),
        classLines = $$.classLines.bind($$),
        classAreas = $$.classAreas.bind($$);

    if (config.subchart_show) {
      //-- Bar --//
      contextBar = context.select('.' + CLASS.chartBars).selectAll('.' + CLASS.chartBar).data(targets);
      contextBarEnter = contextBar.enter().append('g').style('opacity', 0);
      contextBarEnter.merge(contextBar).attr('class', classChartBar); // Bars for each data

      contextBarEnter.append('g').attr("class", classBars); //-- Line --//

      contextLine = context.select('.' + CLASS.chartLines).selectAll('.' + CLASS.chartLine).data(targets);
      contextLineEnter = contextLine.enter().append('g').style('opacity', 0);
      contextLineEnter.merge(contextLine).attr('class', classChartLine); // Lines for each data

      contextLineEnter.append("g").attr("class", classLines); // Area

      contextLineEnter.append("g").attr("class", classAreas); //-- Brush --//

      context.selectAll('.' + CLASS.brush + ' rect').attr(config.axis_rotated ? "width" : "height", config.axis_rotated ? $$.width2 : $$.height2);
    }
  };

  ChartInternal.prototype.updateBarForSubchart = function (durationForExit) {
    var $$ = this;
    var contextBar = $$.context.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar).data($$.barData.bind($$));
    var contextBarEnter = contextBar.enter().append('path').attr("class", $$.classBar.bind($$)).style("stroke", 'none').style("fill", $$.color);
    contextBar.exit().transition().duration(durationForExit).style('opacity', 0).remove();
    $$.contextBar = contextBarEnter.merge(contextBar).style("opacity", $$.initialOpacity.bind($$));
  };

  ChartInternal.prototype.redrawBarForSubchart = function (drawBarOnSub, withTransition, duration) {
    (withTransition ? this.contextBar.transition(Math.random().toString()).duration(duration) : this.contextBar).attr('d', drawBarOnSub).style('opacity', 1);
  };

  ChartInternal.prototype.updateLineForSubchart = function (durationForExit) {
    var $$ = this;
    var contextLine = $$.context.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line).data($$.lineData.bind($$));
    var contextLineEnter = contextLine.enter().append('path').attr('class', $$.classLine.bind($$)).style('stroke', $$.color);
    contextLine.exit().transition().duration(durationForExit).style('opacity', 0).remove();
    $$.contextLine = contextLineEnter.merge(contextLine).style("opacity", $$.initialOpacity.bind($$));
  };

  ChartInternal.prototype.redrawLineForSubchart = function (drawLineOnSub, withTransition, duration) {
    (withTransition ? this.contextLine.transition(Math.random().toString()).duration(duration) : this.contextLine).attr("d", drawLineOnSub).style('opacity', 1);
  };

  ChartInternal.prototype.updateAreaForSubchart = function (durationForExit) {
    var $$ = this,
        d3 = $$.d3;
    var contextArea = $$.context.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area).data($$.lineData.bind($$));
    var contextAreaEnter = contextArea.enter().append('path').attr("class", $$.classArea.bind($$)).style("fill", $$.color).style("opacity", function () {
      $$.orgAreaOpacity = +d3.select(this).style('opacity');
      return 0;
    });
    contextArea.exit().transition().duration(durationForExit).style('opacity', 0).remove();
    $$.contextArea = contextAreaEnter.merge(contextArea).style("opacity", 0);
  };

  ChartInternal.prototype.redrawAreaForSubchart = function (drawAreaOnSub, withTransition, duration) {
    (withTransition ? this.contextArea.transition(Math.random().toString()).duration(duration) : this.contextArea).attr("d", drawAreaOnSub).style("fill", this.color).style("opacity", this.orgAreaOpacity);
  };

  ChartInternal.prototype.redrawSubchart = function (withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices) {
    var $$ = this,
        d3 = $$.d3,
        config = $$.config,
        drawAreaOnSub,
        drawBarOnSub,
        drawLineOnSub;
    $$.context.style('visibility', config.subchart_show ? 'visible' : 'hidden'); // subchart

    if (config.subchart_show) {
      // reflect main chart to extent on subchart if zoomed
      if (d3.event && d3.event.type === 'zoom') {
        $$.brush.selectionAsValue($$.x.orgDomain());
      } // update subchart elements if needed


      if (withSubchart) {
        // extent rect
        if (!$$.brush.empty()) {
          $$.brush.selectionAsValue($$.x.orgDomain());
        } // setup drawer - MEMO: this must be called after axis updated


        drawAreaOnSub = $$.generateDrawArea(areaIndices, true);
        drawBarOnSub = $$.generateDrawBar(barIndices, true);
        drawLineOnSub = $$.generateDrawLine(lineIndices, true);
        $$.updateBarForSubchart(duration);
        $$.updateLineForSubchart(duration);
        $$.updateAreaForSubchart(duration);
        $$.redrawBarForSubchart(drawBarOnSub, duration, duration);
        $$.redrawLineForSubchart(drawLineOnSub, duration, duration);
        $$.redrawAreaForSubchart(drawAreaOnSub, duration, duration);
      }
    }
  };

  ChartInternal.prototype.redrawForBrush = function () {
    var $$ = this,
        x = $$.x,
        d3 = $$.d3,
        s;
    $$.redraw({
      withTransition: false,
      withY: $$.config.zoom_rescale,
      withSubchart: false,
      withUpdateXDomain: true,
      withEventRect: false,
      withDimension: false
    }); // update zoom transation binded to event rect

    s = d3.event.selection || $$.brush.scale.range();
    $$.main.select('.' + CLASS.eventRect).call($$.zoom.transform, d3.zoomIdentity.scale($$.width / (s[1] - s[0])).translate(-s[0], 0));
    $$.config.subchart_onbrush.call($$.api, x.orgDomain());
  };

  ChartInternal.prototype.transformContext = function (withTransition, transitions) {
    var $$ = this,
        subXAxis;

    if (transitions && transitions.axisSubX) {
      subXAxis = transitions.axisSubX;
    } else {
      subXAxis = $$.context.select('.' + CLASS.axisX);

      if (withTransition) {
        subXAxis = subXAxis.transition();
      }
    }

    $$.context.attr("transform", $$.getTranslate('context'));
    subXAxis.attr("transform", $$.getTranslate('subx'));
  };

  ChartInternal.prototype.getDefaultSelection = function () {
    var $$ = this,
        config = $$.config,
        selection = isFunction(config.axis_x_selection) ? config.axis_x_selection($$.getXDomain($$.data.targets)) : config.axis_x_selection;

    if ($$.isTimeSeries()) {
      selection = [$$.parseDate(selection[0]), $$.parseDate(selection[1])];
    }

    return selection;
  };

  ChartInternal.prototype.initText = function () {
    var $$ = this;
    $$.main.select('.' + CLASS.chart).append("g").attr("class", CLASS.chartTexts);
    $$.mainText = $$.d3.selectAll([]);
  };

  ChartInternal.prototype.updateTargetsForText = function (targets) {
    var $$ = this,
        classChartText = $$.classChartText.bind($$),
        classTexts = $$.classTexts.bind($$),
        classFocus = $$.classFocus.bind($$);
    var mainText = $$.main.select('.' + CLASS.chartTexts).selectAll('.' + CLASS.chartText).data(targets);
    var mainTextEnter = mainText.enter().append('g').attr('class', classChartText).style('opacity', 0).style("pointer-events", "none");
    mainTextEnter.append('g').attr('class', classTexts);
    mainTextEnter.merge(mainText).attr('class', function (d) {
      return classChartText(d) + classFocus(d);
    });
  };

  ChartInternal.prototype.updateText = function (xForText, yForText, durationForExit) {
    var $$ = this,
        config = $$.config,
        barOrLineData = $$.barOrLineData.bind($$),
        classText = $$.classText.bind($$);
    var mainText = $$.main.selectAll('.' + CLASS.texts).selectAll('.' + CLASS.text).data(barOrLineData);
    var mainTextEnter = mainText.enter().append('text').attr("class", classText).attr('text-anchor', function (d) {
      return config.axis_rotated ? d.value < 0 ? 'end' : 'start' : 'middle';
    }).style("stroke", 'none').attr('x', xForText).attr('y', yForText).style("fill", function (d) {
      return $$.color(d);
    }).style("fill-opacity", 0);
    $$.mainText = mainTextEnter.merge(mainText).text(function (d, i, j) {
      return $$.dataLabelFormat(d.id)(d.value, d.id, i, j);
    });
    mainText.exit().transition().duration(durationForExit).style('fill-opacity', 0).remove();
  };

  ChartInternal.prototype.redrawText = function (xForText, yForText, forFlow, withTransition, transition) {
    return [(withTransition ? this.mainText.transition(transition) : this.mainText).attr('x', xForText).attr('y', yForText).style("fill", this.color).style("fill-opacity", forFlow ? 0 : this.opacityForText.bind(this))];
  };

  ChartInternal.prototype.getTextRect = function (text, cls, element) {
    var dummy = this.d3.select('body').append('div').classed('c3', true),
        svg = dummy.append("svg").style('visibility', 'hidden').style('position', 'fixed').style('top', 0).style('left', 0),
        font = this.d3.select(element).style('font'),
        rect;
    svg.selectAll('.dummy').data([text]).enter().append('text').classed(cls ? cls : "", true).style('font', font).text(text).each(function () {
      rect = this.getBoundingClientRect();
    });
    dummy.remove();
    return rect;
  };

  ChartInternal.prototype.generateXYForText = function (areaIndices, barIndices, lineIndices, forX) {
    var $$ = this,
        getAreaPoints = $$.generateGetAreaPoints(areaIndices, false),
        getBarPoints = $$.generateGetBarPoints(barIndices, false),
        getLinePoints = $$.generateGetLinePoints(lineIndices, false),
        getter = forX ? $$.getXForText : $$.getYForText;
    return function (d, i) {
      var getPoints = $$.isAreaType(d) ? getAreaPoints : $$.isBarType(d) ? getBarPoints : getLinePoints;
      return getter.call($$, getPoints(d, i), d, this);
    };
  };

  ChartInternal.prototype.getXForText = function (points, d, textElement) {
    var $$ = this,
        box = textElement.getBoundingClientRect(),
        xPos,
        padding;

    if ($$.config.axis_rotated) {
      padding = $$.isBarType(d) ? 4 : 6;
      xPos = points[2][1] + padding * (d.value < 0 ? -1 : 1);
    } else {
      xPos = $$.hasType('bar') ? (points[2][0] + points[0][0]) / 2 : points[0][0];
    } // show labels regardless of the domain if value is null


    if (d.value === null) {
      if (xPos > $$.width) {
        xPos = $$.width - box.width;
      } else if (xPos < 0) {
        xPos = 4;
      }
    }

    return xPos;
  };

  ChartInternal.prototype.getYForText = function (points, d, textElement) {
    var $$ = this,
        box = textElement.getBoundingClientRect(),
        yPos;

    if ($$.config.axis_rotated) {
      yPos = (points[0][0] + points[2][0] + box.height * 0.6) / 2;
    } else {
      yPos = points[2][1];

      if (d.value < 0 || d.value === 0 && !$$.hasPositiveValue) {
        yPos += box.height;

        if ($$.isBarType(d) && $$.isSafari()) {
          yPos -= 3;
        } else if (!$$.isBarType(d) && $$.isChrome()) {
          yPos += 3;
        }
      } else {
        yPos += $$.isBarType(d) ? -3 : -6;
      }
    } // show labels regardless of the domain if value is null


    if (d.value === null && !$$.config.axis_rotated) {
      if (yPos < box.height) {
        yPos = box.height;
      } else if (yPos > this.height) {
        yPos = this.height - 4;
      }
    }

    return yPos;
  };

  ChartInternal.prototype.initTitle = function () {
    var $$ = this;
    $$.title = $$.svg.append("text").text($$.config.title_text).attr("class", $$.CLASS.title);
  };

  ChartInternal.prototype.redrawTitle = function () {
    var $$ = this;
    $$.title.attr("x", $$.xForTitle.bind($$)).attr("y", $$.yForTitle.bind($$));
  };

  ChartInternal.prototype.xForTitle = function () {
    var $$ = this,
        config = $$.config,
        position = config.title_position || 'left',
        x;

    if (position.indexOf('right') >= 0) {
      x = $$.currentWidth - $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).width - config.title_padding.right;
    } else if (position.indexOf('center') >= 0) {
      x = ($$.currentWidth - $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).width) / 2;
    } else {
      // left
      x = config.title_padding.left;
    }

    return x;
  };

  ChartInternal.prototype.yForTitle = function () {
    var $$ = this;
    return $$.config.title_padding.top + $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).height;
  };

  ChartInternal.prototype.getTitlePadding = function () {
    var $$ = this;
    return $$.yForTitle() + $$.config.title_padding.bottom;
  };

  ChartInternal.prototype.initTooltip = function () {
    var $$ = this,
        config = $$.config,
        i;
    $$.tooltip = $$.selectChart.style("position", "relative").append("div").attr('class', CLASS.tooltipContainer).style("position", "absolute").style("pointer-events", "none").style("display", "none"); // Show tooltip if needed

    if (config.tooltip_init_show) {
      if ($$.isTimeSeries() && isString(config.tooltip_init_x)) {
        config.tooltip_init_x = $$.parseDate(config.tooltip_init_x);

        for (i = 0; i < $$.data.targets[0].values.length; i++) {
          if ($$.data.targets[0].values[i].x - config.tooltip_init_x === 0) {
            break;
          }
        }

        config.tooltip_init_x = i;
      }

      $$.tooltip.html(config.tooltip_contents.call($$, $$.data.targets.map(function (d) {
        return $$.addName(d.values[config.tooltip_init_x]);
      }), $$.axis.getXAxisTickFormat(), $$.getYFormat($$.hasArcType()), $$.color));
      $$.tooltip.style("top", config.tooltip_init_position.top).style("left", config.tooltip_init_position.left).style("display", "block");
    }
  };

  ChartInternal.prototype.getTooltipSortFunction = function () {
    var $$ = this,
        config = $$.config;

    if (config.data_groups.length === 0 || config.tooltip_order !== undefined) {
      // if data are not grouped or if an order is specified
      // for the tooltip values we sort them by their values
      var order = config.tooltip_order;

      if (order === undefined) {
        order = config.data_order;
      }

      var valueOf = function valueOf(obj) {
        return obj ? obj.value : null;
      }; // if data are not grouped, we sort them by their value


      if (isString(order) && order.toLowerCase() === 'asc') {
        return function (a, b) {
          return valueOf(a) - valueOf(b);
        };
      } else if (isString(order) && order.toLowerCase() === 'desc') {
        return function (a, b) {
          return valueOf(b) - valueOf(a);
        };
      } else if (isFunction(order)) {
        // if the function is from data_order we need
        // to wrap the returned function in order to format
        // the sorted value to the expected format
        var sortFunction = order;

        if (config.tooltip_order === undefined) {
          sortFunction = function sortFunction(a, b) {
            return order(a ? {
              id: a.id,
              values: [a]
            } : null, b ? {
              id: b.id,
              values: [b]
            } : null);
          };
        }

        return sortFunction;
      } else if (isArray(order)) {
        return function (a, b) {
          return order.indexOf(a.id) - order.indexOf(b.id);
        };
      }
    } else {
      // if data are grouped, we follow the order of grouped targets
      var ids = $$.orderTargets($$.data.targets).map(function (i) {
        return i.id;
      }); // if it was either asc or desc we need to invert the order
      // returned by orderTargets

      if ($$.isOrderAsc() || $$.isOrderDesc()) {
        ids = ids.reverse();
      }

      return function (a, b) {
        return ids.indexOf(a.id) - ids.indexOf(b.id);
      };
    }
  };

  ChartInternal.prototype.getTooltipContent = function (d, defaultTitleFormat, defaultValueFormat, color) {
    var $$ = this,
        config = $$.config,
        titleFormat = config.tooltip_format_title || defaultTitleFormat,
        nameFormat = config.tooltip_format_name || function (name) {
      return name;
    },
        valueFormat = config.tooltip_format_value || defaultValueFormat,
        text,
        i,
        title,
        value,
        name,
        bgcolor;

    var tooltipSortFunction = this.getTooltipSortFunction();

    if (tooltipSortFunction) {
      d.sort(tooltipSortFunction);
    }

    for (i = 0; i < d.length; i++) {
      if (!(d[i] && (d[i].value || d[i].value === 0))) {
        continue;
      }

      if (!text) {
        title = sanitise(titleFormat ? titleFormat(d[i].x) : d[i].x);
        text = "<table class='" + $$.CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : "");
      }

      value = sanitise(valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index, d));

      if (value !== undefined) {
        // Skip elements when their name is set to null
        if (d[i].name === null) {
          continue;
        }

        name = sanitise(nameFormat(d[i].name, d[i].ratio, d[i].id, d[i].index));
        bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);
        text += "<tr class='" + $$.CLASS.tooltipName + "-" + $$.getTargetSelectorSuffix(d[i].id) + "'>";
        text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>";
        text += "<td class='value'>" + value + "</td>";
        text += "</tr>";
      }
    }

    return text + "</table>";
  };

  ChartInternal.prototype.tooltipPosition = function (dataToShow, tWidth, tHeight, element) {
    var $$ = this,
        config = $$.config,
        d3 = $$.d3;
    var svgLeft, tooltipLeft, tooltipRight, tooltipTop, chartRight;
    var forArc = $$.hasArcType(),
        mouse = d3.mouse(element); // Determin tooltip position

    if (forArc) {
      tooltipLeft = ($$.width - ($$.isLegendRight ? $$.getLegendWidth() : 0)) / 2 + mouse[0];
      tooltipTop = ($$.hasType('gauge') ? $$.height : $$.height / 2) + mouse[1] + 20;
    } else {
      svgLeft = $$.getSvgLeft(true);

      if (config.axis_rotated) {
        tooltipLeft = svgLeft + mouse[0] + 100;
        tooltipRight = tooltipLeft + tWidth;
        chartRight = $$.currentWidth - $$.getCurrentPaddingRight();
        tooltipTop = $$.x(dataToShow[0].x) + 20;
      } else {
        tooltipLeft = svgLeft + $$.getCurrentPaddingLeft(true) + $$.x(dataToShow[0].x) + 20;
        tooltipRight = tooltipLeft + tWidth;
        chartRight = svgLeft + $$.currentWidth - $$.getCurrentPaddingRight();
        tooltipTop = mouse[1] + 15;
      }

      if (tooltipRight > chartRight) {
        // 20 is needed for Firefox to keep tooltip width
        tooltipLeft -= tooltipRight - chartRight + 20;
      }

      if (tooltipTop + tHeight > $$.currentHeight) {
        tooltipTop -= tHeight + 30;
      }
    }

    if (tooltipTop < 0) {
      tooltipTop = 0;
    }

    return {
      top: tooltipTop,
      left: tooltipLeft
    };
  };

  ChartInternal.prototype.showTooltip = function (selectedData, element) {
    var $$ = this,
        config = $$.config;
    var tWidth, tHeight, position;
    var forArc = $$.hasArcType(),
        dataToShow = selectedData.filter(function (d) {
      return d && isValue(d.value);
    }),
        positionFunction = config.tooltip_position || ChartInternal.prototype.tooltipPosition;

    if (dataToShow.length === 0 || !config.tooltip_show) {
      return;
    }

    $$.tooltip.html(config.tooltip_contents.call($$, selectedData, $$.axis.getXAxisTickFormat(), $$.getYFormat(forArc), $$.color)).style("display", "block"); // Get tooltip dimensions

    tWidth = $$.tooltip.property('offsetWidth');
    tHeight = $$.tooltip.property('offsetHeight');
    position = positionFunction.call(this, dataToShow, tWidth, tHeight, element); // Set tooltip

    $$.tooltip.style("top", position.top + "px").style("left", position.left + 'px');
  };

  ChartInternal.prototype.hideTooltip = function () {
    this.tooltip.style("display", "none");
  };

  ChartInternal.prototype.setTargetType = function (targetIds, type) {
    var $$ = this,
        config = $$.config;
    $$.mapToTargetIds(targetIds).forEach(function (id) {
      $$.withoutFadeIn[id] = type === config.data_types[id];
      config.data_types[id] = type;
    });

    if (!targetIds) {
      config.data_type = type;
    }
  };

  ChartInternal.prototype.hasType = function (type, targets) {
    var $$ = this,
        types = $$.config.data_types,
        has = false;
    targets = targets || $$.data.targets;

    if (targets && targets.length) {
      targets.forEach(function (target) {
        var t = types[target.id];

        if (t && t.indexOf(type) >= 0 || !t && type === 'line') {
          has = true;
        }
      });
    } else if (Object.keys(types).length) {
      Object.keys(types).forEach(function (id) {
        if (types[id] === type) {
          has = true;
        }
      });
    } else {
      has = $$.config.data_type === type;
    }

    return has;
  };

  ChartInternal.prototype.hasArcType = function (targets) {
    return this.hasType('pie', targets) || this.hasType('donut', targets) || this.hasType('gauge', targets);
  };

  ChartInternal.prototype.isLineType = function (d) {
    var config = this.config,
        id = isString(d) ? d : d.id;
    return !config.data_types[id] || ['line', 'spline', 'area', 'area-spline', 'step', 'area-step'].indexOf(config.data_types[id]) >= 0;
  };

  ChartInternal.prototype.isStepType = function (d) {
    var id = isString(d) ? d : d.id;
    return ['step', 'area-step'].indexOf(this.config.data_types[id]) >= 0;
  };

  ChartInternal.prototype.isSplineType = function (d) {
    var id = isString(d) ? d : d.id;
    return ['spline', 'area-spline'].indexOf(this.config.data_types[id]) >= 0;
  };

  ChartInternal.prototype.isAreaType = function (d) {
    var id = isString(d) ? d : d.id;
    return ['area', 'area-spline', 'area-step'].indexOf(this.config.data_types[id]) >= 0;
  };

  ChartInternal.prototype.isBarType = function (d) {
    var id = isString(d) ? d : d.id;
    return this.config.data_types[id] === 'bar';
  };

  ChartInternal.prototype.isScatterType = function (d) {
    var id = isString(d) ? d : d.id;
    return this.config.data_types[id] === 'scatter';
  };

  ChartInternal.prototype.isPieType = function (d) {
    var id = isString(d) ? d : d.id;
    return this.config.data_types[id] === 'pie';
  };

  ChartInternal.prototype.isGaugeType = function (d) {
    var id = isString(d) ? d : d.id;
    return this.config.data_types[id] === 'gauge';
  };

  ChartInternal.prototype.isDonutType = function (d) {
    var id = isString(d) ? d : d.id;
    return this.config.data_types[id] === 'donut';
  };

  ChartInternal.prototype.isArcType = function (d) {
    return this.isPieType(d) || this.isDonutType(d) || this.isGaugeType(d);
  };

  ChartInternal.prototype.lineData = function (d) {
    return this.isLineType(d) ? [d] : [];
  };

  ChartInternal.prototype.arcData = function (d) {
    return this.isArcType(d.data) ? [d] : [];
  };
  /* not used
   function scatterData(d) {
   return isScatterType(d) ? d.values : [];
   }
   */


  ChartInternal.prototype.barData = function (d) {
    return this.isBarType(d) ? d.values : [];
  };

  ChartInternal.prototype.lineOrScatterData = function (d) {
    return this.isLineType(d) || this.isScatterType(d) ? d.values : [];
  };

  ChartInternal.prototype.barOrLineData = function (d) {
    return this.isBarType(d) || this.isLineType(d) ? d.values : [];
  };

  ChartInternal.prototype.isSafari = function () {
    var ua = window.navigator.userAgent;
    return ua.indexOf('Safari') >= 0 && ua.indexOf('Chrome') < 0;
  };

  ChartInternal.prototype.isChrome = function () {
    var ua = window.navigator.userAgent;
    return ua.indexOf('Chrome') >= 0;
  };

  ChartInternal.prototype.initZoom = function () {
    var $$ = this,
        d3 = $$.d3,
        config = $$.config,
        startEvent;
    $$.zoom = d3.zoom().on("start", function () {
      if (config.zoom_type !== 'scroll') {
        return;
      }

      var e = d3.event.sourceEvent;

      if (e && e.type === "brush") {
        return;
      }

      startEvent = e;
      config.zoom_onzoomstart.call($$.api, e);
    }).on("zoom", function () {
      if (config.zoom_type !== 'scroll') {
        return;
      }

      var e = d3.event.sourceEvent;

      if (e && e.type === "brush") {
        return;
      }

      $$.redrawForZoom();
      config.zoom_onzoom.call($$.api, $$.x.orgDomain());
    }).on('end', function () {
      if (config.zoom_type !== 'scroll') {
        return;
      }

      var e = d3.event.sourceEvent;

      if (e && e.type === "brush") {
        return;
      } // if click, do nothing. otherwise, click interaction will be canceled.


      if (e && startEvent.clientX === e.clientX && startEvent.clientY === e.clientY) {
        return;
      }

      config.zoom_onzoomend.call($$.api, $$.x.orgDomain());
    });

    $$.zoom.updateDomain = function () {
      if (d3.event && d3.event.transform) {
        $$.x.domain(d3.event.transform.rescaleX($$.subX).domain());
      }

      return this;
    };

    $$.zoom.updateExtent = function () {
      this.scaleExtent([1, Infinity]).translateExtent([[0, 0], [$$.width, $$.height]]).extent([[0, 0], [$$.width, $$.height]]);
      return this;
    };

    $$.zoom.update = function () {
      return this.updateExtent().updateDomain();
    };

    return $$.zoom.updateExtent();
  };

  ChartInternal.prototype.zoomTransform = function (range) {
    var $$ = this,
        s = [$$.x(range[0]), $$.x(range[1])];
    return $$.d3.zoomIdentity.scale($$.width / (s[1] - s[0])).translate(-s[0], 0);
  };

  ChartInternal.prototype.initDragZoom = function () {
    var $$ = this;
    var d3 = $$.d3;
    var config = $$.config;
    var context = $$.context = $$.svg;
    var brushXPos = $$.margin.left + 20.5;
    var brushYPos = $$.margin.top + 0.5;

    if (!(config.zoom_type === 'drag' && config.zoom_enabled)) {
      return;
    }

    var getZoomedDomain = function getZoomedDomain(selection) {
      return selection && selection.map(function (x) {
        return $$.x.invert(x);
      });
    };

    var brush = $$.dragZoomBrush = d3.brushX().on("start", function () {
      $$.api.unzoom();
      $$.svg.select("." + CLASS.dragZoom).classed("disabled", false);
      config.zoom_onzoomstart.call($$.api, d3.event.sourceEvent);
    }).on("brush", function () {
      config.zoom_onzoom.call($$.api, getZoomedDomain(d3.event.selection));
    }).on("end", function () {
      if (d3.event.selection == null) {
        return;
      }

      var zoomedDomain = getZoomedDomain(d3.event.selection);

      if (!config.zoom_disableDefaultBehavior) {
        $$.api.zoom(zoomedDomain);
      }

      $$.svg.select("." + CLASS.dragZoom).classed("disabled", true);
      config.zoom_onzoomend.call($$.api, zoomedDomain);
    });
    context.append("g").classed(CLASS.dragZoom, true).attr("clip-path", $$.clipPath).attr("transform", "translate(" + brushXPos + "," + brushYPos + ")").call(brush);
  };

  ChartInternal.prototype.getZoomDomain = function () {
    var $$ = this,
        config = $$.config,
        d3 = $$.d3,
        min = d3.min([$$.orgXDomain[0], config.zoom_x_min]),
        max = d3.max([$$.orgXDomain[1], config.zoom_x_max]);
    return [min, max];
  };

  ChartInternal.prototype.redrawForZoom = function () {
    var $$ = this,
        d3 = $$.d3,
        config = $$.config,
        zoom = $$.zoom,
        x = $$.x;

    if (!config.zoom_enabled) {
      return;
    }

    if ($$.filterTargetsToShow($$.data.targets).length === 0) {
      return;
    }

    zoom.update();

    if (config.zoom_disableDefaultBehavior) {
      return;
    }

    if ($$.isCategorized() && x.orgDomain()[0] === $$.orgXDomain[0]) {
      x.domain([$$.orgXDomain[0] - 1e-10, x.orgDomain()[1]]);
    }

    $$.redraw({
      withTransition: false,
      withY: config.zoom_rescale,
      withSubchart: false,
      withEventRect: false,
      withDimension: false
    });

    if (d3.event.sourceEvent && d3.event.sourceEvent.type === 'mousemove') {
      $$.cancelClick = true;
    }
  };

  return c3;

})));
LICENSE000064400000002116151701472650005561 0ustar00The MIT License (MIT)

Copyright (c) 2013 Masayuki Tanaka

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
c3.min.css000064400000004522151701472650006360 0ustar00.c3 svg{font:10px sans-serif;-webkit-tap-highlight-color:transparent}.c3 line,.c3 path{fill:none;stroke:#000}.c3 text{-webkit-user-select:none;-moz-user-select:none;user-select:none}.c3-bars path,.c3-event-rect,.c3-legend-item-tile,.c3-xgrid-focus,.c3-ygrid{shape-rendering:crispEdges}.c3-chart-arc path{stroke:#fff}.c3-chart-arc rect{stroke:#fff;stroke-width:1}.c3-chart-arc text{fill:#fff;font-size:13px}.c3-grid line{stroke:#aaa}.c3-grid text{fill:#aaa}.c3-xgrid,.c3-ygrid{stroke-dasharray:3 3}.c3-text.c3-empty{fill:grey;font-size:2em}.c3-line{stroke-width:1px}.c3-circle._expanded_{stroke-width:1px;stroke:#fff}.c3-selected-circle{fill:#fff;stroke-width:2px}.c3-bar{stroke-width:0}.c3-bar._expanded_{fill-opacity:1;fill-opacity:.75}.c3-target.c3-focused{opacity:1}.c3-target.c3-focused path.c3-line,.c3-target.c3-focused path.c3-step{stroke-width:2px}.c3-target.c3-defocused{opacity:.3!important}.c3-region{fill:#4682b4;fill-opacity:.1}.c3-brush .extent{fill-opacity:.1}.c3-legend-item{font-size:12px}.c3-legend-item-hidden{opacity:.15}.c3-legend-background{opacity:.75;fill:#fff;stroke:#d3d3d3;stroke-width:1}.c3-title{font:14px sans-serif}.c3-tooltip-container{z-index:10}.c3-tooltip{border-collapse:collapse;border-spacing:0;background-color:#fff;empty-cells:show;-webkit-box-shadow:7px 7px 12px -9px #777;-moz-box-shadow:7px 7px 12px -9px #777;box-shadow:7px 7px 12px -9px #777;opacity:.9}.c3-tooltip tr{border:1px solid #ccc}.c3-tooltip th{background-color:#aaa;font-size:14px;padding:2px 5px;text-align:left;color:#fff}.c3-tooltip td{font-size:13px;padding:3px 6px;background-color:#fff;border-left:1px dotted #999}.c3-tooltip td>span{display:inline-block;width:10px;height:10px;margin-right:6px}.c3-tooltip td.value{text-align:right}.c3-area{stroke-width:0;opacity:.2}.c3-chart-arcs-title{dominant-baseline:middle;font-size:1.3em}.c3-chart-arcs .c3-chart-arcs-background{fill:#e0e0e0;stroke:#fff}.c3-chart-arcs .c3-chart-arcs-gauge-unit{fill:#000;font-size:16px}.c3-chart-arcs .c3-chart-arcs-gauge-max{fill:#777}.c3-chart-arcs .c3-chart-arcs-gauge-min{fill:#777}.c3-chart-arc .c3-gauge-value{fill:#000}.c3-chart-arc.c3-target g path{opacity:1}.c3-chart-arc.c3-target.c3-focused g path{opacity:1}.c3-drag-zoom.enabled{pointer-events:all!important;visibility:visible}.c3-drag-zoom.disabled{pointer-events:none!important;visibility:hidden}.c3-drag-zoom .extent{fill-opacity:.1}README.md000064400000006411151701472650006035 0ustar00# c3

[![CircleCI](https://circleci.com/gh/c3js/c3.svg?style=shield)](https://circleci.com/gh/c3js/c3)
[![license](http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](https://github.com/c3js/c3/blob/master/LICENSE)
[![codecov.io](https://codecov.io/github/c3js/c3/coverage.svg?branch=master)](https://codecov.io/github/c3js/c3?branch=master)
[![Greenkeeper badge](https://badges.greenkeeper.io/c3js/c3.svg)](https://greenkeeper.io/)
[![jsDelivr Hits](https://data.jsdelivr.com/v1/package/npm/c3/badge?style=rounded)](https://www.jsdelivr.com/package/npm/c3)

> c3 is a D3-based reusable chart library that enables deeper integration of charts into web applications.

Follow the link for more information: [http://c3js.org](http://c3js.org/)

## Tutorial and Examples

+ [Getting Started](http://c3js.org/gettingstarted.html)
+ [Examples](http://c3js.org/examples.html)

Additional samples can be found in this repository:
+ [https://github.com/c3js/c3/tree/master/htdocs/samples](https://github.com/c3js/c3/tree/master/htdocs/samples)

You can run these samples as:
```
$ npm run serve-static
```

## Google Group
For general C3.js-related discussion, please visit our [Google Group at https://groups.google.com/forum/#!forum/c3js](https://groups.google.com/forum/#!forum/c3js).

## Gitter
[![Join the chat at https://gitter.im/c3js/c3](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/c3js/c3?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

## Using the issue queue
The [issue queue](https://github.com/c3js/c3/issues) is to be used for reporting defects and problems with C3.js, in addition to feature requests and ideas. It is **not** a catch-all support forum. **For general support enquiries, please use the [Google Group](https://groups.google.com/forum/#!forum/c3js) at https://groups.google.com/forum/#!forum/c3js.** All questions involving the interplay between C3.js and any other library (such as AngularJS) should be posted there first!

Before reporting an issue, please do the following:

1. [Search for existing issues](https://github.com/c3js/c3/issues) to ensure you're not posting a duplicate.

1.  [Search the Google Group](https://groups.google.com/forum/#!forum/c3js) to ensure it hasn't been addressed there already.

1. Create a JSFiddle or Plunkr highlighting the issue. Please don't include any unnecessary dependencies so we can isolate that the issue is in fact with C3. *Please be advised that custom CSS can modify C3.js output!*

1. When posting the issue, please use a descriptive title and include the version of C3 (or, if cloning from Git, the commit hash — C3 is under active development and the master branch contains the latest dev commits!), along with any platform/browser/OS information that may be relevant.

## Pull requests
Pull requests are welcome, though please post an issue first to see whether such a change is desirable.
If you choose to submit a pull request, please do not bump the version number unless asked to, and please include test cases for any new features. Squash all your commits as well, please.

## Playground
Please fork this fiddle:

+ http://jsfiddle.net/7kYJu/4742/

## Dependency

+ [D3.js](https://github.com/mbostock/d3) `^5.0.0`

## License

MIT
c3.css000064400000006710151701472650005577 0ustar00/*-- Chart --*/
.c3 svg {
  font: 10px sans-serif;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}

.c3 path, .c3 line {
  fill: none;
  stroke: #000;
}

.c3 text {
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
}

.c3-legend-item-tile,
.c3-xgrid-focus,
.c3-ygrid,
.c3-event-rect,
.c3-bars path {
  shape-rendering: crispEdges;
}

.c3-chart-arc path {
  stroke: #fff;
}

.c3-chart-arc rect {
  stroke: white;
  stroke-width: 1;
}

.c3-chart-arc text {
  fill: #fff;
  font-size: 13px;
}

/*-- Axis --*/
/*-- Grid --*/
.c3-grid line {
  stroke: #aaa;
}

.c3-grid text {
  fill: #aaa;
}

.c3-xgrid, .c3-ygrid {
  stroke-dasharray: 3 3;
}

/*-- Text on Chart --*/
.c3-text.c3-empty {
  fill: #808080;
  font-size: 2em;
}

/*-- Line --*/
.c3-line {
  stroke-width: 1px;
}

/*-- Point --*/
.c3-circle._expanded_ {
  stroke-width: 1px;
  stroke: white;
}

.c3-selected-circle {
  fill: white;
  stroke-width: 2px;
}

/*-- Bar --*/
.c3-bar {
  stroke-width: 0;
}

.c3-bar._expanded_ {
  fill-opacity: 1;
  fill-opacity: 0.75;
}

/*-- Focus --*/
.c3-target.c3-focused {
  opacity: 1;
}

.c3-target.c3-focused path.c3-line, .c3-target.c3-focused path.c3-step {
  stroke-width: 2px;
}

.c3-target.c3-defocused {
  opacity: 0.3 !important;
}

/*-- Region --*/
.c3-region {
  fill: steelblue;
  fill-opacity: 0.1;
}

/*-- Brush --*/
.c3-brush .extent {
  fill-opacity: 0.1;
}

/*-- Select - Drag --*/
/*-- Legend --*/
.c3-legend-item {
  font-size: 12px;
}

.c3-legend-item-hidden {
  opacity: 0.15;
}

.c3-legend-background {
  opacity: 0.75;
  fill: white;
  stroke: lightgray;
  stroke-width: 1;
}

/*-- Title --*/
.c3-title {
  font: 14px sans-serif;
}

/*-- Tooltip --*/
.c3-tooltip-container {
  z-index: 10;
}

.c3-tooltip {
  border-collapse: collapse;
  border-spacing: 0;
  background-color: #fff;
  empty-cells: show;
  -webkit-box-shadow: 7px 7px 12px -9px #777777;
  -moz-box-shadow: 7px 7px 12px -9px #777777;
  box-shadow: 7px 7px 12px -9px #777777;
  opacity: 0.9;
}

.c3-tooltip tr {
  border: 1px solid #CCC;
}

.c3-tooltip th {
  background-color: #aaa;
  font-size: 14px;
  padding: 2px 5px;
  text-align: left;
  color: #FFF;
}

.c3-tooltip td {
  font-size: 13px;
  padding: 3px 6px;
  background-color: #fff;
  border-left: 1px dotted #999;
}

.c3-tooltip td > span {
  display: inline-block;
  width: 10px;
  height: 10px;
  margin-right: 6px;
}

.c3-tooltip td.value {
  text-align: right;
}

/*-- Area --*/
.c3-area {
  stroke-width: 0;
  opacity: 0.2;
}

/*-- Arc --*/
.c3-chart-arcs-title {
  dominant-baseline: middle;
  font-size: 1.3em;
}

.c3-chart-arcs .c3-chart-arcs-background {
  fill: #e0e0e0;
  stroke: #FFF;
}

.c3-chart-arcs .c3-chart-arcs-gauge-unit {
  fill: #000;
  font-size: 16px;
}

.c3-chart-arcs .c3-chart-arcs-gauge-max {
  fill: #777;
}

.c3-chart-arcs .c3-chart-arcs-gauge-min {
  fill: #777;
}

.c3-chart-arc .c3-gauge-value {
  fill: #000;
  /*  font-size: 28px !important;*/
}

.c3-chart-arc.c3-target g path {
  opacity: 1;
}

.c3-chart-arc.c3-target.c3-focused g path {
  opacity: 1;
}

/*-- Zoom --*/
.c3-drag-zoom.enabled {
  pointer-events: all !important;
  visibility: visible;
}

.c3-drag-zoom.disabled {
  pointer-events: none !important;
  visibility: hidden;
}

.c3-drag-zoom .extent {
  fill-opacity: 0.1;
}