Browse Source

Refactors classes + bugfix + improves coverage (#2405)

* Uses classes prototype instead of their aliases

 - Class chart was moved to its own script.
 - Class AxisInternal was moved to its own script. It's only needed by Class Axis
 - Definition of Chart removed from core.js
 - Definition of AxisInternal removed from axis.js

* Replaces aliases of Class prototypes

  - Alias c3_chart_fn replaced by Chart.prototype where is due
  - Alias c3_chart_internal_fn replaced by ChartInternal.prototype where is due
  - spec/data.convets.js renamed to spec/data.convert-spec.js for clarity

* Fixes Chart.prototype.legend.hide behavior

 - It was calling $$.updateAndRedraw({withLegend: true});
 - It should call $$.updateAndRedraw({withLegend: false});

* loads *-helper.js and *-spec.js files

* adds tests to improve coverage

restores c3.js and c3.min.js to master version

fixes linter error

* util is a plain collection of functions

* adds test for api.x, drag and util
pull/2413/head
Felipe Figueroa 6 years ago committed by Yoshiya Hinosawa
parent
commit
9556e38b41
  1. 2
      karma.conf.js
  2. 128
      spec/api.data-spec.js
  3. 83
      spec/api.x-spec.js
  4. 50
      spec/core-spec.js
  5. 47
      spec/data-spec.js
  6. 0
      spec/data.convert-spec.js
  7. 79
      spec/drag-spec.js
  8. 32
      spec/legend-spec.js
  9. 72
      spec/shape.bar-spec.js
  10. 185
      spec/util-spec.js
  11. 12
      src/api.axis.js
  12. 6
      src/api.category.js
  13. 8
      src/api.chart.js
  14. 4
      src/api.color.js
  15. 14
      src/api.data.js
  16. 6
      src/api.flow.js
  17. 8
      src/api.focus.js
  18. 14
      src/api.grid.js
  19. 4
      src/api.group.js
  20. 10
      src/api.legend.js
  21. 8
      src/api.load.js
  22. 8
      src/api.region.js
  23. 8
      src/api.selection.js
  24. 8
      src/api.show.js
  25. 8
      src/api.tooltip.js
  26. 6
      src/api.transform.js
  27. 6
      src/api.x.js
  28. 14
      src/api.zoom.js
  29. 54
      src/arc.js
  30. 390
      src/axis-internal.js
  31. 582
      src/axis.js
  32. 8
      src/cache.js
  33. 4
      src/category.js
  34. 20
      src/chart.js
  35. 64
      src/class-utils.js
  36. 30
      src/clip.js
  37. 6
      src/color.js
  38. 8
      src/config.js
  39. 510
      src/core.js
  40. 16
      src/data.convert.js
  41. 259
      src/data.js
  42. 8
      src/data.load.js
  43. 20
      src/domain.js
  44. 8
      src/drag.js
  45. 14
      src/format.js
  46. 34
      src/grid.js
  47. 1
      src/index.js
  48. 10
      src/interaction.js
  49. 36
      src/legend.js
  50. 1218
      src/polyfill.js
  51. 18
      src/region.js
  52. 14
      src/scale.js
  53. 18
      src/selection.js
  54. 24
      src/shape.bar.js
  55. 14
      src/shape.js
  56. 50
      src/shape.line.js
  57. 26
      src/size.js
  58. 30
      src/subchart.js
  59. 18
      src/text.js
  60. 27
      src/title.js
  61. 92
      src/tooltip.js
  62. 38
      src/type.js
  63. 6
      src/ua.js
  64. 110
      src/util.js
  65. 10
      src/zoom.js

2
karma.conf.js

@ -6,7 +6,7 @@ module.exports = function(config) {
files: [
'c3.css',
'spec/*-helper.js',
'spec/*.js'
'spec/*-spec.js'
],
preprocessors: {
'spec/*.js': ['browserify']

128
spec/api.data-spec.js

@ -44,13 +44,13 @@ describe('c3 api data', function () {
});
});
it('should return specifid data if string argument given', function () {
it('should return specified data if string argument given', function () {
var results = chart.data('data1');
expect(results.length).toBe(1);
expect(results[0].id).toBe('data1');
});
it('should return specifid data if array argument given', function () {
it('should return specified data if array argument given', function () {
var results = chart.data(['data1', 'data2']);
expect(results.length).toBe(2);
expect(results[0].id).toBe('data1');
@ -164,22 +164,124 @@ describe('c3 api data', function () {
});
describe('c3 api data.x', function () {
'use strict';
var chart;
var args = {
data: {
x: 'x',
columns: [
['x', 10, 30, 45, 50, 70, 100],
['data1', 30, 200, 100, 400, 150, 250],
['data2', 20, 180, 240, 100, 190]
]
}
};
beforeEach(function (done) {
chart = window.initChart(chart, args, done);
});
it('should return values for target data1', function () {
var values = chart.data.values('data1'),
expectedValues =   [30, 200, 100, 400, 150, 250];
expect(values.length).toBe(6);
values.forEach(function (v, i) {
expect(v).toBe(expectedValues[i]);
});
});
it('should return null when no args', function () {
var values = chart.data.values();
expect(values).toBeNull();
});
it('should return data values for data if string argument given', function () {
var results = chart.data('data1');
expect(results.length).toBe(1);
expect(results[0].id).toBe('data1');
});
it('should return specified data if array argument given', function () {
var results = chart.data(['data1', 'data2']);
expect(results.length).toBe(2);
expect(results[0].id).toBe('data1');
expect(results[1].id).toBe('data2');
});
});
describe('c3 api data.xs', function () {
'use strict';
var chart;
var args = {
data: {
xs: {
'data1': 'x1',
'data2': 'x2',
},
columns: [
['x1', 10, 30, 45, 50, 70, 100],
['x2', 30, 50, 75, 100, 120],
['data1', 30, 200, 100, 400, 150, 250],
['data2', 20, 180, 240, 100, 190]
]
}
};
beforeEach(function (done) {
chart = window.initChart(chart, args, done);
});
it('should return values for target data1', function () {
var values = chart.data.values('data1'),
expectedValues =   [30, 200, 100, 400, 150, 250];
expect(values.length).toBe(6);
values.forEach(function (v, i) {
expect(v).toBe(expectedValues[i]);
});
});
it('should return null when no args', function () {
var values = chart.data.values();
expect(values).toBeNull();
});
it('should return data values for data if string argument given', function () {
var results = chart.data('data1');
expect(results.length).toBe(1);
expect(results[0].id).toBe('data1');
});
it('should return specified data if array argument given', function () {
var results = chart.data(['data1', 'data2']);
expect(results.length).toBe(2);
expect(results[0].id).toBe('data1');
expect(results[1].id).toBe('data2');
});
});
var customMatchers = {
toBeHexOrRGB: function(util, customEqualityTesters) {
toBeHexOrRGB: function (util, customEqualityTesters) {
'use strict';
function rgb2hex(rgb){
function rgb2hex(rgb) {
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
}
return {
compare: function(actual, expected){
compare: function (actual, expected) {
if (expected === undefined) {
expected = '';
expected = '';
}
var result = {};
@ -190,11 +292,11 @@ var customMatchers = {
if (result.pass) {
result.message = "Expected " + actual + " not to be quite so goofy";
} else {
result.message = "Expected " + actual + " to be goofy, but it was not very goofy";
result.message = "Expected " + actual + " to be goofy, but it was not very goofy";
}
}
return result;
return result;
}
};
}

83
spec/api.x-spec.js

@ -0,0 +1,83 @@
describe('c3 api.x', function () {
'use strict';
var chart;
var args = {
data: {
x: 'x',
columns: [
['x', 10, 30, 45, 50, 70, 100],
['data1', 30, 200, 100, 400, 150, 250],
['data2', 20, 180, 240, 100, 190]
]
}
};
beforeEach(function (done) {
chart = window.initChart(chart, args, done);
});
it('should return initial ticks for axis x', function () {
var expectedValues =   [10, 30, 45, 50, 70, 100];
d3.select('.c3-axis-x').selectAll('g.tick').each(function (d, i) {
var text = d3.select(this).select('text').text();
expect(+text).toBe(expectedValues[i]);
});
});
it('should return new ticks for axis x after calling chart.x', function () {
var expectedValues =   [16, 26, 55, 60, 75, 90];
chart.x(expectedValues);
d3.select('.c3-axis-x').selectAll('g.tick').each(function (d, i) {
var text = d3.select(this).select('text').text();
expect(+text).toBe(expectedValues[i]);
});
});
});
describe('c3 api.xs', function () {
'use strict';
var chart;
var args = {
data: {
xs: {
'data1': 'x1',
'data2': 'x2',
},
columns: [
['x1', 10, 30, 50, 70, 90, 110],
['x2', 20, 40, 60, 80, 100],
['data1', 30, 200, 100, 400, 150, 250],
['data2', 20, 180, 240, 100, 190]
]
}
};
beforeEach(function (done) {
chart = window.initChart(chart, args, done);
});
it('should return initial ticks for axis x', function () {
var expectedValues =   ["10", "20", "30", "40", "50", "60", "70", "80", "90", "100", "110"];
d3.select('.c3-axis-x').selectAll('g.tick').each(function (d, i) {
var text = d3.select(this).select('text').text();
expect(text).toBe(expectedValues[i]);
});
});
it('should return new ticks for axis x after calling chart.xs', function () {
var expectedValues =    ["15", "25", "35", "45", "55", "65", "75", "85", "95", "105", "115"];
chart.xs({
data1: [15, 35, 55, 75, 95, 115],
data2: [25, 45, 65, 85, 105]
});
d3.select('.c3-axis-x').selectAll('g.tick').each(function (d, i) {
var text = d3.select(this).select('text').text();
expect(text).toBe(expectedValues[i]);
});
});
});

50
spec/core-spec.js

@ -28,11 +28,10 @@ describe('c3 chart', function () {
});
describe('should set 3rd party property to Function', function () {
beforeAll(function(){
beforeAll(function () {
Function.prototype.$extIsFunction = true;
});
it('should be created even if 3rd party property has been set', function () {
var svg = d3.select('#chart svg');
expect(svg).not.toBeNull();
@ -60,10 +59,40 @@ describe('c3 chart', function () {
});
describe('call resize and resized callbacks', function () {
beforeAll(function () {
args.bindto = '#chart';
args.axis = {
rotated: true
};
args.resize_var = false;
args.resized_var = false;
args.onresize = function () {
args.resize_var = true;
};
args.onresized = function () {
args.resized_var = true;
};
});
it('arbitrary parameters should be false before resize', function () {
expect(args.resize_var).toBe(false);
expect(args.resized_var).toBe(false);
});
it('arbitrary parameters should be true after resize', function () {
window.dispatchEvent(new Event('resize'));
expect(args.resize_var).toBe(true);
expect(args.resized_var).toBe(true);
});
});
describe('bindto', function () {
describe('selector', function () {
beforeAll(function(){
beforeAll(function () {
d3.select('#chart').html('');
args.bindto = '#chart';
});
@ -108,6 +137,19 @@ describe('c3 chart', function () {
expect(svg.size()).toBe(0);
});
});
describe('bind to selector with rotated axis', function () {
beforeAll(function () {
args.bindto = '#chart';
args.axis = {
rotated: true
};
});
it('should be created', function () {
var svg = d3.select('#chart svg');
expect(svg.size()).toBe(1);
});
});
});
describe('empty data', function () {
@ -128,7 +170,7 @@ describe('c3 chart', function () {
});
describe('more empty data', function () {
beforeAll(function(){
beforeAll(function () {
args = {
data: {
x: 'x',

47
spec/data-spec.js

@ -1,3 +1,19 @@
describe('load without data', function () {
var chart, args;
beforeAll(function () {
args = {
data: {}
};
});
it('throws when data is an empty object', () => {
expect(() => window.initChart(chart, args))
.toThrowError(Error, /url or json or rows or columns is required/);
});
});
describe('c3 chart data', function () {
'use strict';
@ -165,6 +181,37 @@ describe('c3 chart data', function () {
});
});
describe('load rows', function () {
beforeAll(function () {
args = {
data: {
rows: [
['data1', 'data2', 'data3'],
[90, 120, 300],
[40, 160, 240],
[50, 200, 290],
[120, 160, 230],
[80, 130, 300],
[90, 220, 320]
]
}
};
});
it('should draw correctly', function () {
var expectedCx = [6, 124, 241,358,475,593],
expectedCy = [327, 391, 378,289,340,327];
d3.selectAll('.c3-circles-data1 .c3-circle').each(function (d, i) {
var circle = d3.select(this);
expect(+circle.attr('cx')).toBeCloseTo(expectedCx[i], 0);
expect(+circle.attr('cy')).toBeCloseTo(expectedCy[i], 0);
});
});
});
describe('function in data.order', function () {
beforeAll(function () {
args = {

0
spec/data.convert.js → spec/data.convert-spec.js

79
spec/drag-spec.js

@ -0,0 +1,79 @@
describe('drag behavior', function () {
'use strict';
var chart, shapes, $$, totalshapes;
var args = {
data: {
x: 'x',
columns: [
['x', 10, 30, 45, 50, 70, 100],
['data1', 30, 200, 100, 400, 150, 250],
['data2', 20, 180, 240, 100, 190]
],
selection: {
enabled: true,
grouped: true,
multiple: true,
draggable: true
},
}
};
beforeAll(function (done) {
chart = window.initChart(chart, args, done);
$$ = chart.internal;
shapes = $$.main.selectAll('.' + $$.CLASS.shapes)
.selectAll('.' + $$.CLASS.shape);
totalshapes = shapes.size();
});
it('should contain 15 shapes', function () {
expect(totalshapes).toBe(15);
});
it('should have no selected shapes', function () {
var selected = shapes
.filter(function () {
return d3.select(this).classed($$.CLASS.SELECTED);
}).size();
expect(selected).toBe(0);
});
describe('Trigger drag events', function () {
beforeAll(function () {
var s = chart.internal.eventRect,
coords1 = [(s.attr('width') - s.attr('x')) / 3, (s.attr('height') - s.attr('y')) / 3],
coords2 = [2 * (s.attr('width') - s.attr('x')) / 3, 2 * (s.attr('height') - s.attr('y')) / 3];
$$.dragstart(coords1);
$$.drag(coords2);
$$.dragend();
});
it('should select 6 shapes', function () {
var selected = shapes
.filter(function () {
return d3.select(this).classed($$.CLASS.SELECTED);
}).size();
expect(selected).toBe(6);
});
it('should select 9 unselected shapes', function () {
var unselected = shapes
.filter(function () {
return !d3.select(this).classed($$.CLASS.SELECTED);
}).size();
expect(unselected).toBe(9);
});
});
});

32
spec/legend-spec.js

@ -218,6 +218,38 @@ describe('c3 chart legend', function () {
});
describe('with legend.show is true', function () {
beforeAll(function () {
args = {
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 130, 100, 200, 100, 250, 150]
]
},
legend: {
show: true
}
};
});
it('should initially have rendered some legend items', function () {
expect(d3.selectAll('.c3-legend-item').empty()).toBe(false);
});
it('should remove rendered every legend items', function () {
chart.legend.hide();
d3.selectAll('.c3-legend-item').each(function () {
expect(d3.select(this).style('visibility')).toBe('hidden');
// This selects all the children, but we expect it to be empty
expect(d3.select(this).selectAll("*").length).toEqual(undefined);
});
});
});
describe('custom legend size', function() {
beforeAll(function () {
args = {

72
spec/shape.bar-spec.js

@ -7,6 +7,45 @@ describe('c3 chart shape bar', function () {
chart = window.initChart(chart, args, done);
});
describe('Path boxes', function () {
beforeAll(function () {
args = {
data: {
columns: [
['data1', 30]
],
type: 'bar',
},
bar: {
width: {
max: 40
}
}
};
});
it('bars should have expected Path Box', function () {
var expected = {
x: 279,
y: 40,
width: 40,
height: 387
};
var shapes = chart.internal.main
.selectAll('.' + chart.internal.CLASS.shapes)
.selectAll('.' + chart.internal.CLASS.shape);
shapes.each(function () {
var pathBox = chart.internal.getPathBox(this);
expect(pathBox.x).toBeCloseTo(expected.x, -1);
expect(pathBox.y).toBeCloseTo(expected.y, -1);
expect(pathBox.width).toBeCloseTo(expected.width, -1);
expect(pathBox.height).toBeCloseTo(expected.height, -1);
});
});
});
describe('with groups', function () {
describe('with indexed data', function () {
@ -30,7 +69,8 @@ describe('c3 chart shape bar', function () {
var rect = d3.select(this).node().getBoundingClientRect();
expect(rect.bottom).toBeCloseTo(expectedBottom[i], -1);
});
});
});
});
describe('with timeseries data', function () {
@ -61,7 +101,7 @@ describe('c3 chart shape bar', function () {
var rect = d3.select(this).node().getBoundingClientRect();
expect(rect.bottom).toBeCloseTo(expectedBottom[i], -1);
});
});
});
});
describe('with category data', function () {
@ -93,7 +133,7 @@ describe('c3 chart shape bar', function () {
var rect = d3.select(this).node().getBoundingClientRect();
expect(rect.bottom).toBeCloseTo(expectedBottom[i], -1);
});
});
});
});
});
@ -164,23 +204,23 @@ describe('c3 chart shape bar', function () {
});
describe('bar spacing', function() {
describe('bar spacing', function () {
var createArgs = function(spacing) {
var createArgs = function (spacing) {
return {
size: {
width: 500
width: 500
},
data: {
columns: [
['data1', 30, 200, 100],
['data2', 50, 20, 10],
['data3', 150, 120, 110],
['data4', 12, 24, 20 ]
['data4', 12, 24, 20]
],
type: 'bar',
groups: [
[ 'data1', 'data4' ]
['data1', 'data4']
]
},
bar: {
@ -189,27 +229,27 @@ describe('c3 chart shape bar', function () {
};
};
var getBBox = function(selector) {
return d3.select(selector).node().getBBox();
var getBBox = function (selector) {
return d3.select(selector).node().getBBox();
};
var getBarContainerWidth = function() {
var getBarContainerWidth = function () {
return parseInt(getBBox('.c3-chart-bars').width);
};
var getBarContainerOffset = function() {
var getBarContainerOffset = function () {
return parseInt(getBBox('.c3-chart-bars').x);
};
var getBarBBox = function(name, idx) {
var getBarBBox = function (name, idx) {
return getBBox('.c3-target-' + name + ' .c3-bar-' + (idx || 0));
};
var getBarWidth = function(name, idx) {
return parseInt(getBarBBox(name, idx).width);
var getBarWidth = function (name, idx) {
return parseInt(getBarBBox(name, idx).width);
};
var getBarOffset = function(name1, name2, idx) {
var getBarOffset = function (name1, name2, idx) {
var bbox1 = getBarBBox(name1, idx);
var bbox2 = getBarBBox(name2, idx);
return parseInt(bbox2.x - (bbox1.x + bbox1.width));

185
spec/util-spec.js

@ -0,0 +1,185 @@
import {
asHalfPixel,
ceil10,
diffDomain,
getOption,
hasValue,
isArray,
isDefined,
isEmpty,
isFunction,
isString,
isUndefined,
isValue,
notEmpty,
sanitise
} from '../src/util';
describe('util.js tests', function () {
'use strict';
var undefined_var;
var html_str = '<div>Hello there</div>';
var html_entities_str = '&lt;div&gt;Hello there&lt;/div&gt;';
var empty_string = '';
var nonempty_string = 'hello there';
var nonempty_number = 1234.2;
var null_var = null;
var empty_object = {};
var nonempty_object = {
a: 1
};
var empty_array = [];
var nonempty_array = [1, 3];
var nonempty_function = function (a) {
return a;
};
describe('asHalfPixel, ceil10 and diffDomain functions', function () {
it('asHalfPixel should return correct value', function () {
expect(asHalfPixel(nonempty_number)).toBe(1235.5);
});
it('ceil10 should return correct value', function () {
expect(ceil10(nonempty_number)).toBe(1240);
});
it('diffDomain should return correct value', function () {
expect(diffDomain(nonempty_array)).toBe(2);
});
});
describe('getOption and hasValue functions', function () {
it('getOption should return value if options dict has specified key', function () {
expect(getOption(nonempty_object, 'a', 'b')).toBe(1);
});
it('getOption should return default value if options dict lacks specified key', function () {
expect(getOption(empty_object, 'a', 'b')).toBe('b');
});
it('hasValue should return true if dict has requested value', function () {
expect(hasValue(nonempty_object, 1)).toBe(true);
});
it('hasValue should return false if dict lacks requested value', function () {
expect(hasValue(nonempty_object, 2)).toBe(false);
});
});
describe('sanitise function', function () {
it('should replace < and > tags', function () {
expect(sanitise(html_str)).toBe(html_entities_str);
});
it('should not modify a string not containing < and > tags', function () {
expect(sanitise(html_entities_str)).toBe(html_entities_str);
});
it('should not modify an imput whose type is not string', function () {
expect(sanitise(nonempty_number)).toBe(nonempty_number);
});
});
describe('isArray, isDefined, isEmpty, isFunction, isString, isUndefined, isValue and notEmpty functions', function () {
it('isArray should return true for array var', function () {
expect(isArray(nonempty_array)).toBe(true);
});
it('isDefined should return true for defined var', function () {
expect(isDefined(nonempty_string)).toBe(true);
});
it('isFunction should return true for function var', function () {
expect(isFunction(nonempty_function)).toBe(true);
});
it('isString should return true for string var', function () {
expect(isString(nonempty_string)).toBe(true);
});
it('isUndefined should return true for undefined var', function () {
expect(isUndefined(undefined_var)).toBe(true);
});
it('isValue should return true for value var', function () {
expect(isValue(nonempty_number)).toBe(1234.2);
});
it('isArray should return false for non array var', function () {
expect(isArray(nonempty_string)).toBe(false);
});
it('isDefined should return false for non defined var', function () {
expect(isDefined(undefined_var)).toBe(false);
});
it('isFunction should return false for non function var', function () {
expect(isFunction(nonempty_string)).toBe(false);
});
it('isString should return false for non string var', function () {
expect(isString(undefined_var)).toBe(false);
});
it('isUndefined should return false for non undefined var', function () {
expect(isUndefined(nonempty_string)).toBe(false);
});
it('isValue should return false for null var', function () {
expect(isValue(null_var)).toBe(false);
});
it('isEmpty should return false for nonempty_array', function () {
expect(isEmpty(nonempty_array)).toBe(false);
});
it('isEmpty should return false for nonempty_number', function () {
expect(isEmpty(nonempty_number)).toBe(false);
});
it('isEmpty should return false for nonempty_object', function () {
expect(isEmpty(nonempty_object)).toBe(false);
});
it('isEmpty should return false for nonempty_string', function () {
expect(isEmpty(nonempty_string)).toBe(false);
});
it('isEmpty should return true for empty_array', function () {
expect(isEmpty(empty_array)).toBe(true);
});
it('isEmpty should return true for empty_object', function () {
expect(isEmpty(empty_object)).toBe(true);
});
it('isEmpty should return true for empty_string', function () {
expect(isEmpty(empty_string)).toBe(true);
});
it('isEmpty should return true for null_var', function () {
expect(isEmpty(null_var)).toBe(true);
});
it('isEmpty should return true for undefined_var', function () {
expect(isEmpty(undefined_var)).toBe(true);
});
it('notEmpty should return false for empty_array', function () {
expect(notEmpty(empty_array)).toBe(false);
});
it('notEmpty should return false for empty_object', function () {
expect(notEmpty(empty_object)).toBe(false);
});
it('notEmpty should return false for empty_string', function () {
expect(notEmpty(empty_string)).toBe(false);
});
it('notEmpty should return false for null_var', function () {
expect(notEmpty(null_var)).toBe(false);
});
it('notEmpty should return false for undefined_var', function () {
expect(notEmpty(undefined_var)).toBe(false);
});
it('notEmpty should return true for nonempty_array', function () {
expect(notEmpty(nonempty_array)).toBe(true);
});
it('notEmpty should return true for nonempty_number', function () {
expect(notEmpty(nonempty_number)).toBe(true);
});
it('notEmpty should return true for nonempty_object', function () {
expect(notEmpty(nonempty_object)).toBe(true);
});
it('notEmpty should return true for nonempty_string', function () {
expect(notEmpty(nonempty_string)).toBe(true);
});
});
});

12
src/api.axis.js

@ -1,8 +1,8 @@
import { c3_chart_fn } from './core';
import { Chart } from './core';
import { isValue, isDefined } from './util';
c3_chart_fn.axis = function () {};
c3_chart_fn.axis.labels = function (labels) {
Chart.prototype.axis = function () {};
Chart.prototype.axis.labels = function (labels) {
var $$ = this.internal;
if (arguments.length) {
Object.keys(labels).forEach(function (axisId) {
@ -12,7 +12,7 @@ c3_chart_fn.axis.labels = function (labels) {
}
// TODO: return some values?
};
c3_chart_fn.axis.max = function (max) {
Chart.prototype.axis.max = function (max) {
var $$ = this.internal, config = $$.config;
if (arguments.length) {
if (typeof max === 'object') {
@ -31,7 +31,7 @@ c3_chart_fn.axis.max = function (max) {
};
}
};
c3_chart_fn.axis.min = function (min) {
Chart.prototype.axis.min = function (min) {
var $$ = this.internal, config = $$.config;
if (arguments.length) {
if (typeof min === 'object') {
@ -50,7 +50,7 @@ c3_chart_fn.axis.min = function (min) {
};
}
};
c3_chart_fn.axis.range = function (range) {
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); }

6
src/api.category.js

@ -1,6 +1,6 @@
import { c3_chart_fn } from './core';
import { Chart } from './core';
c3_chart_fn.category = function (i, category) {
Chart.prototype.category = function (i, category) {
var $$ = this.internal, config = $$.config;
if (arguments.length > 1) {
config.axis_x_categories[i] = category;
@ -8,7 +8,7 @@ c3_chart_fn.category = function (i, category) {
}
return config.axis_x_categories[i];
};
c3_chart_fn.categories = function (categories) {
Chart.prototype.categories = function (categories) {
var $$ = this.internal, config = $$.config;
if (!arguments.length) { return config.axis_x_categories; }
config.axis_x_categories = categories;

8
src/api.chart.js

@ -1,18 +1,18 @@
import { c3_chart_fn } from './core';
import { Chart } from './core';
c3_chart_fn.resize = function (size) {
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();
};
c3_chart_fn.flush = function () {
Chart.prototype.flush = function () {
var $$ = this.internal;
$$.updateAndRedraw({withLegend: true, withTransition: false, withTransitionForTransform: false});
};
c3_chart_fn.destroy = function () {
Chart.prototype.destroy = function () {
var $$ = this.internal;
window.clearInterval($$.intervalForObserveInserted);

4
src/api.color.js

@ -1,7 +1,7 @@
import { c3_chart_fn } from './core';
import { Chart } from './core';
// TODO: fix
c3_chart_fn.color = function (id) {
Chart.prototype.color = function (id) {
var $$ = this.internal;
return $$.color(id); // more patterns
};

14
src/api.data.js

@ -1,15 +1,15 @@
import { c3_chart_fn } from './core';
import { Chart } from './core';
c3_chart_fn.data = function (targetIds) {
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;
});
};
c3_chart_fn.data.shown = function (targetIds) {
Chart.prototype.data.shown = function (targetIds) {
return this.internal.filterTargetsToShow(this.data(targetIds));
};
c3_chart_fn.data.values = function (targetId) {
Chart.prototype.data.values = function (targetId) {
var targets, values = null;
if (targetId) {
targets = this.data(targetId);
@ -17,13 +17,13 @@ c3_chart_fn.data.values = function (targetId) {
}
return values;
};
c3_chart_fn.data.names = function (names) {
Chart.prototype.data.names = function (names) {
this.internal.clearLegendItemTextBoxCache();
return this.internal.updateDataAttributes('names', names);
};
c3_chart_fn.data.colors = function (colors) {
Chart.prototype.data.colors = function (colors) {
return this.internal.updateDataAttributes('colors', colors);
};
c3_chart_fn.data.axes = function (axes) {
Chart.prototype.data.axes = function (axes) {
return this.internal.updateDataAttributes('axes', axes);
};

6
src/api.flow.js

@ -1,8 +1,8 @@
import CLASS from './class';
import { c3_chart_fn, c3_chart_internal_fn } from './core';
import { Chart, ChartInternal } from './core';
import { isValue, isDefined, diffDomain } from './util';
c3_chart_fn.flow = function (args) {
Chart.prototype.flow = function (args) {
var $$ = this.internal,
targets, data, notfoundIds = [], orgDataCount = $$.getMaxDataCount(),
dataCount, domain, baseTarget, baseValue, length = 0, tail = 0, diff, to;
@ -145,7 +145,7 @@ c3_chart_fn.flow = function (args) {
});
};
c3_chart_internal_fn.generateFlow = function (args) {
ChartInternal.prototype.generateFlow = function (args) {
var $$ = this, config = $$.config, d3 = $$.d3;
return function () {

8
src/api.focus.js

@ -1,7 +1,7 @@
import CLASS from './class';
import { c3_chart_fn } from './core';
import { Chart } from './core';
c3_chart_fn.focus = function (targetIds) {
Chart.prototype.focus = function (targetIds) {
var $$ = this.internal, candidates;
targetIds = $$.mapToTargetIds(targetIds);
@ -21,7 +21,7 @@ c3_chart_fn.focus = function (targetIds) {
});
};
c3_chart_fn.defocus = function (targetIds) {
Chart.prototype.defocus = function (targetIds) {
var $$ = this.internal, candidates;
targetIds = $$.mapToTargetIds(targetIds);
@ -39,7 +39,7 @@ c3_chart_fn.defocus = function (targetIds) {
$$.defocusedTargetIds = targetIds;
};
c3_chart_fn.revert = function (targetIds) {
Chart.prototype.revert = function (targetIds) {
var $$ = this.internal, candidates;
targetIds = $$.mapToTargetIds(targetIds);

14
src/api.grid.js

@ -1,33 +1,33 @@
import { c3_chart_fn } from './core';
import { Chart } from './core';
c3_chart_fn.xgrids = function (grids) {
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;
};
c3_chart_fn.xgrids.add = function (grids) {
Chart.prototype.xgrids.add = function (grids) {
var $$ = this.internal;
return this.xgrids($$.config.grid_x_lines.concat(grids ? grids : []));
};
c3_chart_fn.xgrids.remove = function (params) { // TODO: multiple
Chart.prototype.xgrids.remove = function (params) { // TODO: multiple
var $$ = this.internal;
$$.removeGridLines(params, true);
};
c3_chart_fn.ygrids = function (grids) {
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;
};
c3_chart_fn.ygrids.add = function (grids) {
Chart.prototype.ygrids.add = function (grids) {
var $$ = this.internal;
return this.ygrids($$.config.grid_y_lines.concat(grids ? grids : []));
};
c3_chart_fn.ygrids.remove = function (params) { // TODO: multiple
Chart.prototype.ygrids.remove = function (params) { // TODO: multiple
var $$ = this.internal;
$$.removeGridLines(params, false);
};

4
src/api.group.js

@ -1,7 +1,7 @@
import { c3_chart_fn } from './core';
import { Chart } from './core';
import { isUndefined } from './util';
c3_chart_fn.groups = function (groups) {
Chart.prototype.groups = function (groups) {
var $$ = this.internal, config = $$.config;
if (isUndefined(groups)) { return config.data_groups; }
config.data_groups = groups;

10
src/api.legend.js

@ -1,13 +1,13 @@
import { c3_chart_fn } from './core';
import { Chart } from './core';
c3_chart_fn.legend = function () {};
c3_chart_fn.legend.show = function (targetIds) {
Chart.prototype.legend = function () {};
Chart.prototype.legend.show = function (targetIds) {
var $$ = this.internal;
$$.showLegend($$.mapToTargetIds(targetIds));
$$.updateAndRedraw({withLegend: true});
};
c3_chart_fn.legend.hide = function (targetIds) {
Chart.prototype.legend.hide = function (targetIds) {
var $$ = this.internal;
$$.hideLegend($$.mapToTargetIds(targetIds));
$$.updateAndRedraw({withLegend: true});
$$.updateAndRedraw({withLegend: false});
};

8
src/api.load.js

@ -1,6 +1,6 @@
import { c3_chart_fn } from './core';
import { Chart } from './core';
c3_chart_fn.load = function (args) {
Chart.prototype.load = function (args) {
var $$ = this.internal, config = $$.config;
// update xs if specified
if (args.xs) {
@ -8,7 +8,7 @@ c3_chart_fn.load = function (args) {
}
// update names if exists
if ('names' in args) {
c3_chart_fn.data.names.bind(this)(args.names);
Chart.prototype.data.names.bind(this)(args.names);
}
// update classes if exists
if ('classes' in args) {
@ -48,7 +48,7 @@ c3_chart_fn.load = function (args) {
}
};
c3_chart_fn.unload = function (args) {
Chart.prototype.unload = function (args) {
var $$ = this.internal;
args = args || {};
if (args instanceof Array) {

8
src/api.region.js

@ -1,21 +1,21 @@
import CLASS from './class';
import { c3_chart_fn } from './core';
import { Chart } from './core';
c3_chart_fn.regions = function (regions) {
Chart.prototype.regions = function (regions) {
var $$ = this.internal, config = $$.config;
if (!regions) { return config.regions; }
config.regions = regions;
$$.redrawWithoutRescale();
return config.regions;
};
c3_chart_fn.regions.add = function (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;
};
c3_chart_fn.regions.remove = function (options) {
Chart.prototype.regions.remove = function (options) {
var $$ = this.internal, config = $$.config,
duration, classes, regions;

8
src/api.selection.js

@ -1,8 +1,8 @@
import CLASS from './class';
import { c3_chart_fn } from './core';
import { Chart } from './core';
import { isDefined } from './util';
c3_chart_fn.selected = function (targetId) {
Chart.prototype.selected = function (targetId) {
var $$ = this.internal, d3 = $$.d3;
return d3.merge(
$$.main.selectAll('.' + CLASS.shapes + $$.getTargetSelectorSuffix(targetId)).selectAll('.' + CLASS.shape)
@ -10,7 +10,7 @@ c3_chart_fn.selected = function (targetId) {
.map(function (d) { return d.map(function (d) { var data = d.__data__; return data.data ? data.data : data; }); })
);
};
c3_chart_fn.select = function (ids, indices, resetOther) {
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) {
@ -34,7 +34,7 @@ c3_chart_fn.select = function (ids, indices, resetOther) {
}
});
};
c3_chart_fn.unselect = function (ids, indices) {
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) {

8
src/api.show.js

@ -1,6 +1,6 @@
import { c3_chart_fn } from './core';
import { Chart } from './core';
c3_chart_fn.show = function (targetIds, options) {
Chart.prototype.show = function (targetIds, options) {
var $$ = this.internal, targets;
targetIds = $$.mapToTargetIds(targetIds);
@ -23,7 +23,7 @@ c3_chart_fn.show = function (targetIds, options) {
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
};
c3_chart_fn.hide = function (targetIds, options) {
Chart.prototype.hide = function (targetIds, options) {
var $$ = this.internal, targets;
targetIds = $$.mapToTargetIds(targetIds);
@ -46,7 +46,7 @@ c3_chart_fn.hide = function (targetIds, options) {
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
};
c3_chart_fn.toggle = function (targetIds, options) {
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);

8
src/api.tooltip.js

@ -1,7 +1,7 @@
import { c3_chart_fn } from './core';
import { Chart } from './core';
c3_chart_fn.tooltip = function () {};
c3_chart_fn.tooltip.show = function (args) {
Chart.prototype.tooltip = function () {};
Chart.prototype.tooltip.show = function (args) {
var $$ = this.internal, targets, data, mouse = {};
// determine mouse position on the chart
@ -29,7 +29,7 @@ c3_chart_fn.tooltip.show = function (args) {
$$.config.tooltip_onshow.call($$, data);
};
c3_chart_fn.tooltip.hide = function () {
Chart.prototype.tooltip.hide = function () {
// TODO: get target data by checking the state of focus
this.internal.dispatchEvent('mouseout', 0);

6
src/api.transform.js

@ -1,12 +1,12 @@
import { c3_chart_fn, c3_chart_internal_fn } from './core';
import { Chart, ChartInternal } from './core';
c3_chart_fn.transform = function (type, targetIds) {
Chart.prototype.transform = function (type, targetIds) {
var $$ = this.internal,
options = ['pie', 'donut'].indexOf(type) >= 0 ? {withTransform: true} : null;
$$.transformTo(targetIds, type, options);
};
c3_chart_internal_fn.transformTo = function (targetIds, type, optionsForRedraw) {
ChartInternal.prototype.transformTo = function (targetIds, type, optionsForRedraw) {
var $$ = this,
withTransitionForAxis = !$$.hasArcType(),
options = optionsForRedraw || {withTransitionForAxis: withTransitionForAxis};

6
src/api.x.js

@ -1,6 +1,6 @@
import { c3_chart_fn } from './core';
import { Chart } from './core';
c3_chart_fn.x = function (x) {
Chart.prototype.x = function (x) {
var $$ = this.internal;
if (arguments.length) {
$$.updateTargetX($$.data.targets, x);
@ -8,7 +8,7 @@ c3_chart_fn.x = function (x) {
}
return $$.data.xs;
};
c3_chart_fn.xs = function (xs) {
Chart.prototype.xs = function (xs) {
var $$ = this.internal;
if (arguments.length) {
$$.updateTargetXs($$.data.targets, xs);

14
src/api.zoom.js

@ -1,7 +1,7 @@
import { c3_chart_fn } from './core';
import { Chart } from './core';
import { isDefined } from './util';
c3_chart_fn.zoom = function (domain) {
Chart.prototype.zoom = function (domain) {
var $$ = this.internal;
if (domain) {
if ($$.isTimeSeries()) {
@ -20,12 +20,12 @@ c3_chart_fn.zoom = function (domain) {
return $$.x.domain();
}
};
c3_chart_fn.zoom.enable = function (enabled) {
Chart.prototype.zoom.enable = function (enabled) {
var $$ = this.internal;
$$.config.zoom_enabled = enabled;
$$.updateAndRedraw();
};
c3_chart_fn.unzoom = function () {
Chart.prototype.unzoom = function () {
var $$ = this.internal;
if ($$.config.subchart_show) {
$$.brush.clear();
@ -36,7 +36,7 @@ c3_chart_fn.unzoom = function () {
}
};
c3_chart_fn.zoom.max = function (max) {
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]);
@ -46,7 +46,7 @@ c3_chart_fn.zoom.max = function (max) {
}
};
c3_chart_fn.zoom.min = function (min) {
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]);
@ -56,7 +56,7 @@ c3_chart_fn.zoom.min = function (min) {
}
};
c3_chart_fn.zoom.range = function (range) {
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); }

54
src/arc.js

@ -1,8 +1,8 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isFunction } from './util';
c3_chart_internal_fn.initPie = function () {
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);
@ -19,7 +19,7 @@ c3_chart_internal_fn.initPie = function () {
$$.pie.sort(orderFct || null);
};
c3_chart_internal_fn.updateRadius = function () {
ChartInternal.prototype.updateRadius = function () {
var $$ = this, config = $$.config,
w = config.gauge_width || config.donut_width,
gaugeArcWidth = $$.filterTargetsToShow($$.data.targets).length * $$.config.gauge_arcs_minWidth;
@ -30,14 +30,14 @@ c3_chart_internal_fn.updateRadius = function () {
$$.gaugeArcWidth = w ? w : (gaugeArcWidth <= $$.radius - $$.innerRadius ? $$.radius - $$.innerRadius : (gaugeArcWidth <= $$.radius ? gaugeArcWidth : $$.radius));
};
c3_chart_internal_fn.updateArc = function () {
ChartInternal.prototype.updateArc = function () {
var $$ = this;
$$.svgArc = $$.getSvgArc();
$$.svgArcExpanded = $$.getSvgArcExpanded();
$$.svgArcExpandedSub = $$.getSvgArcExpanded(0.98);
};
c3_chart_internal_fn.updateAngle = function (d) {
ChartInternal.prototype.updateAngle = function (d) {
var $$ = this, config = $$.config,
found = false, index = 0,
gMin, gMax, gTic, gValue;
@ -71,7 +71,7 @@ c3_chart_internal_fn.updateAngle = function (d) {
return found ? d : null;
};
c3_chart_internal_fn.getSvgArc = function () {
ChartInternal.prototype.getSvgArc = function () {
var $$ = this, hasGaugeType = $$.hasType('gauge'),
singleArcWidth = $$.gaugeArcWidth / $$.filterTargetsToShow($$.data.targets).length,
arc = $$.d3.arc().outerRadius(function(d) {
@ -90,7 +90,7 @@ c3_chart_internal_fn.getSvgArc = function () {
return newArc;
};
c3_chart_internal_fn.getSvgArcExpanded = function (rate) {
ChartInternal.prototype.getSvgArcExpanded = function (rate) {
rate = rate || 1;
var $$ = this, hasGaugeType = $$.hasType('gauge'),
singleArcWidth = $$.gaugeArcWidth / $$.filterTargetsToShow($$.data.targets).length,
@ -106,12 +106,12 @@ c3_chart_internal_fn.getSvgArcExpanded = function (rate) {
};
};
c3_chart_internal_fn.getArc = function (d, withoutUpdate, force) {
ChartInternal.prototype.getArc = function (d, withoutUpdate, force) {
return force || this.isArcType(d.data) ? this.svgArc(d, withoutUpdate) : "M 0 0";
};
c3_chart_internal_fn.transformForArcLabel = function (d) {
ChartInternal.prototype.transformForArcLabel = function (d) {
var $$ = this, config = $$.config,
updated = $$.updateAngle(d), c, x, y, h, ratio, translate = "", hasGauge = $$.hasType('gauge');
if (updated && !hasGauge) {
@ -137,14 +137,14 @@ c3_chart_internal_fn.transformForArcLabel = function (d) {
return translate;
};
c3_chart_internal_fn.getArcRatio = function (d) {
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;
};
c3_chart_internal_fn.convertToArcData = function (d) {
ChartInternal.prototype.convertToArcData = function (d) {
return this.addName({
id: d.data.id,
value: d.value,
@ -153,7 +153,7 @@ c3_chart_internal_fn.convertToArcData = function (d) {
});
};
c3_chart_internal_fn.textForArcLabel = function (d) {
ChartInternal.prototype.textForArcLabel = function (d) {
var $$ = this,
updated, value, ratio, id, format;
if (! $$.shouldShowArcLabel()) { return ""; }
@ -166,14 +166,14 @@ c3_chart_internal_fn.textForArcLabel = function (d) {
return format ? format(value, ratio, id) : $$.defaultArcValueFormat(value, ratio);
};
c3_chart_internal_fn.textForGaugeMinMax = function (value, isMax) {
ChartInternal.prototype.textForGaugeMinMax = function (value, isMax) {
var $$ = this,
format = $$.getGaugeLabelExtents();
return format ? format(value, isMax) : value;
};
c3_chart_internal_fn.expandArc = function (targetIds) {
ChartInternal.prototype.expandArc = function (targetIds) {
var $$ = this, interval;
// MEMO: avoid to cancel transition
@ -206,7 +206,7 @@ c3_chart_internal_fn.expandArc = function (targetIds) {
});
};
c3_chart_internal_fn.unexpandArc = function (targetIds) {
ChartInternal.prototype.unexpandArc = function (targetIds) {
var $$ = this;
if ($$.transiting) { return; }
@ -221,7 +221,7 @@ c3_chart_internal_fn.unexpandArc = function (targetIds) {
$$.svg.selectAll('.' + CLASS.arc);
};
c3_chart_internal_fn.expandDuration = function (id) {
ChartInternal.prototype.expandDuration = function (id) {
var $$ = this, config = $$.config;
if ($$.isDonutType(id)) {
@ -236,14 +236,14 @@ c3_chart_internal_fn.expandDuration = function (id) {
};
c3_chart_internal_fn.shouldExpand = function (id) {
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);
};
c3_chart_internal_fn.shouldShowArcLabel = function () {
ChartInternal.prototype.shouldShowArcLabel = function () {
var $$ = this, config = $$.config, shouldShow = true;
if ($$.hasType('donut')) {
shouldShow = config.donut_label_show;
@ -254,13 +254,13 @@ c3_chart_internal_fn.shouldShowArcLabel = function () {
return shouldShow;
};
c3_chart_internal_fn.meetsArcLabelThreshold = function (ratio) {
ChartInternal.prototype.meetsArcLabelThreshold = function (ratio) {
var $$ = this, config = $$.config,
threshold = $$.hasType('donut') ? config.donut_label_threshold : config.pie_label_threshold;
return ratio >= threshold;
};
c3_chart_internal_fn.getArcLabelFormat = function () {
ChartInternal.prototype.getArcLabelFormat = function () {
var $$ = this, config = $$.config,
format = config.pie_label_format;
if ($$.hasType('gauge')) {
@ -271,17 +271,17 @@ c3_chart_internal_fn.getArcLabelFormat = function () {
return format;
};
c3_chart_internal_fn.getGaugeLabelExtents = function () {
ChartInternal.prototype.getGaugeLabelExtents = function () {
var $$ = this, config = $$.config;
return config.gauge_label_extents;
};
c3_chart_internal_fn.getArcTitle = function () {
ChartInternal.prototype.getArcTitle = function () {
var $$ = this;
return $$.hasType('donut') ? $$.config.donut_title : "";
};
c3_chart_internal_fn.updateTargetsForArc = function (targets) {
ChartInternal.prototype.updateTargetsForArc = function (targets) {
var $$ = this, main = $$.main,
mainPies, mainPieEnter,
classChartArc = $$.classChartArc.bind($$),
@ -303,7 +303,7 @@ c3_chart_internal_fn.updateTargetsForArc = function (targets) {
//mainPieUpdate.exit().remove();
};
c3_chart_internal_fn.initArc = function () {
ChartInternal.prototype.initArc = function () {
var $$ = this;
$$.arcs = $$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartArcs)
@ -314,7 +314,7 @@ c3_chart_internal_fn.initArc = function () {
.text($$.getArcTitle());
};
c3_chart_internal_fn.redrawArc = function (duration, durationForExit, withTransform) {
ChartInternal.prototype.redrawArc = function (duration, durationForExit, withTransform) {
var $$ = this, d3 = $$.d3, config = $$.config, main = $$.main,
arcs, mainArc, backgroundArc,
arcLabelLines, mainArcLabelLine,
@ -499,7 +499,7 @@ c3_chart_internal_fn.redrawArc = function (duration, durationForExit, withTransf
.text(config.gauge_label_show ? $$.textForGaugeMinMax(config.gauge_max, true) : '');
}
};
c3_chart_internal_fn.initGauge = function () {
ChartInternal.prototype.initGauge = function () {
var arcs = this.arcs;
if (this.hasType('gauge')) {
arcs.append('g')
@ -518,6 +518,6 @@ c3_chart_internal_fn.initGauge = function () {
.style("pointer-events", "none");
}
};
c3_chart_internal_fn.getGaugeLabelHeight = function () {
ChartInternal.prototype.getGaugeLabelHeight = function () {
return this.config.gauge_label_show ? 20 : 0;
};

390
src/axis-internal.js

@ -0,0 +1,390 @@
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 (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};

582
src/axis.js

@ -1,416 +1,25 @@
import CLASS from './class';
import {isValue, isFunction, isString, isEmpty, Component } from './util';
export var c3_axis_fn;
export var c3_axis_internal_fn;
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();
}
c3_axis_internal_fn = AxisInternal.prototype;
c3_axis_internal_fn.axisX = function (selection, x, tickOffset) {
selection.attr("transform", function (d) {
return "translate(" + Math.ceil(x(d) + tickOffset) + ", 0)";
});
};
c3_axis_internal_fn.axisY = function (selection, y) {
selection.attr("transform", function (d) {
return "translate(0," + Math.ceil(y(d)) + ")";
});
};
c3_axis_internal_fn.scaleExtent = function (domain) {
var start = domain[0], stop = domain[domain.length - 1];
return start < stop ? [ start, stop ] : [ stop, start ];
};
c3_axis_internal_fn.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;
};
c3_axis_internal_fn.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;
};
c3_axis_internal_fn.textFormatted = function (v) {
var internal = this,
formatted = internal.tickFormat ? internal.tickFormat(v) : v;
return typeof formatted !== 'undefined' ? formatted : '';
};
c3_axis_internal_fn.updateRange = function () {
var internal = this;
internal.range = internal.scale.rangeExtent ? internal.scale.rangeExtent() : internal.scaleExtent(internal.scale.range());
return internal.range;
};
c3_axis_internal_fn.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;
};
c3_axis_internal_fn.isVertical = function () {
return this.orient === 'left' || this.orient === 'right';
};
c3_axis_internal_fn.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 };
});
};
c3_axis_internal_fn.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 + "");
};
c3_axis_internal_fn.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;
};
c3_axis_internal_fn.updateTickLength = function () {
var internal = this;
internal.tickLength = Math.max(internal.innerTickSize, 0) + internal.tickPadding;
};
c3_axis_internal_fn.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;
};
c3_axis_internal_fn.textY = function (){
var internal = this, rotate = internal.tickTextRotate;
return rotate ? 11.5 - 2.5 * (rotate / 15) * (rotate > 0 ? 1 : -1) : internal.tickLength;
};
c3_axis_internal_fn.textTransform = function () {
var internal = this, rotate = internal.tickTextRotate;
return rotate ? "rotate(" + rotate + ")" : "";
};
c3_axis_internal_fn.textTextAnchor = function () {
var internal = this, rotate = internal.tickTextRotate;
return rotate ? (rotate > 0 ? "start" : "end") : "middle";
};
c3_axis_internal_fn.tspanDx = function () {
var internal = this, rotate = internal.tickTextRotate;
return rotate ? 8 * Math.sin(Math.PI * (rotate / 180)) : 0;
};
c3_axis_internal_fn.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;
};
c3_axis_internal_fn.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 default class Axis extends Component {
constructor (owner) {
var fn = {
fn: c3_axis_fn,
internal: {
fn: c3_axis_internal_fn
}
};
super(owner, 'axis', fn);
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;
}
}
c3_axis_fn = Axis.prototype;
c3_axis_fn.init = function init() {
var $$ = this.owner, config = $$.config, main = $$.main;
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)
@ -440,8 +49,9 @@ c3_axis_fn.init = function init() {
.attr("transform", config.axis_rotated ? "" : "rotate(-90)")
.style("text-anchor", this.textAnchorForY2AxisLabel.bind(this));
};
c3_axis_fn.getXAxis = function getXAxis(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) {
var $$ = this.owner, config = $$.config,
Axis.prototype.getXAxis = function getXAxis(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) {
var $$ = this.owner,
config = $$.config,
axisParams = {
isCategory: $$.isCategorized(),
withOuterTick: withOuterTick,
@ -454,7 +64,9 @@ c3_axis_fn.getXAxis = function getXAxis(scale, orient, tickFormat, tickValues, w
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); });
tickValues = tickValues.map(function (v) {
return $$.parseDate(v);
});
}
// Set tick
@ -468,8 +80,10 @@ c3_axis_fn.getXAxis = function getXAxis(scale, orient, tickFormat, tickValues, w
return axis;
};
c3_axis_fn.updateXAxisTickValues = function updateXAxisTickValues(targets, axis) {
var $$ = this.owner, config = $$.config, tickValues;
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());
}
@ -481,8 +95,9 @@ c3_axis_fn.updateXAxisTickValues = function updateXAxisTickValues(targets, axis)
}
return tickValues;
};
c3_axis_fn.getYAxis = function getYAxis(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) {
var $$ = this.owner, config = $$.config,
Axis.prototype.getYAxis = function getYAxis(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) {
var $$ = this.owner,
config = $$.config,
axisParams = {
withOuterTick: withOuterTick,
withoutTransition: withoutTransition,
@ -496,15 +111,18 @@ c3_axis_fn.getYAxis = function getYAxis(scale, orient, tickFormat, tickValues, w
}
return axis;
};
c3_axis_fn.getId = function getId(id) {
Axis.prototype.getId = function getId(id) {
var config = this.owner.config;
return id in config.data_axes ? config.data_axes[id] : 'y';
};
c3_axis_fn.getXAxisTickFormat = function getXAxisTickFormat() {
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; };
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)) {
@ -515,22 +133,26 @@ c3_axis_fn.getXAxisTickFormat = function getXAxisTickFormat() {
};
}
}
return isFunction(format) ? function (v) { return format.call($$, v); } : format;
return isFunction(format) ? function (v) {
return format.call($$, v);
} : format;
};
c3_axis_fn.getTickValues = function getTickValues(tickValues, axis) {
Axis.prototype.getTickValues = function getTickValues(tickValues, axis) {
return tickValues ? tickValues : axis ? axis.tickValues() : undefined;
};
c3_axis_fn.getXAxisTickValues = function getXAxisTickValues() {
Axis.prototype.getXAxisTickValues = function getXAxisTickValues() {
return this.getTickValues(this.owner.config.axis_x_tick_values, this.owner.xAxis);
};
c3_axis_fn.getYAxisTickValues = function getYAxisTickValues() {
Axis.prototype.getYAxisTickValues = function getYAxisTickValues() {
return this.getTickValues(this.owner.config.axis_y_tick_values, this.owner.yAxis);
};
c3_axis_fn.getY2AxisTickValues = function getY2AxisTickValues() {
Axis.prototype.getY2AxisTickValues = function getY2AxisTickValues() {
return this.getTickValues(this.owner.config.axis_y2_tick_values, this.owner.y2Axis);
};
c3_axis_fn.getLabelOptionByAxisId = function getLabelOptionByAxisId(axisId) {
var $$ = this.owner, config = $$.config, option;
Axis.prototype.getLabelOptionByAxisId = function getLabelOptionByAxisId(axisId) {
var $$ = this.owner,
config = $$.config,
option;
if (axisId === 'y') {
option = config.axis_y_label;
} else if (axisId === 'y2') {
@ -540,12 +162,13 @@ c3_axis_fn.getLabelOptionByAxisId = function getLabelOptionByAxisId(axisId) {
}
return option;
};
c3_axis_fn.getLabelText = function getLabelText(axisId) {
Axis.prototype.getLabelText = function getLabelText(axisId) {
var option = this.getLabelOptionByAxisId(axisId);
return isString(option) ? option : option ? option.text : null;
};
c3_axis_fn.setLabelText = function setLabelText(axisId, text) {
var $$ = this.owner, config = $$.config,
Axis.prototype.setLabelText = function setLabelText(axisId, text) {
var $$ = this.owner,
config = $$.config,
option = this.getLabelOptionByAxisId(axisId);
if (isString(option)) {
if (axisId === 'y') {
@ -559,7 +182,7 @@ c3_axis_fn.setLabelText = function setLabelText(axisId, text) {
option.text = text;
}
};
c3_axis_fn.getLabelPosition = function getLabelPosition(axisId, defaultPosition) {
Axis.prototype.getLabelPosition = function getLabelPosition(axisId, defaultPosition) {
var option = this.getLabelOptionByAxisId(axisId),
position = (option && typeof option === 'object' && option.position) ? option.position : defaultPosition;
return {
@ -573,28 +196,28 @@ c3_axis_fn.getLabelPosition = function getLabelPosition(axisId, defaultPosition)
isBottom: position.indexOf('bottom') >= 0
};
};
c3_axis_fn.getXAxisLabelPosition = function getXAxisLabelPosition() {
Axis.prototype.getXAxisLabelPosition = function getXAxisLabelPosition() {
return this.getLabelPosition('x', this.owner.config.axis_rotated ? 'inner-top' : 'inner-right');
};
c3_axis_fn.getYAxisLabelPosition = function getYAxisLabelPosition() {
Axis.prototype.getYAxisLabelPosition = function getYAxisLabelPosition() {
return this.getLabelPosition('y', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top');
};
c3_axis_fn.getY2AxisLabelPosition = function getY2AxisLabelPosition() {
Axis.prototype.getY2AxisLabelPosition = function getY2AxisLabelPosition() {
return this.getLabelPosition('y2', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top');
};
c3_axis_fn.getLabelPositionById = function getLabelPositionById(id) {
Axis.prototype.getLabelPositionById = function getLabelPositionById(id) {
return id === 'y2' ? this.getY2AxisLabelPosition() : id === 'y' ? this.getYAxisLabelPosition() : this.getXAxisLabelPosition();
};
c3_axis_fn.textForXAxisLabel = function textForXAxisLabel() {
Axis.prototype.textForXAxisLabel = function textForXAxisLabel() {
return this.getLabelText('x');
};
c3_axis_fn.textForYAxisLabel = function textForYAxisLabel() {
Axis.prototype.textForYAxisLabel = function textForYAxisLabel() {
return this.getLabelText('y');
};
c3_axis_fn.textForY2AxisLabel = function textForY2AxisLabel() {
Axis.prototype.textForY2AxisLabel = function textForY2AxisLabel() {
return this.getLabelText('y2');
};
c3_axis_fn.xForAxisLabel = function xForAxisLabel(forHorizontal, position) {
Axis.prototype.xForAxisLabel = function xForAxisLabel(forHorizontal, position) {
var $$ = this.owner;
if (forHorizontal) {
return position.isLeft ? 0 : position.isCenter ? $$.width / 2 : $$.width;
@ -602,40 +225,41 @@ c3_axis_fn.xForAxisLabel = function xForAxisLabel(forHorizontal, position) {
return position.isBottom ? -$$.height : position.isMiddle ? -$$.height / 2 : 0;
}
};
c3_axis_fn.dxForAxisLabel = function dxForAxisLabel(forHorizontal, position) {
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";
}
};
c3_axis_fn.textAnchorForAxisLabel = function textAnchorForAxisLabel(forHorizontal, position) {
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';
}
};
c3_axis_fn.xForXAxisLabel = function xForXAxisLabel() {
Axis.prototype.xForXAxisLabel = function xForXAxisLabel() {
return this.xForAxisLabel(!this.owner.config.axis_rotated, this.getXAxisLabelPosition());
};
c3_axis_fn.xForYAxisLabel = function xForYAxisLabel() {
Axis.prototype.xForYAxisLabel = function xForYAxisLabel() {
return this.xForAxisLabel(this.owner.config.axis_rotated, this.getYAxisLabelPosition());
};
c3_axis_fn.xForY2AxisLabel = function xForY2AxisLabel() {
Axis.prototype.xForY2AxisLabel = function xForY2AxisLabel() {
return this.xForAxisLabel(this.owner.config.axis_rotated, this.getY2AxisLabelPosition());
};
c3_axis_fn.dxForXAxisLabel = function dxForXAxisLabel() {
Axis.prototype.dxForXAxisLabel = function dxForXAxisLabel() {
return this.dxForAxisLabel(!this.owner.config.axis_rotated, this.getXAxisLabelPosition());
};
c3_axis_fn.dxForYAxisLabel = function dxForYAxisLabel() {
Axis.prototype.dxForYAxisLabel = function dxForYAxisLabel() {
return this.dxForAxisLabel(this.owner.config.axis_rotated, this.getYAxisLabelPosition());
};
c3_axis_fn.dxForY2AxisLabel = function dxForY2AxisLabel() {
Axis.prototype.dxForY2AxisLabel = function dxForY2AxisLabel() {
return this.dxForAxisLabel(this.owner.config.axis_rotated, this.getY2AxisLabelPosition());
};
c3_axis_fn.dyForXAxisLabel = function dyForXAxisLabel() {
var $$ = this.owner, config = $$.config,
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'));
@ -643,7 +267,7 @@ c3_axis_fn.dyForXAxisLabel = function dyForXAxisLabel() {
return position.isInner ? "-0.5em" : config.axis_x_height ? config.axis_x_height - 10 : "3em";
}
};
c3_axis_fn.dyForYAxisLabel = function dyForYAxisLabel() {
Axis.prototype.dyForYAxisLabel = function dyForYAxisLabel() {
var $$ = this.owner,
position = this.getYAxisLabelPosition();
if ($$.config.axis_rotated) {
@ -652,7 +276,7 @@ c3_axis_fn.dyForYAxisLabel = function dyForYAxisLabel() {
return position.isInner ? "1.2em" : -10 - ($$.config.axis_y_inner ? 0 : (this.getMaxTickWidth('y') + 10));
}
};
c3_axis_fn.dyForY2AxisLabel = function dyForY2AxisLabel() {
Axis.prototype.dyForY2AxisLabel = function dyForY2AxisLabel() {
var $$ = this.owner,
position = this.getY2AxisLabelPosition();
if ($$.config.axis_rotated) {
@ -661,21 +285,23 @@ c3_axis_fn.dyForY2AxisLabel = function dyForY2AxisLabel() {
return position.isInner ? "-0.5em" : 15 + ($$.config.axis_y2_inner ? 0 : (this.getMaxTickWidth('y2') + 15));
}
};
c3_axis_fn.textAnchorForXAxisLabel = function textAnchorForXAxisLabel() {
Axis.prototype.textAnchorForXAxisLabel = function textAnchorForXAxisLabel() {
var $$ = this.owner;
return this.textAnchorForAxisLabel(!$$.config.axis_rotated, this.getXAxisLabelPosition());
};
c3_axis_fn.textAnchorForYAxisLabel = function textAnchorForYAxisLabel() {
Axis.prototype.textAnchorForYAxisLabel = function textAnchorForYAxisLabel() {
var $$ = this.owner;
return this.textAnchorForAxisLabel($$.config.axis_rotated, this.getYAxisLabelPosition());
};
c3_axis_fn.textAnchorForY2AxisLabel = function textAnchorForY2AxisLabel() {
Axis.prototype.textAnchorForY2AxisLabel = function textAnchorForY2AxisLabel() {
var $$ = this.owner;
return this.textAnchorForAxisLabel($$.config.axis_rotated, this.getY2AxisLabelPosition());
};
c3_axis_fn.getMaxTickWidth = function getMaxTickWidth(id, withoutRecompute) {
var $$ = this.owner, config = $$.config,
maxWidth = 0, targetsToShow, scale, axis, dummy, svg;
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];
}
@ -694,40 +320,42 @@ c3_axis_fn.getMaxTickWidth = function getMaxTickWidth(id, withoutRecompute) {
}
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; }
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();
});
dummy.remove();
});
}
$$.currentMaxTickWidths[id] = maxWidth <= 0 ? $$.currentMaxTickWidths[id] : maxWidth;
return $$.currentMaxTickWidths[id];
};
c3_axis_fn.updateLabels = function updateLabels(withTransition) {
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("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("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("x", this.xForY2AxisLabel.bind(this))
.attr("dx", this.dxForY2AxisLabel.bind(this))
.attr("dy", this.dyForY2AxisLabel.bind(this))
.text(this.textForY2AxisLabel.bind(this));
};
c3_axis_fn.getPadding = function getPadding(padding, key, defaultValue, domainLength) {
Axis.prototype.getPadding = function getPadding(padding, key, defaultValue, domainLength) {
var p = typeof padding === 'number' ? padding : padding[key];
if (!isValue(p)) {
return defaultValue;
@ -738,13 +366,14 @@ c3_axis_fn.getPadding = function getPadding(padding, key, defaultValue, domainLe
// assume padding is pixels if unit is not specified
return this.convertPixelsToAxisPadding(p, domainLength);
};
c3_axis_fn.convertPixelsToAxisPadding = function convertPixelsToAxisPadding(pixels, domainLength) {
Axis.prototype.convertPixelsToAxisPadding = function convertPixelsToAxisPadding(pixels, domainLength) {
var $$ = this.owner,
length = $$.config.axis_rotated ? $$.width : $$.height;
return domainLength * (pixels / length);
};
c3_axis_fn.generateTickValues = function generateTickValues(values, tickCount, forTimeSeries) {
var tickValues = values, targetCount, start, end, count, interval, i, tickValue;
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
@ -766,11 +395,16 @@ c3_axis_fn.generateTickValues = function generateTickValues(values, tickCount, f
tickValues.push(end);
}
}
if (!forTimeSeries) { tickValues = tickValues.sort(function (a, b) { return a - b; }); }
if (!forTimeSeries) {
tickValues = tickValues.sort(function (a, b) {
return a - b;
});
}
return tickValues;
};
c3_axis_fn.generateTransitions = function generateTransitions(duration) {
var $$ = this.owner, axes = $$.axes;
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,
@ -778,7 +412,7 @@ c3_axis_fn.generateTransitions = function generateTransitions(duration) {
axisSubX: duration ? axes.subx.transition().duration(duration) : axes.subx
};
};
c3_axis_fn.redraw = function redraw(duration, isHidden) {
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);

8
src/cache.js

@ -1,15 +1,15 @@
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
c3_chart_internal_fn.hasCaches = function (ids) {
ChartInternal.prototype.hasCaches = function (ids) {
for (var i = 0; i < ids.length; i++) {
if (! (ids[i] in this.cache)) { return false; }
}
return true;
};
c3_chart_internal_fn.addCache = function (id, target) {
ChartInternal.prototype.addCache = function (id, target) {
this.cache[id] = this.cloneTarget(target);
};
c3_chart_internal_fn.getCaches = function (ids) {
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]])); }

4
src/category.js

@ -1,6 +1,6 @@
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
c3_chart_internal_fn.categoryName = function (i) {
ChartInternal.prototype.categoryName = function (i) {
var config = this.config;
return i < config.axis_x_categories.length ? config.axis_x_categories[i] : i;
};

20
src/chart.js

@ -0,0 +1,20 @@
import {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);
}

64
src/class-utils.js

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

30
src/clip.js

@ -1,60 +1,60 @@
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
c3_chart_internal_fn.getClipPath = function (id) {
ChartInternal.prototype.getClipPath = function (id) {
var isIE9 = window.navigator.appVersion.toLowerCase().indexOf("msie 9.") >= 0;
return "url(" + (isIE9 ? "" : document.URL.split('#')[0]) + "#" + id + ")";
};
c3_chart_internal_fn.appendClip = function (parent, id) {
ChartInternal.prototype.appendClip = function (parent, id) {
return parent.append("clipPath").attr("id", id).append("rect");
};
c3_chart_internal_fn.getAxisClipX = function (forHorizontal) {
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);
};
c3_chart_internal_fn.getAxisClipY = function (forHorizontal) {
ChartInternal.prototype.getAxisClipY = function (forHorizontal) {
return forHorizontal ? -20 : -this.margin.top;
};
c3_chart_internal_fn.getXAxisClipX = function () {
ChartInternal.prototype.getXAxisClipX = function () {
var $$ = this;
return $$.getAxisClipX(!$$.config.axis_rotated);
};
c3_chart_internal_fn.getXAxisClipY = function () {
ChartInternal.prototype.getXAxisClipY = function () {
var $$ = this;
return $$.getAxisClipY(!$$.config.axis_rotated);
};
c3_chart_internal_fn.getYAxisClipX = function () {
ChartInternal.prototype.getYAxisClipX = function () {
var $$ = this;
return $$.config.axis_y_inner ? -1 : $$.getAxisClipX($$.config.axis_rotated);
};
c3_chart_internal_fn.getYAxisClipY = function () {
ChartInternal.prototype.getYAxisClipY = function () {
var $$ = this;
return $$.getAxisClipY($$.config.axis_rotated);
};
c3_chart_internal_fn.getAxisClipWidth = function (forHorizontal) {
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;
};
c3_chart_internal_fn.getAxisClipHeight = function (forHorizontal) {
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;
};
c3_chart_internal_fn.getXAxisClipWidth = function () {
ChartInternal.prototype.getXAxisClipWidth = function () {
var $$ = this;
return $$.getAxisClipWidth(!$$.config.axis_rotated);
};
c3_chart_internal_fn.getXAxisClipHeight = function () {
ChartInternal.prototype.getXAxisClipHeight = function () {
var $$ = this;
return $$.getAxisClipHeight(!$$.config.axis_rotated);
};
c3_chart_internal_fn.getYAxisClipWidth = function () {
ChartInternal.prototype.getYAxisClipWidth = function () {
var $$ = this;
return $$.getAxisClipWidth($$.config.axis_rotated) + ($$.config.axis_y_inner ? 20 : 0);
};
c3_chart_internal_fn.getYAxisClipHeight = function () {
ChartInternal.prototype.getYAxisClipHeight = function () {
var $$ = this;
return $$.getAxisClipHeight($$.config.axis_rotated);
};

6
src/color.js

@ -1,7 +1,7 @@
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { notEmpty } from './util';
c3_chart_internal_fn.generateColor = function () {
ChartInternal.prototype.generateColor = function () {
var $$ = this, config = $$.config, d3 = $$.d3,
colors = config.data_colors,
pattern = notEmpty(config.color_pattern) ? config.color_pattern : d3.schemeCategory10,
@ -28,7 +28,7 @@ c3_chart_internal_fn.generateColor = function () {
return callback instanceof Function ? callback(color, d) : color;
};
};
c3_chart_internal_fn.generateLevelColor = function () {
ChartInternal.prototype.generateLevelColor = function () {
var $$ = this, config = $$.config,
colors = config.color_pattern,
threshold = config.color_threshold,

8
src/config.js

@ -1,7 +1,7 @@
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isDefined } from './util';
c3_chart_internal_fn.getDefaultConfig = function () {
ChartInternal.prototype.getDefaultConfig = function () {
var config = {
bindto: '#chart',
svg_classname: undefined,
@ -243,9 +243,9 @@ c3_chart_internal_fn.getDefaultConfig = function () {
return config;
};
c3_chart_internal_fn.additionalConfig = {};
ChartInternal.prototype.additionalConfig = {};
c3_chart_internal_fn.loadConfig = function (config) {
ChartInternal.prototype.loadConfig = function (config) {
var this_config = this.config, target, keys, read;
function find() {
var key = keys.shift();

510
src/core.js

@ -1,73 +1,88 @@
import {
ChartInternal
} from './chart-internal';
import {
Chart
} from './chart';
import {
AxisInternal
} from './axis-internal';
import Axis from './axis';
import CLASS from './class';
import {
c3,
isEmpty,
notEmpty,
isValue,
isFunction,
isString,
isUndefined,
isDefined,
ceil10,
asHalfPixel,
diffDomain,
getOption,
hasValue,
sanitise,
getPathBox
getPathBox,
isFunction,
isValue,
notEmpty
} from './util';
export {c3};
export var c3_chart_fn;
export var c3_chart_internal_fn;
var c3 = {
version: "0.6.4",
chart: {
fn: Chart.prototype,
internal: {
fn: ChartInternal.prototype,
axis: {
fn: Axis.prototype,
internal: {
fn: AxisInternal.prototype
}
}
}
},
generate: function(config) {
return new Chart(config);
}
};
c3_chart_fn = c3.chart.fn;
c3_chart_internal_fn = c3.chart.internal.fn;
export {
c3
};
c3_chart_internal_fn.beforeInit = function () {
ChartInternal.prototype.beforeInit = function() {
// can do something
};
c3_chart_internal_fn.afterInit = function () {
ChartInternal.prototype.afterInit = function() {
// can do something
};
c3_chart_internal_fn.init = function () {
var $$ = this, config = $$.config;
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) {
} else if (config.data_json) {
$$.initWithData($$.convertJsonToData(config.data_json, config.data_keys));
}
else if (config.data_rows) {
} else if (config.data_rows) {
$$.initWithData($$.convertRowsToData(config.data_rows));
}
else if (config.data_columns) {
} else if (config.data_columns) {
$$.initWithData($$.convertColumnsToData(config.data_columns));
}
else {
} else {
throw Error('url or json or rows or columns is required.');
}
};
c3_chart_internal_fn.initParams = function () {
var $$ = this, d3 = $$.d3, config = $$.config;
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),
$$.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),
$$.clipPathForGrid = $$.getClipPath($$.clipIdForGrid);
$$.clipPathForSubchart = $$.getClipPath($$.clipIdForSubchart);
$$.dragStart = null;
$$.dragging = false;
@ -81,14 +96,28 @@ c3_chart_internal_fn.initParams = function () {
$$.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); }
$$.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 = [];
@ -126,27 +155,37 @@ c3_chart_internal_fn.initParams = function () {
$$.axes.subx = d3.selectAll([]); // needs when excluding subchart.js
};
c3_chart_internal_fn.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.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();
}
};
c3_chart_internal_fn.initWithData = function (data) {
var $$ = this, d3 = $$.d3, config = $$.config;
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') {
} else if (typeof config.bindto.node === 'function') {
$$.selectChart = config.bindto;
}
else {
} else {
$$.selectChart = d3.select(config.bindto);
}
if ($$.selectChart.empty()) {
@ -192,8 +231,12 @@ c3_chart_internal_fn.initWithData = function (data) {
// Define svgs
$$.svg = $$.selectChart.append("svg")
.style("overflow", "hidden")
.on('mouseenter', function () { return config.onmouseover.call($$); })
.on('mouseleave', function () { return config.onmouseout.call($$); });
.on('mouseenter', function() {
return config.onmouseover.call($$);
})
.on('mouseleave', function() {
return config.onmouseout.call($$);
});
if ($$.config.svg_classname) {
$$.svg.attr('class', $$.config.svg_classname);
@ -211,16 +254,30 @@ c3_chart_internal_fn.initWithData = function (data) {
// Define regions
main = $$.main = $$.svg.append("g").attr("transform", $$.getTranslate('main'));
if ($$.initPie) { $$.initPie(); }
if ($$.initSubchart) { $$.initSubchart(); }
if ($$.initTooltip) { $$.initTooltip(); }
if ($$.initLegend) { $$.initLegend(); }
if ($$.initTitle) { $$.initTitle(); }
if ($$.initZoom) { $$.initZoom(); }
if ($$.initPie) {
$$.initPie();
}
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(); }
if ($$.initSubchartBrush) {
$$.initSubchartBrush();
}
/*-- Main Region --*/
@ -242,7 +299,9 @@ c3_chart_internal_fn.initWithData = function (data) {
.attr('class', CLASS.chart);
// Grid lines
if (config.grid_lines_front) { $$.initGridLines(); }
if (config.grid_lines_front) {
$$.initGridLines();
}
// Cover whole with rects for events
$$.initEventRect();
@ -257,7 +316,9 @@ c3_chart_internal_fn.initWithData = function (data) {
$$.updateTargets($$.data.targets);
// Set default extent if defined
if (config.axis_x_selection) { $$.brush.selectionAsValue($$.getDefaultSelection()); }
if (config.axis_x_selection) {
$$.brush.selectionAsValue($$.getDefaultSelection());
}
// Draw with targets
if (binding) {
@ -279,10 +340,10 @@ c3_chart_internal_fn.initWithData = function (data) {
$$.api.element = $$.selectChart.node();
};
c3_chart_internal_fn.smoothLines = function (el, type) {
ChartInternal.prototype.smoothLines = function(el, type) {
var $$ = this;
if (type === 'grid') {
el.each(function () {
el.each(function() {
var g = $$.d3.select(this),
x1 = g.attr('x1'),
x2 = g.attr('x2'),
@ -298,9 +359,9 @@ c3_chart_internal_fn.smoothLines = function (el, type) {
}
};
c3_chart_internal_fn.updateSizes = function () {
var $$ = this, config = $$.config;
ChartInternal.prototype.updateSizes = function() {
var $$ = this,
config = $$.config;
var legendHeight = $$.legend ? $$.getLegendHeight() : 0,
legendWidth = $$.legend ? $$.getLegendWidth() : 0,
legendHeightForBottom = $$.isLegendRight || $$.isLegendInset ? 0 : legendHeight,
@ -344,17 +405,27 @@ c3_chart_internal_fn.updateSizes = function () {
bottom: 0,
left: 0
};
if ($$.updateSizeForLegend) { $$.updateSizeForLegend(legendHeight, legendWidth); }
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; }
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; }
if ($$.width2 < 0) {
$$.width2 = 0;
}
if ($$.height2 < 0) {
$$.height2 = 0;
}
// for arc
$$.arcWidth = $$.width - ($$.isLegendRight ? legendWidth + 10 : 0);
@ -362,14 +433,16 @@ c3_chart_internal_fn.updateSizes = function () {
if ($$.hasType('gauge') && !config.gauge_fullCircle) {
$$.arcHeight += $$.height - $$.getGaugeLabelHeight();
}
if ($$.updateRadius) { $$.updateRadius(); }
if ($$.updateRadius) {
$$.updateRadius();
}
if ($$.isLegendRight && hasArc) {
$$.margin3.left = $$.arcWidth / 2 + $$.radiusExpanded * 1.1;
}
};
c3_chart_internal_fn.updateTargets = function (targets) {
ChartInternal.prototype.updateTargets = function(targets) {
var $$ = this;
/*-- Main --*/
@ -384,25 +457,36 @@ c3_chart_internal_fn.updateTargets = function (targets) {
$$.updateTargetsForLine(targets);
//-- Arc --//
if ($$.hasArcType() && $$.updateTargetsForArc) { $$.updateTargetsForArc(targets); }
if ($$.hasArcType() && $$.updateTargetsForArc) {
$$.updateTargetsForArc(targets);
}
/*-- Sub --*/
if ($$.updateTargetsForSubchart) { $$.updateTargetsForSubchart(targets); }
if ($$.updateTargetsForSubchart) {
$$.updateTargetsForSubchart(targets);
}
// Fade-in each chart
$$.showTargets();
};
c3_chart_internal_fn.showTargets = function () {
ChartInternal.prototype.showTargets = function() {
var $$ = this;
$$.svg.selectAll('.' + CLASS.target).filter(function (d) { return $$.isTargetToShow(d.id); })
.transition().duration($$.config.transition_duration)
$$.svg.selectAll('.' + CLASS.target).filter(function(d) {
return $$.isTargetToShow(d.id);
})
.transition().duration($$.config.transition_duration)
.style("opacity", 1);
};
c3_chart_internal_fn.redraw = function (options, transitions) {
var $$ = this, main = $$.main, d3 = $$.d3, config = $$.config;
var areaIndices = $$.getShapeIndices($$.isAreaType), barIndices = $$.getShapeIndices($$.isBarType), lineIndices = $$.getShapeIndices($$.isLineType);
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;
@ -410,8 +494,10 @@ c3_chart_internal_fn.redraw = function (options, transitions) {
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;
var targetsToShow = $$.filterTargetsToShow($$.data.targets),
tickValues, i, intervalForCulling, xDomainForZoom;
var xv = $$.xv.bind($$),
cx, cy;
options = options || {};
withY = getOption(options, "withY", true);
@ -487,7 +573,7 @@ c3_chart_internal_fn.redraw = function (options, transitions) {
break;
}
}
$$.svg.selectAll('.' + CLASS.axisX + ' .tick text').each(function (e) {
$$.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');
@ -525,11 +611,13 @@ c3_chart_internal_fn.redraw = function (options, transitions) {
.attr("x", $$.width / 2)
.attr("y", $$.height / 2)
.text(config.data_empty_label_text)
.transition()
.transition()
.style('opacity', targetsToShow.length ? 0 : 1);
// event rect
if (withEventRect) { $$.redrawEventRect(); }
if (withEventRect) {
$$.redrawEventRect();
}
// grid
$$.updateGrid(duration);
@ -551,10 +639,14 @@ c3_chart_internal_fn.redraw = function (options, transitions) {
}
// title
if ($$.redrawTitle) { $$.redrawTitle(); }
if ($$.redrawTitle) {
$$.redrawTitle();
}
// arc
if ($$.redrawArc) { $$.redrawArc(duration, durationForExit, withTransform); }
if ($$.redrawArc) {
$$.redrawArc(duration, durationForExit, withTransform);
}
// subchart
if ($$.redrawSubchart) {
@ -596,22 +688,25 @@ c3_chart_internal_fn.redraw = function (options, transitions) {
$$.redrawText(xForText, yForText, options.flow, true, transition),
$$.redrawRegion(true, transition),
$$.redrawGrid(true, transition),
].forEach(function (transitions) {
transitions.forEach(function (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) {
transitionsToWait.forEach(function(t) {
waitForDraw.add(t);
});
waitForDraw(function () {
if (flow) { flow(); }
if (config.onrendered) { config.onrendered.call($$); }
waitForDraw(function() {
if (flow) {
flow();
}
if (config.onrendered) {
config.onrendered.call($$);
}
});
}
else {
} else {
$$.redrawBar(drawBar);
$$.redrawLine(drawLine);
$$.redrawArea(drawArea);
@ -619,19 +714,25 @@ c3_chart_internal_fn.redraw = function (options, transitions) {
$$.redrawText(xForText, yForText, options.flow);
$$.redrawRegion();
$$.redrawGrid();
if (flow) { flow(); }
if (config.onrendered) { config.onrendered.call($$); }
if (flow) {
flow();
}
if (config.onrendered) {
config.onrendered.call($$);
}
}
}
// update fadein condition
$$.mapToIds($$.data.targets).forEach(function (id) {
$$.mapToIds($$.data.targets).forEach(function(id) {
$$.withoutFadeIn[id] = true;
});
};
c3_chart_internal_fn.updateAndRedraw = function (options) {
var $$ = this, config = $$.config, transitions;
ChartInternal.prototype.updateAndRedraw = function(options) {
var $$ = this,
config = $$.config,
transitions;
options = options || {};
// same with redraw
options.withTransition = getOption(options, "withTransition", true);
@ -656,7 +757,7 @@ c3_chart_internal_fn.updateAndRedraw = function (options) {
// Draw with new sizes & scales
$$.redraw(options, transitions);
};
c3_chart_internal_fn.redrawWithoutRescale = function () {
ChartInternal.prototype.redrawWithoutRescale = function() {
this.redraw({
withY: false,
withSubchart: false,
@ -665,23 +766,26 @@ c3_chart_internal_fn.redrawWithoutRescale = function () {
});
};
c3_chart_internal_fn.isTimeSeries = function () {
ChartInternal.prototype.isTimeSeries = function() {
return this.config.axis_x_type === 'timeseries';
};
c3_chart_internal_fn.isCategorized = function () {
ChartInternal.prototype.isCategorized = function() {
return this.config.axis_x_type.indexOf('categor') >= 0;
};
c3_chart_internal_fn.isCustomX = function () {
var $$ = this, config = $$.config;
ChartInternal.prototype.isCustomX = function() {
var $$ = this,
config = $$.config;
return !$$.isTimeSeries() && (config.data_x || notEmpty(config.data_xs));
};
c3_chart_internal_fn.isTimeSeriesY = function () {
ChartInternal.prototype.isTimeSeriesY = function() {
return this.config.axis_y_type === 'timeseries';
};
c3_chart_internal_fn.getTranslate = function (target) {
var $$ = this, config = $$.config, x, y;
ChartInternal.prototype.getTranslate = function(target) {
var $$ = this,
config = $$.config,
x, y;
if (target === 'main') {
x = asHalfPixel($$.margin.left);
y = asHalfPixel($$.margin.top);
@ -705,66 +809,72 @@ c3_chart_internal_fn.getTranslate = function (target) {
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
y = $$.arcHeight / 2 - ($$.hasType('gauge') ? 6 : 0); // to prevent wrong display of min and max label
}
return "translate(" + x + "," + y + ")";
};
c3_chart_internal_fn.initialOpacity = function (d) {
ChartInternal.prototype.initialOpacity = function(d) {
return d.value !== null && this.withoutFadeIn[d.id] ? 1 : 0;
};
c3_chart_internal_fn.initialOpacityForCircle = function (d) {
ChartInternal.prototype.initialOpacityForCircle = function(d) {
return d.value !== null && this.withoutFadeIn[d.id] ? this.opacityForCircle(d) : 0;
};
c3_chart_internal_fn.opacityForCircle = function (d) {
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;
};
c3_chart_internal_fn.opacityForText = function () {
ChartInternal.prototype.opacityForText = function() {
return this.hasDataLabel() ? 1 : 0;
};
c3_chart_internal_fn.xx = function (d) {
ChartInternal.prototype.xx = function(d) {
return d ? this.x(d.x) : null;
};
c3_chart_internal_fn.xv = function (d) {
var $$ = this, value = d.value;
ChartInternal.prototype.xv = function(d) {
var $$ = this,
value = d.value;
if ($$.isTimeSeries()) {
value = $$.parseDate(d.value);
}
else if ($$.isCategorized() && typeof d.value === 'string') {
} else if ($$.isCategorized() && typeof d.value === 'string') {
value = $$.config.axis_x_categories.indexOf(d.value);
}
return Math.ceil($$.x(value));
};
c3_chart_internal_fn.yv = function (d) {
ChartInternal.prototype.yv = function(d) {
var $$ = this,
yScale = d.axis && d.axis === 'y2' ? $$.y2 : $$.y;
return Math.ceil(yScale(d.value));
};
c3_chart_internal_fn.subxx = function (d) {
ChartInternal.prototype.subxx = function(d) {
return d ? this.subX(d.x) : null;
};
c3_chart_internal_fn.transformMain = function (withTransition, transitions) {
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(); }
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 (withTransition) {
yAxis = yAxis.transition();
}
}
if (transitions && transitions.axisY2) {
y2Axis = transitions.axisY2;
} else {
y2Axis = $$.main.select('.' + CLASS.axisY2);
if (withTransition) { y2Axis = y2Axis.transition(); }
if (withTransition) {
y2Axis = y2Axis.transition();
}
}
(withTransition ? $$.main.transition() : $$.main).attr("transform", $$.getTranslate('main'));
xAxis.attr("transform", $$.getTranslate('x'));
@ -772,14 +882,18 @@ c3_chart_internal_fn.transformMain = function (withTransition, transitions) {
y2Axis.attr("transform", $$.getTranslate('y2'));
$$.main.select('.' + CLASS.chartArcs).attr("transform", $$.getTranslate('arc'));
};
c3_chart_internal_fn.transformAll = function (withTransition, transitions) {
ChartInternal.prototype.transformAll = function(withTransition, transitions) {
var $$ = this;
$$.transformMain(withTransition, transitions);
if ($$.config.subchart_show) { $$.transformContext(withTransition, transitions); }
if ($$.legend) { $$.transformLegend(withTransition); }
if ($$.config.subchart_show) {
$$.transformContext(withTransition, transitions);
}
if ($$.legend) {
$$.transformLegend(withTransition);
}
};
c3_chart_internal_fn.updateSvgSize = function () {
ChartInternal.prototype.updateSvgSize = function() {
var $$ = this,
brush = $$.svg.select(".c3-brush .overlay");
$$.svg.attr('width', $$.currentWidth).attr('height', $$.currentHeight);
@ -803,8 +917,7 @@ c3_chart_internal_fn.updateSvgSize = function () {
$$.selectChart.style('max-height', $$.currentHeight + "px");
};
c3_chart_internal_fn.updateDimension = function (withoutAxis) {
ChartInternal.prototype.updateDimension = function(withoutAxis) {
var $$ = this;
if (!withoutAxis) {
if ($$.config.axis_rotated) {
@ -821,23 +934,26 @@ c3_chart_internal_fn.updateDimension = function (withoutAxis) {
$$.transformAll(false);
};
c3_chart_internal_fn.observeInserted = function (selection) {
var $$ = this, observer;
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) {
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 () {
$$.intervalForObserveInserted = window.setInterval(function() {
// parentNode will NOT be null when completed
if (selection.node().parentNode) {
window.clearInterval($$.intervalForObserveInserted);
$$.updateDimension();
if ($$.brush) { $$.brush.update(); }
if ($$.brush) {
$$.brush.update();
}
$$.config.oninit.call($$);
$$.redraw({
withTransform: true,
@ -853,23 +969,28 @@ c3_chart_internal_fn.observeInserted = function (selection) {
}
});
});
observer.observe(selection.node(), {attributes: true, childList: true, characterData: true});
observer.observe(selection.node(), {
attributes: true,
childList: true,
characterData: true
});
};
c3_chart_internal_fn.bindResize = function () {
var $$ = this, config = $$.config;
ChartInternal.prototype.bindResize = function() {
var $$ = this,
config = $$.config;
$$.resizeFunction = $$.generateResize(); // need to call .remove
$$.resizeFunction.add(function () {
$$.resizeFunction.add(function() {
config.onresize.call($$);
});
if (config.resize_auto) {
$$.resizeFunction.add(function () {
$$.resizeFunction.add(function() {
if ($$.resizeTimeout !== undefined) {
window.clearTimeout($$.resizeTimeout);
}
$$.resizeTimeout = window.setTimeout(function () {
$$.resizeTimeout = window.setTimeout(function() {
delete $$.resizeTimeout;
$$.updateAndRedraw({
withUpdateXDomain: false,
@ -878,11 +999,13 @@ c3_chart_internal_fn.bindResize = function () {
withTransitionForTransform: false,
withLegend: true,
});
if ($$.brush) { $$.brush.update(); }
if ($$.brush) {
$$.brush.update();
}
}, 100);
});
}
$$.resizeFunction.add(function () {
$$.resizeFunction.add(function() {
config.onresized.call($$);
});
@ -915,25 +1038,26 @@ c3_chart_internal_fn.bindResize = function () {
window.onresize = function() {
// if element not displayed skip it
if (!$$.api.element.offsetParent) {
return;
return;
}
wrapper();
};
};
}
};
c3_chart_internal_fn.generateResize = function () {
ChartInternal.prototype.generateResize = function() {
var resizeFunctions = [];
function callResizeFunctions() {
resizeFunctions.forEach(function (f) {
resizeFunctions.forEach(function(f) {
f();
});
}
callResizeFunctions.add = function (f) {
callResizeFunctions.add = function(f) {
resizeFunctions.push(f);
};
callResizeFunctions.remove = function (f) {
callResizeFunctions.remove = function(f) {
for (var i = 0; i < resizeFunctions.length; i++) {
if (resizeFunctions[i] === f) {
resizeFunctions.splice(i, 1);
@ -944,20 +1068,24 @@ c3_chart_internal_fn.generateResize = function () {
return callResizeFunctions;
};
c3_chart_internal_fn.endall = function (transition, callback) {
ChartInternal.prototype.endall = function(transition, callback) {
var n = 0;
transition
.each(function () { ++n; })
.on("end", function () {
if (!--n) { callback.apply(this, arguments); }
.each(function() {
++n;
})
.on("end", function() {
if (!--n) {
callback.apply(this, arguments);
}
});
};
c3_chart_internal_fn.generateWait = function () {
ChartInternal.prototype.generateWait = function() {
var transitionsToWait = [],
f = function (callback) {
var timer = setInterval(function () {
f = function(callback) {
var timer = setInterval(function() {
var done = 0;
transitionsToWait.forEach(function (t) {
transitionsToWait.forEach(function(t) {
if (t.empty()) {
done += 1;
return;
@ -970,18 +1098,21 @@ c3_chart_internal_fn.generateWait = function () {
});
if (done === transitionsToWait.length) {
clearInterval(timer);
if (callback) { callback(); }
if (callback) {
callback();
}
}
}, 50);
};
f.add = function (transition) {
f.add = function(transition) {
transitionsToWait.push(transition);
};
return f;
};
c3_chart_internal_fn.parseDate = function (date) {
var $$ = this, parsedDate;
ChartInternal.prototype.parseDate = function(date) {
var $$ = this,
parsedDate;
if (date instanceof Date) {
parsedDate = date;
} else if (typeof date === 'string') {
@ -997,7 +1128,7 @@ c3_chart_internal_fn.parseDate = function (date) {
return parsedDate;
};
c3_chart_internal_fn.isTabVisible = function () {
ChartInternal.prototype.isTabVisible = function() {
var hidden;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
@ -1012,19 +1143,12 @@ c3_chart_internal_fn.isTabVisible = function () {
return document[hidden] ? false : true;
};
c3_chart_internal_fn.isValue = isValue;
c3_chart_internal_fn.isFunction = isFunction;
c3_chart_internal_fn.isString = isString;
c3_chart_internal_fn.isUndefined = isUndefined;
c3_chart_internal_fn.isDefined = isDefined;
c3_chart_internal_fn.ceil10 = ceil10;
c3_chart_internal_fn.asHalfPixel = asHalfPixel;
c3_chart_internal_fn.diffDomain = diffDomain;
c3_chart_internal_fn.isEmpty = isEmpty;
c3_chart_internal_fn.notEmpty = notEmpty;
c3_chart_internal_fn.notEmpty = notEmpty;
c3_chart_internal_fn.getOption = getOption;
c3_chart_internal_fn.hasValue = hasValue;
c3_chart_internal_fn.sanitise = sanitise;
c3_chart_internal_fn.getPathBox = getPathBox;
c3_chart_internal_fn.CLASS = CLASS;
ChartInternal.prototype.getPathBox = getPathBox;
ChartInternal.prototype.CLASS = CLASS;
export {
Chart
};
export {
ChartInternal
};

16
src/data.convert.js

@ -1,7 +1,7 @@
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isValue, isUndefined, isDefined, notEmpty, isArray } from './util';
c3_chart_internal_fn.convertUrlToData = function (url, mimeType, headers, keys, done) {
ChartInternal.prototype.convertUrlToData = function (url, mimeType, headers, keys, done) {
var $$ = this, type = mimeType ? mimeType : 'csv', f, converter;
if (type === 'json') {
@ -21,7 +21,7 @@ c3_chart_internal_fn.convertUrlToData = function (url, mimeType, headers, keys,
throw error;
});
};
c3_chart_internal_fn.convertXsvToData = function (xsv) {
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 }), {}) ] };
@ -31,7 +31,7 @@ c3_chart_internal_fn.convertXsvToData = function (xsv) {
return { keys, rows: [].concat(xsv) };
}
};
c3_chart_internal_fn.convertJsonToData = function (json, keys) {
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
@ -63,7 +63,7 @@ c3_chart_internal_fn.convertJsonToData = function (json, keys) {
}
return data;
};
c3_chart_internal_fn.findValueInJson = function (object, path) {
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('.');
@ -83,7 +83,7 @@ c3_chart_internal_fn.findValueInJson = function (object, path) {
* @param {any[][]} rows The row data
* @return {Object}
*/
c3_chart_internal_fn.convertRowsToData = (rows) => {
ChartInternal.prototype.convertRowsToData = (rows) => {
const newRows = [];
const keys = rows[0];
@ -105,7 +105,7 @@ c3_chart_internal_fn.convertRowsToData = (rows) => {
* @param {any[][]} columns The column data
* @return {Object}
*/
c3_chart_internal_fn.convertColumnsToData = (columns) => {
ChartInternal.prototype.convertColumnsToData = (columns) => {
const newRows = [];
const keys = [];
@ -134,7 +134,7 @@ c3_chart_internal_fn.convertColumnsToData = (columns) => {
* @param {boolean} appendXs True to append to $$.data.xs, False to replace.
* @return {!Array}
*/
c3_chart_internal_fn.convertDataToTargets = function (data, appendXs) {
ChartInternal.prototype.convertDataToTargets = function (data, appendXs) {
var $$ = this, config = $$.config, targets, ids, xs, keys;
// handles format where keys are not orderly provided

259
src/data.js

@ -1,19 +1,29 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { isValue, isFunction, isArray, notEmpty, hasValue } from './util';
import {
ChartInternal
} from './core';
import {
isValue,
isFunction,
isArray,
notEmpty,
hasValue
} from './util';
c3_chart_internal_fn.isX = function (key) {
var $$ = this, config = $$.config;
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));
};
c3_chart_internal_fn.isNotX = function (key) {
ChartInternal.prototype.isNotX = function (key) {
return !this.isX(key);
};
c3_chart_internal_fn.getXKey = function (id) {
var $$ = this, config = $$.config;
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;
};
c3_chart_internal_fn.getXValuesOfXKey = function (key, targets) {
ChartInternal.prototype.getXValuesOfXKey = function (key, targets) {
var $$ = this,
xValues, ids = targets && notEmpty(targets) ? $$.mapToIds(targets) : [];
ids.forEach(function (id) {
@ -23,38 +33,41 @@ c3_chart_internal_fn.getXValuesOfXKey = function (key, targets) {
});
return xValues;
};
c3_chart_internal_fn.getXValue = function (id, i) {
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;
};
c3_chart_internal_fn.getOtherTargetXs = function () {
ChartInternal.prototype.getOtherTargetXs = function () {
var $$ = this,
idsForX = Object.keys($$.data.xs);
return idsForX.length ? $$.data.xs[idsForX[0]] : null;
};
c3_chart_internal_fn.getOtherTargetX = function (index) {
ChartInternal.prototype.getOtherTargetX = function (index) {
var xs = this.getOtherTargetXs();
return xs && index < xs.length ? xs[index] : null;
};
c3_chart_internal_fn.addXs = function (xs) {
ChartInternal.prototype.addXs = function (xs) {
var $$ = this;
Object.keys(xs).forEach(function (id) {
$$.config.data_xs[id] = xs[id];
});
};
c3_chart_internal_fn.addName = function (data) {
var $$ = this, name;
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;
};
c3_chart_internal_fn.getValueOnIndex = function (values, index) {
var valueOnIndex = values.filter(function (v) { return v.index === index; });
ChartInternal.prototype.getValueOnIndex = function (values, index) {
var valueOnIndex = values.filter(function (v) {
return v.index === index;
});
return valueOnIndex.length ? valueOnIndex[0] : null;
};
c3_chart_internal_fn.updateTargetX = function (targets, x) {
ChartInternal.prototype.updateTargetX = function (targets, x) {
var $$ = this;
targets.forEach(function (t) {
t.values.forEach(function (v, i) {
@ -63,7 +76,7 @@ c3_chart_internal_fn.updateTargetX = function (targets, x) {
$$.data.xs[t.id] = x;
});
};
c3_chart_internal_fn.updateTargetXs = function (targets, xs) {
ChartInternal.prototype.updateTargetXs = function (targets, xs) {
var $$ = this;
targets.forEach(function (t) {
if (xs[t.id]) {
@ -71,41 +84,49 @@ c3_chart_internal_fn.updateTargetXs = function (targets, xs) {
}
});
};
c3_chart_internal_fn.generateTargetX = function (rawX, id, index) {
var $$ = this, x;
ChartInternal.prototype.generateTargetX = function (rawX, id, index) {
var $$ = this,
x;
if ($$.isTimeSeries()) {
x = rawX ? $$.parseDate(rawX) : $$.parseDate($$.getXValue(id, index));
}
else if ($$.isCustomX() && !$$.isCategorized()) {
} else if ($$.isCustomX() && !$$.isCategorized()) {
x = isValue(rawX) ? +rawX : $$.getXValue(id, index);
}
else {
} else {
x = index;
}
return x;
};
c3_chart_internal_fn.cloneTarget = function (target) {
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};
id: target.id,
id_org: target.id_org,
values: target.values.map(function (d) {
return {
x: d.x,
value: d.value,
id: d.id
};
})
};
};
c3_chart_internal_fn.getMaxDataCount = function () {
ChartInternal.prototype.getMaxDataCount = function () {
var $$ = this;
return $$.d3.max($$.data.targets, function (t) { return t.values.length; });
return $$.d3.max($$.data.targets, function (t) {
return t.values.length;
});
};
c3_chart_internal_fn.mapToIds = function (targets) {
return targets.map(function (d) { return d.id; });
ChartInternal.prototype.mapToIds = function (targets) {
return targets.map(function (d) {
return d.id;
});
};
c3_chart_internal_fn.mapToTargetIds = function (ids) {
ChartInternal.prototype.mapToTargetIds = function (ids) {
var $$ = this;
return ids ? [].concat(ids) : $$.mapToIds($$.data.targets);
};
c3_chart_internal_fn.hasTarget = function (targets, id) {
var ids = this.mapToIds(targets), i;
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;
@ -113,23 +134,35 @@ c3_chart_internal_fn.hasTarget = function (targets, id) {
}
return false;
};
c3_chart_internal_fn.isTargetToShow = function (targetId) {
ChartInternal.prototype.isTargetToShow = function (targetId) {
return this.hiddenTargetIds.indexOf(targetId) < 0;
};
c3_chart_internal_fn.isLegendToShow = function (targetId) {
ChartInternal.prototype.isLegendToShow = function (targetId) {
return this.hiddenLegendIds.indexOf(targetId) < 0;
};
c3_chart_internal_fn.filterTargetsToShow = function (targets) {
ChartInternal.prototype.filterTargetsToShow = function (targets) {
var $$ = this;
return targets.filter(function (t) { return $$.isTargetToShow(t.id); });
return targets.filter(function (t) {
return $$.isTargetToShow(t.id);
});
};
c3_chart_internal_fn.mapTargetsToUniqueXs = function (targets) {
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; });
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;
});
};
c3_chart_internal_fn.addHiddenTargetIds = function (targetIds) {
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) {
@ -137,10 +170,12 @@ c3_chart_internal_fn.addHiddenTargetIds = function (targetIds) {
}
}
};
c3_chart_internal_fn.removeHiddenTargetIds = function (targetIds) {
this.hiddenTargetIds = this.hiddenTargetIds.filter(function (id) { return targetIds.indexOf(id) < 0; });
ChartInternal.prototype.removeHiddenTargetIds = function (targetIds) {
this.hiddenTargetIds = this.hiddenTargetIds.filter(function (id) {
return targetIds.indexOf(id) < 0;
});
};
c3_chart_internal_fn.addHiddenLegendIds = function (targetIds) {
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) {
@ -148,10 +183,12 @@ c3_chart_internal_fn.addHiddenLegendIds = function (targetIds) {
}
}
};
c3_chart_internal_fn.removeHiddenLegendIds = function (targetIds) {
this.hiddenLegendIds = this.hiddenLegendIds.filter(function (id) { return targetIds.indexOf(id) < 0; });
ChartInternal.prototype.removeHiddenLegendIds = function (targetIds) {
this.hiddenLegendIds = this.hiddenLegendIds.filter(function (id) {
return targetIds.indexOf(id) < 0;
});
};
c3_chart_internal_fn.getValuesAsIdKeyed = function (targets) {
ChartInternal.prototype.getValuesAsIdKeyed = function (targets) {
var ys = {};
targets.forEach(function (t) {
ys[t.id] = [];
@ -161,8 +198,9 @@ c3_chart_internal_fn.getValuesAsIdKeyed = function (targets) {
});
return ys;
};
c3_chart_internal_fn.checkValueInTargets = function (targets, checker) {
var ids = Object.keys(targets), i, j, values;
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++) {
@ -173,24 +211,33 @@ c3_chart_internal_fn.checkValueInTargets = function (targets, checker) {
}
return false;
};
c3_chart_internal_fn.hasNegativeValueInTargets = function (targets) {
return this.checkValueInTargets(targets, function (v) { return v < 0; });
ChartInternal.prototype.hasNegativeValueInTargets = function (targets) {
return this.checkValueInTargets(targets, function (v) {
return v < 0;
});
};
c3_chart_internal_fn.hasPositiveValueInTargets = 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;
});
};
c3_chart_internal_fn.isOrderDesc = function () {
ChartInternal.prototype.isOrderDesc = function () {
var config = this.config;
return typeof(config.data_order) === 'string' && config.data_order.toLowerCase() === 'desc';
return typeof (config.data_order) === 'string' && config.data_order.toLowerCase() === 'desc';
};
c3_chart_internal_fn.isOrderAsc = function () {
ChartInternal.prototype.isOrderAsc = function () {
var config = this.config;
return typeof(config.data_order) === 'string' && config.data_order.toLowerCase() === 'asc';
return typeof (config.data_order) === 'string' && config.data_order.toLowerCase() === 'asc';
};
c3_chart_internal_fn.getOrderFunction = function() {
var $$ = this, config = $$.config, orderAsc = $$.isOrderAsc(), orderDesc = $$.isOrderDesc();
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); };
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);
@ -205,20 +252,26 @@ c3_chart_internal_fn.getOrderFunction = function() {
};
}
};
c3_chart_internal_fn.orderTargets = function (targets) {
ChartInternal.prototype.orderTargets = function (targets) {
var fct = this.getOrderFunction();
if (fct) {
targets.sort(fct);
}
return targets;
};
c3_chart_internal_fn.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.filterByX = function (targets, x) {
return this.d3.merge(targets.map(function (t) {
return t.values;
})).filter(function (v) {
return v.x - x === 0;
});
};
c3_chart_internal_fn.filterRemoveNull = function (data) {
return data.filter(function (d) { return isValue(d.value); });
ChartInternal.prototype.filterRemoveNull = function (data) {
return data.filter(function (d) {
return isValue(d.value);
});
};
c3_chart_internal_fn.filterByXDomain = function (targets, xDomain) {
ChartInternal.prototype.filterByXDomain = function (targets, xDomain) {
return targets.map(function (t) {
return {
id: t.id,
@ -229,7 +282,7 @@ c3_chart_internal_fn.filterByXDomain = function (targets, xDomain) {
};
});
};
c3_chart_internal_fn.hasDataLabel = function () {
ChartInternal.prototype.hasDataLabel = function () {
var config = this.config;
if (typeof config.data_labels === 'boolean' && config.data_labels) {
return true;
@ -238,27 +291,31 @@ c3_chart_internal_fn.hasDataLabel = function () {
}
return false;
};
c3_chart_internal_fn.getDataLabelLength = function (min, max, key) {
ChartInternal.prototype.getDataLabelLength = function (min, max, key) {
var $$ = this,
lengths = [0, 0], paddingCoef = 1.3;
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); })
.text(function (d) {
return $$.dataLabelFormat(d.id)(d);
})
.each(function (d, i) {
lengths[i] = this.getBoundingClientRect()[key] * paddingCoef;
})
.remove();
return lengths;
};
c3_chart_internal_fn.isNoneArc = function (d) {
return this.hasTarget(this.data.targets, d.id);
},
c3_chart_internal_fn.isArc = function (d) {
return 'data' in d && this.hasTarget(this.data.targets, d.data.id);
};
c3_chart_internal_fn.findClosestFromTargets = function (targets, pos) {
var $$ = this, candidates;
ChartInternal.prototype.isNoneArc = function (d) {
return this.hasTarget(this.data.targets, d.id);
},
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) {
@ -268,11 +325,15 @@ c3_chart_internal_fn.findClosestFromTargets = function (targets, pos) {
// decide closest point and return
return $$.findClosest(candidates, pos);
};
c3_chart_internal_fn.findClosest = function (values, pos) {
var $$ = this, minDist = $$.config.point_sensitivity, closest;
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) {
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;
@ -280,7 +341,9 @@ c3_chart_internal_fn.findClosest = function (values, pos) {
});
// find closest point from non-bar
values.filter(function (v) { return v && !$$.isBarType(v.id); }).forEach(function (v) {
values.filter(function (v) {
return v && !$$.isBarType(v.id);
}).forEach(function (v) {
var d = $$.dist(v, pos);
if (d < minDist) {
minDist = d;
@ -290,16 +353,18 @@ c3_chart_internal_fn.findClosest = function (values, pos) {
return closest;
};
c3_chart_internal_fn.dist = function (data, pos) {
var $$ = this, config = $$.config,
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));
};
c3_chart_internal_fn.convertValuesToStep = function (values) {
var converted = [].concat(values), i;
ChartInternal.prototype.convertValuesToStep = function (values) {
var converted = [].concat(values),
i;
if (!this.isCategorized()) {
return values;
@ -322,12 +387,18 @@ c3_chart_internal_fn.convertValuesToStep = function (values) {
return converted;
};
c3_chart_internal_fn.updateDataAttributes = function (name, attrs) {
var $$ = this, config = $$.config, current = config['data_' + name];
if (typeof attrs === 'undefined') { return current; }
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});
$$.redraw({
withLegend: true
});
return current;
};

8
src/data.load.js

@ -1,7 +1,7 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
c3_chart_internal_fn.load = function (targets, args) {
ChartInternal.prototype.load = function (targets, args) {
var $$ = this;
if (targets) {
// filter loading targets if needed
@ -36,7 +36,7 @@ c3_chart_internal_fn.load = function (targets, args) {
if (args.done) { args.done(); }
};
c3_chart_internal_fn.loadFromArgs = function (args) {
ChartInternal.prototype.loadFromArgs = function (args) {
var $$ = this;
if (args.data) {
$$.load($$.convertDataToTargets(args.data), args);
@ -59,7 +59,7 @@ c3_chart_internal_fn.loadFromArgs = function (args) {
$$.load(null, args);
}
};
c3_chart_internal_fn.unload = function (targetIds, done) {
ChartInternal.prototype.unload = function (targetIds, done) {
var $$ = this;
if (!done) {
done = function () {};

20
src/domain.js

@ -1,7 +1,7 @@
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isValue, isDefined, diffDomain, notEmpty } from './util';
c3_chart_internal_fn.getYDomainMin = function (targets) {
ChartInternal.prototype.getYDomainMin = function (targets) {
var $$ = this, config = $$.config,
ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets),
j, k, baseId, idsInGroup, id, hasNegativeValue;
@ -32,7 +32,7 @@ c3_chart_internal_fn.getYDomainMin = function (targets) {
}
return $$.d3.min(Object.keys(ys).map(function (key) { return $$.d3.min(ys[key]); }));
};
c3_chart_internal_fn.getYDomainMax = function (targets) {
ChartInternal.prototype.getYDomainMax = function (targets) {
var $$ = this, config = $$.config,
ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets),
j, k, baseId, idsInGroup, id, hasPositiveValue;
@ -63,7 +63,7 @@ c3_chart_internal_fn.getYDomainMax = function (targets) {
}
return $$.d3.max(Object.keys(ys).map(function (key) { return $$.d3.max(ys[key]); }));
};
c3_chart_internal_fn.getYDomain = function (targets, axisId, xDomain) {
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,
@ -145,19 +145,19 @@ c3_chart_internal_fn.getYDomain = function (targets, axisId, xDomain) {
domain = [yDomainMin - padding_bottom, yDomainMax + padding_top];
return isInverted ? domain.reverse() : domain;
};
c3_chart_internal_fn.getXDomainMin = function (targets) {
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; }); });
};
c3_chart_internal_fn.getXDomainMax = function (targets) {
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; }); });
};
c3_chart_internal_fn.getXDomainPadding = function (domain) {
ChartInternal.prototype.getXDomainPadding = function (domain) {
var $$ = this, config = $$.config,
diff = domain[1] - domain[0],
maxDataCount, padding, paddingLeft, paddingRight;
@ -179,7 +179,7 @@ c3_chart_internal_fn.getXDomainPadding = function (domain) {
}
return {left: paddingLeft, right: paddingRight};
};
c3_chart_internal_fn.getXDomain = function (targets) {
ChartInternal.prototype.getXDomain = function (targets) {
var $$ = this,
xDomain = [$$.getXDomainMin(targets), $$.getXDomainMax(targets)],
firstX = xDomain[0], lastX = xDomain[1],
@ -203,7 +203,7 @@ c3_chart_internal_fn.getXDomain = function (targets) {
}
return [min, max];
};
c3_chart_internal_fn.updateXDomain = function (targets, withUpdateXDomain, withUpdateOrgXDomain, withTrim, domain) {
ChartInternal.prototype.updateXDomain = function (targets, withUpdateXDomain, withUpdateOrgXDomain, withTrim, domain) {
var $$ = this, config = $$.config;
if (withUpdateOrgXDomain) {
@ -222,7 +222,7 @@ c3_chart_internal_fn.updateXDomain = function (targets, withUpdateXDomain, withU
return $$.x.domain();
};
c3_chart_internal_fn.trimXDomain = function (domain) {
ChartInternal.prototype.trimXDomain = function (domain) {
var zoomDomain = this.getZoomDomain(),
min = zoomDomain[0], max = zoomDomain[1];
if (domain[0] <= min) {

8
src/drag.js

@ -1,8 +1,8 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { getPathBox } from './util';
c3_chart_internal_fn.drag = function (mouse) {
ChartInternal.prototype.drag = function (mouse) {
var $$ = this, config = $$.config, main = $$.main, d3 = $$.d3;
var sx, sy, mx, my, minX, maxX, minY, maxY;
@ -59,7 +59,7 @@ c3_chart_internal_fn.drag = function (mouse) {
});
};
c3_chart_internal_fn.dragstart = function (mouse) {
ChartInternal.prototype.dragstart = function (mouse) {
var $$ = this, config = $$.config;
if ($$.hasArcType()) { return; }
if (! config.data_selection_enabled) { return; } // do nothing if not selectable
@ -70,7 +70,7 @@ c3_chart_internal_fn.dragstart = function (mouse) {
$$.dragging = true;
};
c3_chart_internal_fn.dragend = function () {
ChartInternal.prototype.dragend = function () {
var $$ = this, config = $$.config;
if ($$.hasArcType()) { return; }
if (! config.data_selection_enabled) { return; } // do nothing if not selectable

14
src/format.js

@ -1,7 +1,7 @@
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isValue } from './util';
c3_chart_internal_fn.getYFormat = function (forArc) {
ChartInternal.prototype.getYFormat = function (forArc) {
var $$ = this,
formatForY = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.yFormat,
formatForY2 = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.y2Format;
@ -10,23 +10,23 @@ c3_chart_internal_fn.getYFormat = function (forArc) {
return format.call($$, v, ratio);
};
};
c3_chart_internal_fn.yFormat = function (v) {
ChartInternal.prototype.yFormat = function (v) {
var $$ = this, config = $$.config,
format = config.axis_y_tick_format ? config.axis_y_tick_format : $$.defaultValueFormat;
return format(v);
};
c3_chart_internal_fn.y2Format = function (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);
};
c3_chart_internal_fn.defaultValueFormat = function (v) {
ChartInternal.prototype.defaultValueFormat = function (v) {
return isValue(v) ? +v : "";
};
c3_chart_internal_fn.defaultArcValueFormat = function (v, ratio) {
ChartInternal.prototype.defaultArcValueFormat = function (v, ratio) {
return (ratio * 100).toFixed(1) + '%';
};
c3_chart_internal_fn.dataLabelFormat = function (targetId) {
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

34
src/grid.js

@ -1,8 +1,8 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isValue } from './util';
c3_chart_internal_fn.initGrid = function () {
ChartInternal.prototype.initGrid = function () {
var $$ = this, config = $$.config, d3 = $$.d3;
$$.grid = $$.main.append('g')
.attr("clip-path", $$.clipPathForGrid)
@ -22,7 +22,7 @@ c3_chart_internal_fn.initGrid = function () {
$$.xgrid = d3.selectAll([]);
if (!config.grid_lines_front) { $$.initGridLines(); }
};
c3_chart_internal_fn.initGridLines = function () {
ChartInternal.prototype.initGridLines = function () {
var $$ = this, d3 = $$.d3;
$$.gridLines = $$.main.append('g')
.attr("clip-path", $$.clipPathForGrid)
@ -31,7 +31,7 @@ c3_chart_internal_fn.initGridLines = function () {
$$.gridLines.append('g').attr('class', CLASS.ygridLines);
$$.xgridLines = d3.selectAll([]);
};
c3_chart_internal_fn.updateXGrid = function (withoutUpdate) {
ChartInternal.prototype.updateXGrid = function (withoutUpdate) {
var $$ = this, config = $$.config, d3 = $$.d3,
xgridData = $$.generateGridData(config.grid_x_type, $$.x),
tickOffset = $$.isCategorized() ? $$.xAxis.tickOffset() : 0;
@ -73,7 +73,7 @@ c3_chart_internal_fn.updateXGrid = function (withoutUpdate) {
xgrid.exit().remove();
};
c3_chart_internal_fn.updateYGrid = function () {
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)
@ -91,19 +91,19 @@ c3_chart_internal_fn.updateYGrid = function () {
$$.smoothLines($$.ygrid, 'grid');
};
c3_chart_internal_fn.gridTextAnchor = function (d) {
ChartInternal.prototype.gridTextAnchor = function (d) {
return d.position ? d.position : "end";
};
c3_chart_internal_fn.gridTextDx = function (d) {
ChartInternal.prototype.gridTextDx = function (d) {
return d.position === 'start' ? 4 : d.position === 'middle' ? 0 : -4;
};
c3_chart_internal_fn.xGridTextX = function (d) {
ChartInternal.prototype.xGridTextX = function (d) {
return d.position === 'start' ? -this.height : d.position === 'middle' ? -this.height / 2 : 0;
};
c3_chart_internal_fn.yGridTextX = function (d) {
ChartInternal.prototype.yGridTextX = function (d) {
return d.position === 'start' ? 0 : d.position === 'middle' ? this.width / 2 : this.width;
};
c3_chart_internal_fn.updateGrid = function (duration) {
ChartInternal.prototype.updateGrid = function (duration) {
var $$ = this, main = $$.main, config = $$.config,
xgridLine, xgridLineEnter, ygridLine, ygridLineEnter,
xv = $$.xv.bind($$), yv = $$.yv.bind($$),
@ -186,7 +186,7 @@ c3_chart_internal_fn.updateGrid = function (duration) {
.style("opacity", 0)
.remove();
};
c3_chart_internal_fn.redrawGrid = function (withTransition, transition) {
ChartInternal.prototype.redrawGrid = function (withTransition, transition) {
var $$ = this, config = $$.config, xv = $$.xv.bind($$),
lines = $$.xgridLines.select('line'),
texts = $$.xgridLines.select('text');
@ -204,7 +204,7 @@ c3_chart_internal_fn.redrawGrid = function (withTransition, transition) {
.style("opacity", 1)
];
};
c3_chart_internal_fn.showXGridFocus = function (selectedData) {
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),
@ -219,10 +219,10 @@ c3_chart_internal_fn.showXGridFocus = function (selectedData) {
.attr(config.axis_rotated ? 'y2' : 'x2', xx);
$$.smoothLines(focusEl, 'grid');
};
c3_chart_internal_fn.hideXGridFocus = function () {
ChartInternal.prototype.hideXGridFocus = function () {
this.main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden");
};
c3_chart_internal_fn.updateXgridFocus = function () {
ChartInternal.prototype.updateXgridFocus = function () {
var $$ = this, config = $$.config;
$$.main.select('line.' + CLASS.xgridFocus)
.attr("x1", config.axis_rotated ? 0 : -10)
@ -230,7 +230,7 @@ c3_chart_internal_fn.updateXgridFocus = function () {
.attr("y1", config.axis_rotated ? -10 : 0)
.attr("y2", config.axis_rotated ? -10 : $$.height);
};
c3_chart_internal_fn.generateGridData = function (type, scale) {
ChartInternal.prototype.generateGridData = function (type, scale) {
var $$ = this,
gridData = [], xDomain, firstYear, lastYear, i,
tickNum = $$.main.select("." + CLASS.axisX).selectAll('.tick').size();
@ -249,7 +249,7 @@ c3_chart_internal_fn.generateGridData = function (type, scale) {
}
return gridData;
};
c3_chart_internal_fn.getGridFilterToRemove = function (params) {
ChartInternal.prototype.getGridFilterToRemove = function (params) {
return params ? function (line) {
var found = false;
[].concat(params).forEach(function (param) {
@ -260,7 +260,7 @@ c3_chart_internal_fn.getGridFilterToRemove = function (params) {
return found;
} : function () { return true; };
};
c3_chart_internal_fn.removeGridLines = function (params, forX) {
ChartInternal.prototype.removeGridLines = function (params, forX) {
var $$ = this, config = $$.config,
toRemove = $$.getGridFilterToRemove(params),
toShow = function (line) { return !toRemove(line); },

1
src/index.js

@ -1,7 +1,6 @@
import { c3 } from './core';
import './polyfill';
import './api.axis';
import './api.category';
import './api.chart';

10
src/interaction.js

@ -1,7 +1,7 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
c3_chart_internal_fn.initEventRect = function () {
ChartInternal.prototype.initEventRect = function () {
var $$ = this, config = $$.config;
$$.main.select('.' + CLASS.chart).append("g")
@ -21,7 +21,7 @@ c3_chart_internal_fn.initEventRect = function () {
}
}
};
c3_chart_internal_fn.redrawEventRect = function () {
ChartInternal.prototype.redrawEventRect = function () {
var $$ = this, d3 = $$.d3, config = $$.config,
x, y, w, h;
@ -140,11 +140,11 @@ c3_chart_internal_fn.redrawEventRect = function () {
) : function () {}
);
};
c3_chart_internal_fn.getMousePosition = function (data) {
ChartInternal.prototype.getMousePosition = function (data) {
var $$ = this;
return [$$.x(data.x), $$.getYScale(data.id)(data.value)];
};
c3_chart_internal_fn.dispatchEvent = function (type, mouse) {
ChartInternal.prototype.dispatchEvent = function (type, mouse) {
var $$ = this,
selector = '.' + CLASS.eventRect,
eventRect = $$.main.select(selector).node(),

36
src/legend.js

@ -1,8 +1,8 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isDefined, isEmpty, getOption } from './util';
c3_chart_internal_fn.initLegend = function () {
ChartInternal.prototype.initLegend = function () {
var $$ = this;
$$.legendItemTextBox = {};
$$.legendHasRendered = false;
@ -16,11 +16,11 @@ c3_chart_internal_fn.initLegend = function () {
// MEMO: translate will be upated by this, so transform not needed in updateLegend()
$$.updateLegendWithDefaults();
};
c3_chart_internal_fn.updateLegendWithDefaults = function () {
ChartInternal.prototype.updateLegendWithDefaults = function () {
var $$ = this;
$$.updateLegend($$.mapToIds($$.data.targets), {withTransform: false, withTransitionForTransform: false, withTransition: false});
};
c3_chart_internal_fn.updateSizeForLegend = function (legendHeight, legendWidth) {
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
@ -33,24 +33,24 @@ c3_chart_internal_fn.updateSizeForLegend = function (legendHeight, legendWidth)
left: $$.isLegendRight ? $$.currentWidth - legendWidth : $$.isLegendInset ? insetLegendPosition.left : 0
};
};
c3_chart_internal_fn.transformLegend = function (withTransition) {
ChartInternal.prototype.transformLegend = function (withTransition) {
var $$ = this;
(withTransition ? $$.legend.transition() : $$.legend).attr("transform", $$.getTranslate('legend'));
};
c3_chart_internal_fn.updateLegendStep = function (step) {
ChartInternal.prototype.updateLegendStep = function (step) {
this.legendStep = step;
};
c3_chart_internal_fn.updateLegendItemWidth = function (w) {
ChartInternal.prototype.updateLegendItemWidth = function (w) {
this.legendItemWidth = w;
};
c3_chart_internal_fn.updateLegendItemHeight = function (h) {
ChartInternal.prototype.updateLegendItemHeight = function (h) {
this.legendItemHeight = h;
};
c3_chart_internal_fn.getLegendWidth = function () {
ChartInternal.prototype.getLegendWidth = function () {
var $$ = this;
return $$.config.legend_show ? $$.isLegendRight || $$.isLegendInset ? $$.legendItemWidth * ($$.legendStep + 1) : $$.currentWidth : 0;
};
c3_chart_internal_fn.getLegendHeight = function () {
ChartInternal.prototype.getLegendHeight = function () {
var $$ = this, h = 0;
if ($$.config.legend_show) {
if ($$.isLegendRight) {
@ -61,13 +61,13 @@ c3_chart_internal_fn.getLegendHeight = function () {
}
return h;
};
c3_chart_internal_fn.opacityForLegend = function (legendItem) {
ChartInternal.prototype.opacityForLegend = function (legendItem) {
return legendItem.classed(CLASS.legendItemHidden) ? null : 1;
};
c3_chart_internal_fn.opacityForUnfocusedLegend = function (legendItem) {
ChartInternal.prototype.opacityForUnfocusedLegend = function (legendItem) {
return legendItem.classed(CLASS.legendItemHidden) ? null : 0.3;
};
c3_chart_internal_fn.toggleFocusLegend = function (targetIds, focus) {
ChartInternal.prototype.toggleFocusLegend = function (targetIds, focus) {
var $$ = this;
targetIds = $$.mapToTargetIds(targetIds);
$$.legend.selectAll('.' + CLASS.legendItem)
@ -79,14 +79,14 @@ c3_chart_internal_fn.toggleFocusLegend = function (targetIds, focus) {
return opacity.call($$, $$.d3.select(this));
});
};
c3_chart_internal_fn.revertLegend = function () {
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)); });
};
c3_chart_internal_fn.showLegend = function (targetIds) {
ChartInternal.prototype.showLegend = function (targetIds) {
var $$ = this, config = $$.config;
if (!config.legend_show) {
config.legend_show = true;
@ -101,7 +101,7 @@ c3_chart_internal_fn.showLegend = function (targetIds) {
.transition()
.style('opacity', function () { return $$.opacityForLegend($$.d3.select(this)); });
};
c3_chart_internal_fn.hideLegend = function (targetIds) {
ChartInternal.prototype.hideLegend = function (targetIds) {
var $$ = this, config = $$.config;
if (config.legend_show && isEmpty(targetIds)) {
config.legend_show = false;
@ -112,10 +112,10 @@ c3_chart_internal_fn.hideLegend = function (targetIds) {
.style('opacity', 0)
.style('visibility', 'hidden');
};
c3_chart_internal_fn.clearLegendItemTextBoxCache = function () {
ChartInternal.prototype.clearLegendItemTextBoxCache = function () {
this.legendItemTextBox = {};
};
c3_chart_internal_fn.updateLegend = function (targetIds, options, transitions) {
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;

1218
src/polyfill.js

File diff suppressed because it is too large Load Diff

18
src/region.js

@ -1,14 +1,14 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isValue } from './util';
c3_chart_internal_fn.initRegion = function () {
ChartInternal.prototype.initRegion = function () {
var $$ = this;
$$.region = $$.main.append('g')
.attr("clip-path", $$.clipPath)
.attr("class", CLASS.regions);
};
c3_chart_internal_fn.updateRegion = function (duration) {
ChartInternal.prototype.updateRegion = function (duration) {
var $$ = this, config = $$.config;
// hide if arc type
@ -28,7 +28,7 @@ c3_chart_internal_fn.updateRegion = function (duration) {
.style("opacity", 0)
.remove();
};
c3_chart_internal_fn.redrawRegion = function (withTransition, transition) {
ChartInternal.prototype.redrawRegion = function (withTransition, transition) {
var $$ = this, regions = $$.mainRegion;
return [(withTransition ? regions.transition(transition) : regions)
.attr("x", $$.regionX.bind($$))
@ -38,7 +38,7 @@ c3_chart_internal_fn.redrawRegion = function (withTransition, transition) {
.style("fill-opacity", function (d) { return isValue(d.opacity) ? d.opacity : 0.1; })
];
};
c3_chart_internal_fn.regionX = function (d) {
ChartInternal.prototype.regionX = function (d) {
var $$ = this, config = $$.config,
xPos, yScale = d.axis === 'y' ? $$.y : $$.y2;
if (d.axis === 'y' || d.axis === 'y2') {
@ -48,7 +48,7 @@ c3_chart_internal_fn.regionX = function (d) {
}
return xPos;
};
c3_chart_internal_fn.regionY = function (d) {
ChartInternal.prototype.regionY = function (d) {
var $$ = this, config = $$.config,
yPos, yScale = d.axis === 'y' ? $$.y : $$.y2;
if (d.axis === 'y' || d.axis === 'y2') {
@ -58,7 +58,7 @@ c3_chart_internal_fn.regionY = function (d) {
}
return yPos;
};
c3_chart_internal_fn.regionWidth = function (d) {
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') {
@ -68,7 +68,7 @@ c3_chart_internal_fn.regionWidth = function (d) {
}
return end < start ? 0 : end - start;
};
c3_chart_internal_fn.regionHeight = function (d) {
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') {
@ -78,6 +78,6 @@ c3_chart_internal_fn.regionHeight = function (d) {
}
return end < start ? 0 : end - start;
};
c3_chart_internal_fn.isRegionOnX = function (d) {
ChartInternal.prototype.isRegionOnX = function (d) {
return !d.axis || d.axis === 'x';
};

14
src/scale.js

@ -1,9 +1,9 @@
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
c3_chart_internal_fn.getScale = function (min, max, forTimeseries) {
ChartInternal.prototype.getScale = function (min, max, forTimeseries) {
return (forTimeseries ? this.d3.scaleTime() : this.d3.scaleLinear()).range([min, max]);
};
c3_chart_internal_fn.getX = function (min, max, domain, offset) {
ChartInternal.prototype.getX = function (min, max, domain, offset) {
var $$ = this,
scale = $$.getScale(min, max, $$.isTimeSeries()),
_scale = domain ? scale.domain(domain) : scale, key;
@ -40,18 +40,18 @@ c3_chart_internal_fn.getX = function (min, max, domain, offset) {
}
return scale;
};
c3_chart_internal_fn.getY = function (min, max, domain) {
ChartInternal.prototype.getY = function (min, max, domain) {
var scale = this.getScale(min, max, this.isTimeSeriesY());
if (domain) { scale.domain(domain); }
return scale;
};
c3_chart_internal_fn.getYScale = function (id) {
ChartInternal.prototype.getYScale = function (id) {
return this.axis.getId(id) === 'y2' ? this.y2 : this.y;
};
c3_chart_internal_fn.getSubYScale = function (id) {
ChartInternal.prototype.getSubYScale = function (id) {
return this.axis.getId(id) === 'y2' ? this.subY2 : this.subY;
};
c3_chart_internal_fn.updateScales = function () {
ChartInternal.prototype.updateScales = function () {
var $$ = this, config = $$.config,
forInit = !$$.x;
// update edges

18
src/selection.js

@ -1,7 +1,7 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
c3_chart_internal_fn.selectPoint = function (target, d, i) {
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($$),
@ -19,7 +19,7 @@ c3_chart_internal_fn.selectPoint = function (target, d, i) {
.transition().duration(100)
.attr("r", r);
};
c3_chart_internal_fn.unselectPoint = function (target, d, i) {
ChartInternal.prototype.unselectPoint = function (target, d, i) {
var $$ = this;
$$.config.data_onunselected.call($$.api, d, target.node());
// remove selected-circle from low layer g
@ -27,10 +27,10 @@ c3_chart_internal_fn.unselectPoint = function (target, d, i) {
.transition().duration(100).attr('r', 0)
.remove();
};
c3_chart_internal_fn.togglePoint = function (selected, target, d, i) {
ChartInternal.prototype.togglePoint = function (selected, target, d, i) {
selected ? this.selectPoint(target, d, i) : this.unselectPoint(target, d, i);
};
c3_chart_internal_fn.selectPath = function (target, d) {
ChartInternal.prototype.selectPath = function (target, d) {
var $$ = this;
$$.config.data_onselected.call($$, d, target.node());
if ($$.config.interaction_brighten) {
@ -38,7 +38,7 @@ c3_chart_internal_fn.selectPath = function (target, d) {
.style("fill", function () { return $$.d3.rgb($$.color(d)).brighter(0.75); });
}
};
c3_chart_internal_fn.unselectPath = function (target, d) {
ChartInternal.prototype.unselectPath = function (target, d) {
var $$ = this;
$$.config.data_onunselected.call($$, d, target.node());
if ($$.config.interaction_brighten) {
@ -46,10 +46,10 @@ c3_chart_internal_fn.unselectPath = function (target, d) {
.style("fill", function () { return $$.color(d); });
}
};
c3_chart_internal_fn.togglePath = function (selected, target, d, i) {
ChartInternal.prototype.togglePath = function (selected, target, d, i) {
selected ? this.selectPath(target, d, i) : this.unselectPath(target, d, i);
};
c3_chart_internal_fn.getToggle = function (that, d) {
ChartInternal.prototype.getToggle = function (that, d) {
var $$ = this, toggle;
if (that.nodeName === 'circle') {
if ($$.isStepType(d)) {
@ -64,7 +64,7 @@ c3_chart_internal_fn.getToggle = function (that, d) {
}
return toggle;
};
c3_chart_internal_fn.toggleShape = function (that, d, i) {
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($$);

24
src/shape.bar.js

@ -1,13 +1,13 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isValue } from './util';
c3_chart_internal_fn.initBar = function () {
ChartInternal.prototype.initBar = function () {
var $$ = this;
$$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartBars);
};
c3_chart_internal_fn.updateTargetsForBar = function (targets) {
ChartInternal.prototype.updateTargetsForBar = function (targets) {
var $$ = this, config = $$.config,
mainBars, mainBarEnter,
classChartBar = $$.classChartBar.bind($$),
@ -25,7 +25,7 @@ c3_chart_internal_fn.updateTargetsForBar = function (targets) {
.style("cursor", function (d) { return config.data_selection_isselectable(d) ? "pointer" : null; });
};
c3_chart_internal_fn.updateBar = function (durationForExit) {
ChartInternal.prototype.updateBar = function (durationForExit) {
var $$ = this,
barData = $$.barData.bind($$),
classBar = $$.classBar.bind($$),
@ -42,7 +42,7 @@ c3_chart_internal_fn.updateBar = function (durationForExit) {
mainBar.exit().transition().duration(durationForExit)
.style("opacity", 0);
};
c3_chart_internal_fn.redrawBar = function (drawBar, withTransition, transition) {
ChartInternal.prototype.redrawBar = function (drawBar, withTransition, transition) {
return [
(withTransition ? this.mainBar.transition(transition) : this.mainBar)
.attr('d', drawBar)
@ -51,25 +51,25 @@ c3_chart_internal_fn.redrawBar = function (drawBar, withTransition, transition)
.style("opacity", 1)
];
};
c3_chart_internal_fn.getBarW = function (axis, barTargetsNum) {
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;
};
c3_chart_internal_fn.getBars = function (i, id) {
ChartInternal.prototype.getBars = function (i, id) {
var $$ = this;
return (id ? $$.main.selectAll('.' + CLASS.bars + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.bar + (isValue(i) ? '-' + i : ''));
};
c3_chart_internal_fn.expandBars = function (i, id, reset) {
ChartInternal.prototype.expandBars = function (i, id, reset) {
var $$ = this;
if (reset) { $$.unexpandBars(); }
$$.getBars(i, id).classed(CLASS.EXPANDED, true);
};
c3_chart_internal_fn.unexpandBars = function (i) {
ChartInternal.prototype.unexpandBars = function (i) {
var $$ = this;
$$.getBars(i).classed(CLASS.EXPANDED, false);
};
c3_chart_internal_fn.generateDrawBar = function (barIndices, isSub) {
ChartInternal.prototype.generateDrawBar = function (barIndices, isSub) {
var $$ = this, config = $$.config,
getPoints = $$.generateGetBarPoints(barIndices, isSub);
return function (d, i) {
@ -89,7 +89,7 @@ c3_chart_internal_fn.generateDrawBar = function (barIndices, isSub) {
return path;
};
};
c3_chart_internal_fn.generateGetBarPoints = function (barIndices, isSub) {
ChartInternal.prototype.generateGetBarPoints = function (barIndices, isSub) {
var $$ = this,
axis = isSub ? $$.subXAxis : $$.xAxis,
barTargetsNum = barIndices.__max__ + 1,
@ -116,7 +116,7 @@ c3_chart_internal_fn.generateGetBarPoints = function (barIndices, isSub) {
];
};
};
c3_chart_internal_fn.isWithinBar = function (mouse, that) {
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),

14
src/shape.js

@ -1,8 +1,8 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isUndefined } from './util';
c3_chart_internal_fn.getShapeIndices = function (typeFilter) {
ChartInternal.prototype.getShapeIndices = function (typeFilter) {
var $$ = this, config = $$.config,
indices = {}, i = 0, j, k;
$$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$)).forEach(function (d) {
@ -20,21 +20,21 @@ c3_chart_internal_fn.getShapeIndices = function (typeFilter) {
indices.__max__ = i - 1;
return indices;
};
c3_chart_internal_fn.getShapeX = function (offset, targetsNum, indices, isSub) {
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;
};
};
c3_chart_internal_fn.getShapeY = function (isSub) {
ChartInternal.prototype.getShapeY = function (isSub) {
var $$ = this;
return function (d) {
var scale = isSub ? $$.getSubYScale(d.id) : $$.getYScale(d.id);
return scale(d.value);
};
};
c3_chart_internal_fn.getShapeOffset = function (typeFilter, indices, isSub) {
ChartInternal.prototype.getShapeOffset = function (typeFilter, indices, isSub) {
var $$ = this,
targets = $$.orderTargets($$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$))),
targetIds = targets.map(function (t) { return t.id; });
@ -63,7 +63,7 @@ c3_chart_internal_fn.getShapeOffset = function (typeFilter, indices, isSub) {
return offset;
};
};
c3_chart_internal_fn.isWithinShape = function (that, d) {
ChartInternal.prototype.isWithinShape = function (that, d) {
var $$ = this,
shape = $$.d3.select(that), isWithin;
if (!$$.isTargetToShow(d.id)) {
@ -79,7 +79,7 @@ c3_chart_internal_fn.isWithinShape = function (that, d) {
};
c3_chart_internal_fn.getInterpolate = function (d) {
ChartInternal.prototype.getInterpolate = function (d) {
var $$ = this, d3 = $$.d3,
types = {
'linear': d3.curveLinear,

50
src/shape.line.js

@ -1,13 +1,13 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isValue, isFunction, isUndefined, isDefined } from './util';
c3_chart_internal_fn.initLine = function () {
ChartInternal.prototype.initLine = function () {
var $$ = this;
$$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartLines);
};
c3_chart_internal_fn.updateTargetsForLine = function (targets) {
ChartInternal.prototype.updateTargetsForLine = function (targets) {
var $$ = this, config = $$.config,
mainLines, mainLineEnter,
classChartLine = $$.classChartLine.bind($$),
@ -43,7 +43,7 @@ c3_chart_internal_fn.updateTargetsForLine = function (targets) {
// MEMO: can not keep same color...
//mainLineUpdate.exit().remove();
};
c3_chart_internal_fn.updateLine = function (durationForExit) {
ChartInternal.prototype.updateLine = function (durationForExit) {
var $$ = this;
var mainLine = $$.main.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line)
.data($$.lineData.bind($$));
@ -57,7 +57,7 @@ c3_chart_internal_fn.updateLine = function (durationForExit) {
mainLine.exit().transition().duration(durationForExit)
.style('opacity', 0);
};
c3_chart_internal_fn.redrawLine = function (drawLine, withTransition, transition) {
ChartInternal.prototype.redrawLine = function (drawLine, withTransition, transition) {
return [
(withTransition ? this.mainLine.transition(transition) : this.mainLine)
.attr("d", drawLine)
@ -65,7 +65,7 @@ c3_chart_internal_fn.redrawLine = function (drawLine, withTransition, transition
.style("opacity", 1)
];
};
c3_chart_internal_fn.generateDrawLine = function (lineIndices, isSub) {
ChartInternal.prototype.generateDrawLine = function (lineIndices, isSub) {
var $$ = this, config = $$.config,
line = $$.d3.line(),
getPoints = $$.generateGetLinePoints(lineIndices, isSub),
@ -97,7 +97,7 @@ c3_chart_internal_fn.generateDrawLine = function (lineIndices, isSub) {
return path ? path : "M 0 0";
};
};
c3_chart_internal_fn.generateGetLinePoints = function (lineIndices, isSub) { // partial duplication of generateGetBarPoints
ChartInternal.prototype.generateGetLinePoints = function (lineIndices, isSub) { // partial duplication of generateGetBarPoints
var $$ = this, config = $$.config,
lineTargetsNum = lineIndices.__max__ + 1,
x = $$.getShapeX(0, lineTargetsNum, lineIndices, !!isSub),
@ -123,7 +123,7 @@ c3_chart_internal_fn.generateGetLinePoints = function (lineIndices, isSub) { //
};
c3_chart_internal_fn.lineWithRegions = function (d, x, y, _regions) {
ChartInternal.prototype.lineWithRegions = function (d, x, y, _regions) {
var $$ = this, config = $$.config,
prev = -1, i, j,
s = "M", sWithRegion,
@ -219,7 +219,7 @@ c3_chart_internal_fn.lineWithRegions = function (d, x, y, _regions) {
};
c3_chart_internal_fn.updateArea = function (durationForExit) {
ChartInternal.prototype.updateArea = function (durationForExit) {
var $$ = this, d3 = $$.d3;
var mainArea = $$.main.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area)
.data($$.lineData.bind($$));
@ -232,7 +232,7 @@ c3_chart_internal_fn.updateArea = function (durationForExit) {
mainArea.exit().transition().duration(durationForExit)
.style('opacity', 0);
};
c3_chart_internal_fn.redrawArea = function (drawArea, withTransition, transition) {
ChartInternal.prototype.redrawArea = function (drawArea, withTransition, transition) {
return [
(withTransition ? this.mainArea.transition(transition) : this.mainArea)
.attr("d", drawArea)
@ -240,7 +240,7 @@ c3_chart_internal_fn.redrawArea = function (drawArea, withTransition, transition
.style("opacity", this.orgAreaOpacity)
];
};
c3_chart_internal_fn.generateDrawArea = function (areaIndices, isSub) {
ChartInternal.prototype.generateDrawArea = function (areaIndices, isSub) {
var $$ = this, config = $$.config, area = $$.d3.area(),
getPoints = $$.generateGetAreaPoints(areaIndices, isSub),
yScaleGetter = isSub ? $$.getSubYScale : $$.getYScale,
@ -273,10 +273,10 @@ c3_chart_internal_fn.generateDrawArea = function (areaIndices, isSub) {
return path ? path : "M 0 0";
};
};
c3_chart_internal_fn.getAreaBaseValue = function () {
ChartInternal.prototype.getAreaBaseValue = function () {
return 0;
};
c3_chart_internal_fn.generateGetAreaPoints = function (areaIndices, isSub) { // partial duplication of generateGetBarPoints
ChartInternal.prototype.generateGetAreaPoints = function (areaIndices, isSub) { // partial duplication of generateGetBarPoints
var $$ = this, config = $$.config,
areaTargetsNum = areaIndices.__max__ + 1,
x = $$.getShapeX(0, areaTargetsNum, areaIndices, !!isSub),
@ -302,7 +302,7 @@ c3_chart_internal_fn.generateGetAreaPoints = function (areaIndices, isSub) { //
};
c3_chart_internal_fn.updateCircle = function (cx, cy) {
ChartInternal.prototype.updateCircle = function (cx, cy) {
var $$ = this;
var mainCircle = $$.main.selectAll('.' + CLASS.circles).selectAll('.' + CLASS.circle)
.data($$.lineOrScatterData.bind($$));
@ -317,7 +317,7 @@ c3_chart_internal_fn.updateCircle = function (cx, cy) {
mainCircle.exit()
.style("opacity", 0);
};
c3_chart_internal_fn.redrawCircle = function (cx, cy, withTransition, transition) {
ChartInternal.prototype.redrawCircle = function (cx, cy, withTransition, transition) {
var $$ = this,
selectedCircles = $$.main.selectAll('.' + CLASS.selectedCircle);
return [
@ -331,10 +331,10 @@ c3_chart_internal_fn.redrawCircle = function (cx, cy, withTransition, transition
.attr("cy", cy)
];
};
c3_chart_internal_fn.circleX = function (d) {
ChartInternal.prototype.circleX = function (d) {
return d.x || d.x === 0 ? this.x(d.x) : null;
};
c3_chart_internal_fn.updateCircleY = function () {
ChartInternal.prototype.updateCircleY = function () {
var $$ = this, lineIndices, getPoints;
if ($$.config.data_groups.length > 0) {
lineIndices = $$.getShapeIndices($$.isLineType),
@ -348,11 +348,11 @@ c3_chart_internal_fn.updateCircleY = function () {
};
}
};
c3_chart_internal_fn.getCircles = function (i, id) {
ChartInternal.prototype.getCircles = function (i, id) {
var $$ = this;
return (id ? $$.main.selectAll('.' + CLASS.circles + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.circle + (isValue(i) ? '-' + i : ''));
};
c3_chart_internal_fn.expandCircles = function (i, id, reset) {
ChartInternal.prototype.expandCircles = function (i, id, reset) {
var $$ = this,
r = $$.pointExpandedR.bind($$);
if (reset) { $$.unexpandCircles(); }
@ -360,7 +360,7 @@ c3_chart_internal_fn.expandCircles = function (i, id, reset) {
.classed(CLASS.EXPANDED, true)
.attr('r', r);
};
c3_chart_internal_fn.unexpandCircles = function (i) {
ChartInternal.prototype.unexpandCircles = function (i) {
var $$ = this,
r = $$.pointR.bind($$);
$$.getCircles(i)
@ -368,11 +368,11 @@ c3_chart_internal_fn.unexpandCircles = function (i) {
.classed(CLASS.EXPANDED, false)
.attr('r', r);
};
c3_chart_internal_fn.pointR = function (d) {
ChartInternal.prototype.pointR = function (d) {
var $$ = this, config = $$.config;
return $$.isStepType(d) ? 0 : (isFunction(config.point_r) ? config.point_r(d) : config.point_r);
};
c3_chart_internal_fn.pointExpandedR = function (d) {
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);
@ -380,16 +380,16 @@ c3_chart_internal_fn.pointExpandedR = function (d) {
return $$.pointR(d);
}
};
c3_chart_internal_fn.pointSelectR = function (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);
};
c3_chart_internal_fn.isWithinCircle = function (that, r) {
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;
};
c3_chart_internal_fn.isWithinStep = function (that, y) {
ChartInternal.prototype.isWithinStep = function (that, y) {
return Math.abs(y - this.d3.mouse(that)[1]) < 30;
};

26
src/size.js

@ -1,17 +1,17 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isValue, ceil10 } from './util';
c3_chart_internal_fn.getCurrentWidth = function () {
ChartInternal.prototype.getCurrentWidth = function () {
var $$ = this, config = $$.config;
return config.size_width ? config.size_width : $$.getParentWidth();
};
c3_chart_internal_fn.getCurrentHeight = function () {
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);
};
c3_chart_internal_fn.getCurrentPaddingTop = function () {
ChartInternal.prototype.getCurrentPaddingTop = function () {
var $$ = this,
config = $$.config,
padding = isValue(config.padding_top) ? config.padding_top : 0;
@ -20,11 +20,11 @@ c3_chart_internal_fn.getCurrentPaddingTop = function () {
}
return padding;
};
c3_chart_internal_fn.getCurrentPaddingBottom = function () {
ChartInternal.prototype.getCurrentPaddingBottom = function () {
var config = this.config;
return isValue(config.padding_bottom) ? config.padding_bottom : 0;
};
c3_chart_internal_fn.getCurrentPaddingLeft = function (withoutRecompute) {
ChartInternal.prototype.getCurrentPaddingLeft = function (withoutRecompute) {
var $$ = this, config = $$.config;
if (isValue(config.padding_left)) {
return config.padding_left;
@ -36,7 +36,7 @@ c3_chart_internal_fn.getCurrentPaddingLeft = function (withoutRecompute) {
return ceil10($$.getAxisWidthByAxisId('y', withoutRecompute));
}
};
c3_chart_internal_fn.getCurrentPaddingRight = function () {
ChartInternal.prototype.getCurrentPaddingRight = function () {
var $$ = this, config = $$.config,
defaultPadding = 10, legendWidthOnRight = $$.isLegendRight ? $$.getLegendWidth() + 20 : 0;
if (isValue(config.padding_right)) {
@ -50,7 +50,7 @@ c3_chart_internal_fn.getCurrentPaddingRight = function () {
}
};
c3_chart_internal_fn.getParentRectValue = function (key) {
ChartInternal.prototype.getParentRectValue = function (key) {
var parent = this.selectChart.node(), v;
while (parent && parent.tagName !== 'BODY') {
try {
@ -69,16 +69,16 @@ c3_chart_internal_fn.getParentRectValue = function (key) {
}
return v;
};
c3_chart_internal_fn.getParentWidth = function () {
ChartInternal.prototype.getParentWidth = function () {
return this.getParentRectValue('width');
};
c3_chart_internal_fn.getParentHeight = function () {
ChartInternal.prototype.getParentHeight = function () {
var h = this.selectChart.style('height');
return h.indexOf('px') > 0 ? +h.replace('px', '') : 0;
};
c3_chart_internal_fn.getSvgLeft = function (withoutRecompute) {
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,
@ -91,11 +91,11 @@ c3_chart_internal_fn.getSvgLeft = function (withoutRecompute) {
};
c3_chart_internal_fn.getAxisWidthByAxisId = function (id, withoutRecompute) {
ChartInternal.prototype.getAxisWidthByAxisId = function (id, withoutRecompute) {
var $$ = this, position = $$.axis.getLabelPositionById(id);
return $$.axis.getMaxTickWidth(id, withoutRecompute) + (position.isInner ? 20 : 40);
};
c3_chart_internal_fn.getHorizontalAxisHeight = function (axisId) {
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; }

30
src/subchart.js

@ -1,8 +1,8 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isFunction } from './util';
c3_chart_internal_fn.initBrush = function (scale) {
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 () {
@ -59,7 +59,7 @@ c3_chart_internal_fn.initBrush = function (scale) {
};
return $$.brush.updateScale(scale);
};
c3_chart_internal_fn.initSubchart = function () {
ChartInternal.prototype.initSubchart = function () {
var $$ = this, config = $$.config,
context = $$.context = $$.svg.append("g").attr("transform", $$.getTranslate('context')),
visibility = config.subchart_show ? 'visible' : 'hidden';
@ -92,13 +92,13 @@ c3_chart_internal_fn.initSubchart = function () {
.attr("transform", $$.getTranslate('subx'))
.attr("clip-path", config.axis_rotated ? "" : $$.clipPathForXAxis);
};
c3_chart_internal_fn.initSubchartBrush = function () {
ChartInternal.prototype.initSubchartBrush = function () {
var $$ = this;
// Add extent rect for Brush
$$.initBrush($$.subX).updateExtent();
$$.context.select('.' + CLASS.brush).call($$.brush);
};
c3_chart_internal_fn.updateTargetsForSubchart = function (targets) {
ChartInternal.prototype.updateTargetsForSubchart = function (targets) {
var $$ = this, context = $$.context, config = $$.config,
contextLineEnter, contextLine, contextBarEnter, contextBar,
classChartBar = $$.classChartBar.bind($$),
@ -138,7 +138,7 @@ c3_chart_internal_fn.updateTargetsForSubchart = function (targets) {
.attr(config.axis_rotated ? "width" : "height", config.axis_rotated ? $$.width2 : $$.height2);
}
};
c3_chart_internal_fn.updateBarForSubchart = function (durationForExit) {
ChartInternal.prototype.updateBarForSubchart = function (durationForExit) {
var $$ = this;
var contextBar = $$.context.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar)
.data($$.barData.bind($$));
@ -152,12 +152,12 @@ c3_chart_internal_fn.updateBarForSubchart = function (durationForExit) {
$$.contextBar = contextBarEnter.merge(contextBar)
.style("opacity", $$.initialOpacity.bind($$));
};
c3_chart_internal_fn.redrawBarForSubchart = function (drawBarOnSub, withTransition, duration) {
ChartInternal.prototype.redrawBarForSubchart = function (drawBarOnSub, withTransition, duration) {
(withTransition ? this.contextBar.transition(Math.random().toString()).duration(duration) : this.contextBar)
.attr('d', drawBarOnSub)
.style('opacity', 1);
};
c3_chart_internal_fn.updateLineForSubchart = function (durationForExit) {
ChartInternal.prototype.updateLineForSubchart = function (durationForExit) {
var $$ = this;
var contextLine = $$.context.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line)
.data($$.lineData.bind($$));
@ -170,12 +170,12 @@ c3_chart_internal_fn.updateLineForSubchart = function (durationForExit) {
$$.contextLine = contextLineEnter.merge(contextLine)
.style("opacity", $$.initialOpacity.bind($$));
};
c3_chart_internal_fn.redrawLineForSubchart = function (drawLineOnSub, withTransition, duration) {
ChartInternal.prototype.redrawLineForSubchart = function (drawLineOnSub, withTransition, duration) {
(withTransition ? this.contextLine.transition(Math.random().toString()).duration(duration) : this.contextLine)
.attr("d", drawLineOnSub)
.style('opacity', 1);
};
c3_chart_internal_fn.updateAreaForSubchart = function (durationForExit) {
ChartInternal.prototype.updateAreaForSubchart = function (durationForExit) {
var $$ = this, d3 = $$.d3;
var contextArea = $$.context.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area)
.data($$.lineData.bind($$));
@ -189,13 +189,13 @@ c3_chart_internal_fn.updateAreaForSubchart = function (durationForExit) {
$$.contextArea = contextAreaEnter.merge(contextArea)
.style("opacity", 0);
};
c3_chart_internal_fn.redrawAreaForSubchart = function (drawAreaOnSub, withTransition, duration) {
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);
};
c3_chart_internal_fn.redrawSubchart = function (withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices) {
ChartInternal.prototype.redrawSubchart = function (withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices) {
var $$ = this, d3 = $$.d3, config = $$.config,
drawAreaOnSub, drawBarOnSub, drawLineOnSub;
@ -228,7 +228,7 @@ c3_chart_internal_fn.redrawSubchart = function (withSubchart, transitions, durat
}
}
};
c3_chart_internal_fn.redrawForBrush = function () {
ChartInternal.prototype.redrawForBrush = function () {
var $$ = this, x = $$.x, d3 = $$.d3, s;
$$.redraw({
withTransition: false,
@ -245,7 +245,7 @@ c3_chart_internal_fn.redrawForBrush = function () {
.translate(-s[0], 0));
$$.config.subchart_onbrush.call($$.api, x.orgDomain());
};
c3_chart_internal_fn.transformContext = function (withTransition, transitions) {
ChartInternal.prototype.transformContext = function (withTransition, transitions) {
var $$ = this, subXAxis;
if (transitions && transitions.axisSubX) {
subXAxis = transitions.axisSubX;
@ -256,7 +256,7 @@ c3_chart_internal_fn.transformContext = function (withTransition, transitions) {
$$.context.attr("transform", $$.getTranslate('context'));
subXAxis.attr("transform", $$.getTranslate('subx'));
};
c3_chart_internal_fn.getDefaultSelection = function () {
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()) {

18
src/text.js

@ -1,13 +1,13 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
c3_chart_internal_fn.initText = function () {
ChartInternal.prototype.initText = function () {
var $$ = this;
$$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartTexts);
$$.mainText = $$.d3.selectAll([]);
};
c3_chart_internal_fn.updateTargetsForText = function (targets) {
ChartInternal.prototype.updateTargetsForText = function (targets) {
var $$ = this,
classChartText = $$.classChartText.bind($$),
classTexts = $$.classTexts.bind($$),
@ -23,7 +23,7 @@ c3_chart_internal_fn.updateTargetsForText = function (targets) {
mainTextEnter.merge(mainText)
.attr('class', function (d) { return classChartText(d) + classFocus(d); });
};
c3_chart_internal_fn.updateText = function (xForText, yForText, durationForExit) {
ChartInternal.prototype.updateText = function (xForText, yForText, durationForExit) {
var $$ = this, config = $$.config,
barOrLineData = $$.barOrLineData.bind($$),
classText = $$.classText.bind($$);
@ -44,7 +44,7 @@ c3_chart_internal_fn.updateText = function (xForText, yForText, durationForExit)
.style('fill-opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawText = function (xForText, yForText, forFlow, withTransition, transition) {
ChartInternal.prototype.redrawText = function (xForText, yForText, forFlow, withTransition, transition) {
return [
(withTransition ? this.mainText.transition(transition) : this.mainText)
.attr('x', xForText)
@ -53,7 +53,7 @@ c3_chart_internal_fn.redrawText = function (xForText, yForText, forFlow, withTra
.style("fill-opacity", forFlow ? 0 : this.opacityForText.bind(this))
];
};
c3_chart_internal_fn.getTextRect = function (text, cls, element) {
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'),
@ -68,7 +68,7 @@ c3_chart_internal_fn.getTextRect = function (text, cls, element) {
dummy.remove();
return rect;
};
c3_chart_internal_fn.generateXYForText = function (areaIndices, barIndices, lineIndices, forX) {
ChartInternal.prototype.generateXYForText = function (areaIndices, barIndices, lineIndices, forX) {
var $$ = this,
getAreaPoints = $$.generateGetAreaPoints(areaIndices, false),
getBarPoints = $$.generateGetBarPoints(barIndices, false),
@ -79,7 +79,7 @@ c3_chart_internal_fn.generateXYForText = function (areaIndices, barIndices, line
return getter.call($$, getPoints(d, i), d, this);
};
};
c3_chart_internal_fn.getXForText = function (points, d, textElement) {
ChartInternal.prototype.getXForText = function (points, d, textElement) {
var $$ = this,
box = textElement.getBoundingClientRect(), xPos, padding;
if ($$.config.axis_rotated) {
@ -98,7 +98,7 @@ c3_chart_internal_fn.getXForText = function (points, d, textElement) {
}
return xPos;
};
c3_chart_internal_fn.getYForText = function (points, d, textElement) {
ChartInternal.prototype.getYForText = function (points, d, textElement) {
var $$ = this,
box = textElement.getBoundingClientRect(),
yPos;

27
src/title.js

@ -1,19 +1,24 @@
import { c3_chart_internal_fn } from './core';
import {
ChartInternal
} from './core';
c3_chart_internal_fn.initTitle = function () {
ChartInternal.prototype.initTitle = function () {
var $$ = this;
$$.title = $$.svg.append("text")
.text($$.config.title_text)
.attr("class", $$.CLASS.title);
.text($$.config.title_text)
.attr("class", $$.CLASS.title);
};
c3_chart_internal_fn.redrawTitle = function () {
ChartInternal.prototype.redrawTitle = function () {
var $$ = this;
$$.title
.attr("x", $$.xForTitle.bind($$))
.attr("y", $$.yForTitle.bind($$));
.attr("x", $$.xForTitle.bind($$))
.attr("y", $$.yForTitle.bind($$));
};
c3_chart_internal_fn.xForTitle = function () {
var $$ = this, config = $$.config, position = config.title_position || 'left', x;
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) {
@ -23,11 +28,11 @@ c3_chart_internal_fn.xForTitle = function () {
}
return x;
};
c3_chart_internal_fn.yForTitle = function () {
ChartInternal.prototype.yForTitle = function () {
var $$ = this;
return $$.config.title_padding.top + $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).height;
};
c3_chart_internal_fn.getTitlePadding = function() {
ChartInternal.prototype.getTitlePadding = function () {
var $$ = this;
return $$.yForTitle() + $$.config.title_padding.bottom;
};

92
src/tooltip.js

@ -1,12 +1,22 @@
import CLASS from './class';
import { c3_chart_internal_fn } from './core';
import { isValue, isFunction, isArray, isString, sanitise } from './util';
c3_chart_internal_fn.initTooltip = function () {
var $$ = this, config = $$.config, i;
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")
.append("div")
.attr('class', CLASS.tooltipContainer)
.style("position", "absolute")
.style("pointer-events", "none")
@ -16,7 +26,9 @@ c3_chart_internal_fn.initTooltip = function () {
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; }
if (($$.data.targets[0].values[i].x - config.tooltip_init_x) === 0) {
break;
}
}
config.tooltip_init_x = i;
}
@ -28,8 +40,9 @@ c3_chart_internal_fn.initTooltip = function () {
.style("display", "block");
}
};
c3_chart_internal_fn.getTooltipSortFunction = function() {
var $$ = this, config = $$.config;
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
@ -40,13 +53,13 @@ c3_chart_internal_fn.getTooltipSortFunction = function() {
order = config.data_order;
}
var valueOf = function(obj) {
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 function (a, b) {
return valueOf(a) - valueOf(b);
};
} else if (isString(order) && order.toLowerCase() === 'desc') {
@ -65,10 +78,10 @@ c3_chart_internal_fn.getTooltipSortFunction = function() {
sortFunction = function (a, b) {
return order(a ? {
id: a.id,
values: [ a ]
values: [a]
} : null, b ? {
id: b.id,
values: [ b ]
values: [b]
} : null);
};
}
@ -76,13 +89,13 @@ c3_chart_internal_fn.getTooltipSortFunction = function() {
return sortFunction;
} else if (isArray(order)) {
return function(a, b) {
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) {
var ids = $$.orderTargets($$.data.targets).map(function (i) {
return i.id;
});
@ -92,27 +105,32 @@ c3_chart_internal_fn.getTooltipSortFunction = function() {
ids = ids.reverse();
}
return function(a, b) {
return function (a, b) {
return ids.indexOf(a.id) - ids.indexOf(b.id);
};
}
};
c3_chart_internal_fn.getTooltipContent = function (d, defaultTitleFormat, defaultValueFormat, color) {
var $$ = this, config = $$.config,
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; },
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) {
if (tooltipSortFunction) {
d.sort(tooltipSortFunction);
}
for (i = 0; i < d.length; i++) {
if (! (d[i] && (d[i].value || d[i].value === 0))) { continue; }
if (!(d[i] && (d[i].value || d[i].value === 0))) {
continue;
}
if (! text) {
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>" : "");
}
@ -120,7 +138,9 @@ c3_chart_internal_fn.getTooltipContent = function (d, defaultTitleFormat, defaul
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; }
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);
@ -132,12 +152,14 @@ c3_chart_internal_fn.getTooltipContent = function (d, defaultTitleFormat, defaul
}
return text + "</table>";
};
c3_chart_internal_fn.tooltipPosition = function (dataToShow, tWidth, tHeight, element) {
var $$ = this, config = $$.config, d3 = $$.d3;
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
// Determin tooltip position
if (forArc) {
tooltipLeft = (($$.width - ($$.isLegendRight ? $$.getLegendWidth() : 0)) / 2) + mouse[0];
tooltipTop = ($$.hasType('gauge') ? $$.height : $$.height / 2) + mouse[1] + 20;
@ -166,14 +188,20 @@ c3_chart_internal_fn.tooltipPosition = function (dataToShow, tWidth, tHeight, el
if (tooltipTop < 0) {
tooltipTop = 0;
}
return {top: tooltipTop, left: tooltipLeft};
return {
top: tooltipTop,
left: tooltipLeft
};
};
c3_chart_internal_fn.showTooltip = function (selectedData, element) {
var $$ = this, config = $$.config;
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 || c3_chart_internal_fn.tooltipPosition;
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;
}
@ -189,6 +217,6 @@ c3_chart_internal_fn.showTooltip = function (selectedData, element) {
.style("top", position.top + "px")
.style("left", position.left + 'px');
};
c3_chart_internal_fn.hideTooltip = function () {
ChartInternal.prototype.hideTooltip = function () {
this.tooltip.style("display", "none");
};

38
src/type.js

@ -1,7 +1,7 @@
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
import { isString } from './util';
c3_chart_internal_fn.setTargetType = function (targetIds, type) {
ChartInternal.prototype.setTargetType = function (targetIds, type) {
var $$ = this, config = $$.config;
$$.mapToTargetIds(targetIds).forEach(function (id) {
$$.withoutFadeIn[id] = (type === config.data_types[id]);
@ -11,7 +11,7 @@ c3_chart_internal_fn.setTargetType = function (targetIds, type) {
config.data_type = type;
}
};
c3_chart_internal_fn.hasType = function (type, targets) {
ChartInternal.prototype.hasType = function (type, targets) {
var $$ = this, types = $$.config.data_types, has = false;
targets = targets || $$.data.targets;
if (targets && targets.length) {
@ -30,52 +30,52 @@ c3_chart_internal_fn.hasType = function (type, targets) {
}
return has;
};
c3_chart_internal_fn.hasArcType = function (targets) {
ChartInternal.prototype.hasArcType = function (targets) {
return this.hasType('pie', targets) || this.hasType('donut', targets) || this.hasType('gauge', targets);
};
c3_chart_internal_fn.isLineType = function (d) {
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;
};
c3_chart_internal_fn.isStepType = function (d) {
ChartInternal.prototype.isStepType = function (d) {
var id = isString(d) ? d : d.id;
return ['step', 'area-step'].indexOf(this.config.data_types[id]) >= 0;
};
c3_chart_internal_fn.isSplineType = function (d) {
ChartInternal.prototype.isSplineType = function (d) {
var id = isString(d) ? d : d.id;
return ['spline', 'area-spline'].indexOf(this.config.data_types[id]) >= 0;
};
c3_chart_internal_fn.isAreaType = function (d) {
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;
};
c3_chart_internal_fn.isBarType = function (d) {
ChartInternal.prototype.isBarType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'bar';
};
c3_chart_internal_fn.isScatterType = function (d) {
ChartInternal.prototype.isScatterType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'scatter';
};
c3_chart_internal_fn.isPieType = function (d) {
ChartInternal.prototype.isPieType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'pie';
};
c3_chart_internal_fn.isGaugeType = function (d) {
ChartInternal.prototype.isGaugeType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'gauge';
};
c3_chart_internal_fn.isDonutType = function (d) {
ChartInternal.prototype.isDonutType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'donut';
};
c3_chart_internal_fn.isArcType = function (d) {
ChartInternal.prototype.isArcType = function (d) {
return this.isPieType(d) || this.isDonutType(d) || this.isGaugeType(d);
};
c3_chart_internal_fn.lineData = function (d) {
ChartInternal.prototype.lineData = function (d) {
return this.isLineType(d) ? [d] : [];
};
c3_chart_internal_fn.arcData = function (d) {
ChartInternal.prototype.arcData = function (d) {
return this.isArcType(d.data) ? [d] : [];
};
/* not used
@ -83,12 +83,12 @@ c3_chart_internal_fn.arcData = function (d) {
return isScatterType(d) ? d.values : [];
}
*/
c3_chart_internal_fn.barData = function (d) {
ChartInternal.prototype.barData = function (d) {
return this.isBarType(d) ? d.values : [];
};
c3_chart_internal_fn.lineOrScatterData = function (d) {
ChartInternal.prototype.lineOrScatterData = function (d) {
return this.isLineType(d) || this.isScatterType(d) ? d.values : [];
};
c3_chart_internal_fn.barOrLineData = function (d) {
ChartInternal.prototype.barOrLineData = function (d) {
return this.isBarType(d) || this.isLineType(d) ? d.values : [];
};

6
src/ua.js

@ -1,10 +1,10 @@
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
c3_chart_internal_fn.isSafari = function () {
ChartInternal.prototype.isSafari = function () {
var ua = window.navigator.userAgent;
return ua.indexOf('Safari') >= 0 && ua.indexOf('Chrome') < 0;
};
c3_chart_internal_fn.isChrome = function () {
ChartInternal.prototype.isChrome = function () {
var ua = window.navigator.userAgent;
return ua.indexOf('Chrome') >= 0;
};

110
src/util.js

@ -1,91 +1,53 @@
import {ChartInternal} from './chart-internal';
export var c3 = { version: "0.6.4" ,
chart: {
fn: Chart.prototype,
internal: {
fn: ChartInternal.prototype,
}
}
export var asHalfPixel = function(n) {
return Math.ceil(n) + 0.5;
};
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);
}
});
})(c3.chart.fn, this, this);
}
c3.generate = function (config) {
return new Chart(config);
export var ceil10 = function(v) {
return Math.ceil(v / 10) * 10;
};
export function Component(owner, componentKey, fn) {
this.owner = owner;
c3.chart.internal[componentKey] = fn;
}
export var isValue = function (v) {
return v || v === 0;
export var diffDomain = function(d) {
return d[1] - d[0];
};
export var isFunction = function (o) {
return typeof o === 'function';
export var getOption = function(options, key, defaultValue) {
return isDefined(options[key]) ? options[key] : defaultValue;
};
export var isArray = function (o) {
return Array.isArray(o);
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 isString = function (o) {
return typeof o === 'string';
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 isUndefined = function (v) {
return typeof v === 'undefined';
export var isArray = function(o) {
return Array.isArray(o);
};
export var isDefined = function (v) {
export var isDefined = function(v) {
return typeof v !== 'undefined';
};
export var ceil10 = function (v) {
return Math.ceil(v / 10) * 10;
};
export var asHalfPixel = function (n) {
return Math.ceil(n) + 0.5;
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 diffDomain = function (d) {
return d[1] - d[0];
export var isFunction = function(o) {
return typeof o === 'function';
};
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 isString = function(o) {
return typeof o === 'string';
};
export var notEmpty = function (o) {
return !c3.chart.internal.fn.isEmpty(o);
export var isUndefined = function(v) {
return typeof v === 'undefined';
};
export var getOption = function (options, key, defaultValue) {
return isDefined(options[key]) ? options[key] : defaultValue;
export var isValue = function(v) {
return v || v === 0;
};
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 notEmpty = function(o) {
return !isEmpty(o);
};
export var sanitise = function (str) {
export var sanitise = function(str) {
return typeof str === 'string' ? str.replace(/</g, '&lt;').replace(/>/g, '&gt;') : str;
};
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};
};

10
src/zoom.js

@ -1,6 +1,6 @@
import { c3_chart_internal_fn } from './core';
import { ChartInternal } from './core';
c3_chart_internal_fn.initZoom = function () {
ChartInternal.prototype.initZoom = function () {
var $$ = this, d3 = $$.d3, config = $$.config, startEvent;
$$.zoom = d3.zoom()
@ -43,18 +43,18 @@ c3_chart_internal_fn.initZoom = function () {
return $$.zoom.updateExtent();
};
c3_chart_internal_fn.zoomTransform = function (range) {
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);
};
c3_chart_internal_fn.getZoomDomain = function () {
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];
};
c3_chart_internal_fn.redrawForZoom = function () {
ChartInternal.prototype.redrawForZoom = function () {
var $$ = this, d3 = $$.d3, config = $$.config, zoom = $$.zoom, x = $$.x;
if (!config.zoom_enabled) {
return;

Loading…
Cancel
Save