Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Html legend support #1329

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,7 @@ module.exports.jsFiles = [
'src/bubble-overlay.js',
'src/row-chart.js',
'src/legend.js',
'src/html-legend.js',
'src/scatter-plot.js',
'src/number-display.js',
'src/heatmap.js',
Expand Down
146 changes: 146 additions & 0 deletions spec/html-legend-spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/* global appendChartID, loadDateFixture */
describe('dc.htmlLegend', function () {
var id, chart, dateDimension, dateValueSumGroup, dateIdSumGroup, legend, legendId;

beforeEach(function () {
var data = crossfilter(loadDateFixture());
dateDimension = data.dimension(function (d) {
return d3.time.day(d.dd);
});
dateValueSumGroup = dateDimension.group().reduceSum(function (d) {
return d.value;
});
dateIdSumGroup = dateDimension.group().reduceSum(function (d) {
return d.id;
});

id = 'html-legend-chart';
legendId = 'html-legend-chart-legend';
appendChartID(id);
appendChartID(legendId);

chart = dc.lineChart('#' + id);
chart
.dimension(dateDimension)
.group(dateIdSumGroup, 'Id Sum')
.stack(dateValueSumGroup, 'Value Sum')
.stack(dateValueSumGroup, 'Fixed', function () {
})
.x(d3.time.scale().domain([new Date(2012, 4, 20), new Date(2012, 7, 15)]))
.legend(dc.htmlLegend().container('#' + legendId));
legend = d3.select('#' + legendId);
});

function legendItem (n, orientation) {
return d3.select(legend.selectAll('div.dc-html-legend div.dc-legend-item-' + orientation)[0][n]);
}

function legendLabel (n, orientation) {
return d3.select(legend.selectAll('div.dc-html-legend div.dc-legend-item-' + orientation + ' span.dc-legend-item-label')[0][n]);
}

function legendIcon (n, orientation) {
return d3.select(legend.selectAll('div.dc-html-legend div.dc-legend-item-' + orientation + ' span.dc-legend-item-color')[0][n]);
}

describe('rendering the legend', function () {
beforeEach(function () {
chart.render();
});

it('should generate a legend', function () {
expect(legend.select('div.dc-html-legend').empty()).toBeFalsy();
});

it('should generate a legend item for each stacked line', function () {
expect(legend.select('div.dc-html-legend').selectAll('.dc-legend-item-vertical').size()).toBe(3);
});

it('should generate legend item boxes', function () {
expect(legendIcon(0, 'vertical').style('background-color')).toBe('rgb(31, 119, 180)');
expect(legendIcon(1, 'vertical').style('background-color')).toBe('rgb(255, 127, 14)');
expect(legendIcon(2, 'vertical').style('background-color')).toBe('rgb(44, 160, 44)');
});

it('should generate legend labels', function () {
expect(legendLabel(0, 'vertical').text()).toBe('Id Sum');
expect(legendLabel(1, 'vertical').text()).toBe('Value Sum');
expect(legendLabel(2, 'vertical').text()).toBe('Fixed');
});

it('not allow hiding stacks be default', function () {
legendItem(0, 'vertical').on('click').call(legendItem(0)[0][0], legendItem(0, 'vertical').datum());
expect(chart.selectAll('path.line').size()).toBe(3);
});
});

describe('with .horizontal(true)', function () {
beforeEach(function () {
chart.legend(dc.htmlLegend().container('#' + legendId).horizontal(true));
chart.render();
});

it('should generate a legend', function () {
expect(legend.select('div.dc-html-legend').empty()).toBeFalsy();
});

it('should generate a legend item for each stacked line', function () {
expect(legend.select('div.dc-html-legend').selectAll('div.dc-legend-item-horizontal').size()).toBe(3);
});

it('should generate legend item boxes', function () {
expect(legendIcon(0, 'horizontal').style('background-color')).toBe('rgb(31, 119, 180)');
expect(legendIcon(1, 'horizontal').style('background-color')).toBe('rgb(255, 127, 14)');
expect(legendIcon(2, 'horizontal').style('background-color')).toBe('rgb(44, 160, 44)');
});

it('should generate legend labels', function () {
expect(legendLabel(0, 'horizontal').text()).toBe('Id Sum');
expect(legendLabel(1, 'horizontal').text()).toBe('Value Sum');
expect(legendLabel(2, 'horizontal').text()).toBe('Fixed');
});

it('not allow hiding stacks be default', function () {
var firstLegendItem = legendItem(0, 'horizontal');
firstLegendItem.on('click').call(firstLegendItem[0][0], firstLegendItem.datum());
expect(chart.selectAll('path.line').size()).toBe(3);
});
});

describe('with .maxItems(2)', function () {
beforeEach(function () {
chart.legend(dc.htmlLegend().container('#' + legendId).horizontal(true).maxItems(2));
chart.render();
});
it('should display two items', function () {
expect(legend.select('div.dc-html-legend').selectAll('div.dc-legend-item-horizontal').size()).toBe(2);
});
});

describe('with invalid .maxItems', function () {
beforeEach(function () {
chart.legend(dc.htmlLegend().container('#' + legendId).horizontal(true).maxItems('foo'));
chart.render();
});
it('should display three items', function () {
expect(legend.select('div.dc-html-legend').selectAll('div.dc-legend-item-horizontal').size()).toBe(3);
});
});

describe('with .legendText()', function () {
beforeEach(function () {
chart.legend(dc.htmlLegend().container('#' + legendId).legendText(function (d, i) {
var _i = i + 1;
return _i + '. ' + d.name;
}));
chart.render();
});

it('should label the legend items with the names of their associated stacks', function () {
expect(legendLabel(0, 'vertical').text()).toBe('1. Id Sum');
expect(legendLabel(1, 'vertical').text()).toBe('2. Value Sum');
expect(legendLabel(2, 'vertical').text()).toBe('3. Fixed');
});
});

});
123 changes: 123 additions & 0 deletions src/html-legend.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/**
* htmlLegend is a attachable widget that can be added to other dc charts to render horizontal/vertical legend
* labels.
*
* Examples:
* - {@link http://dc-js.github.com/dc.js/ Nasdaq 100 Index}
* @class legend
* @memberof dc
* @example
* chart.legend(dc.htmlLegend().container(legendContainerElement).horizontal(false))
* @returns {dc.htmlLegend}
*/
dc.htmlLegend = function () {
var _legend = {},
_parent,
_container,
_legendText = dc.pluck('name'),
_maxItems,
_horizontal = false;

var _l;

_legend.parent = function (p) {
if (!arguments.length) {
return _parent;
}
_parent = p;
return _legend;
};

_legend.render = function () {
var orientation = _horizontal ? 'horizontal' : 'vertical';
_container.select('div.dc-html-legend').remove();
_l = _container.append('div')
.attr('class', 'dc-html-legend');
var legendables = _parent.legendables();
if (_maxItems !== undefined) {
legendables = legendables.slice(0, _maxItems);
}
var itemEnter = _l.selectAll('div.dc-legend-item-' + orientation)
.data(legendables).enter()
.append('div').attr('class', 'dc-legend-item-' + orientation)
.on('mouseover', _parent.legendHighlight)
.on('mouseout', _parent.legendReset)
.on('click', _parent.legendToggle);
itemEnter.append('span')
.attr('class', 'dc-legend-item-color')
.style('background-color', dc.pluck('color'));
itemEnter.append('span')
.attr('class', 'dc-legend-item-label')
.text(_legendText);
};

/**
#### .container([selector])
Set the container selector for the legend widget. Required.
**/
_legend.container = function (c) {
if (!arguments.length) {
return _container;
}
_container = d3.select(c);
return _legend;
};

/**
#### .horizontal([boolean])
Display the legend horizontally instead of horizontally

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this comment say 'vertically' not 'horizontally' at the end of the sentence?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, will need to correct that, Thanks for pointing it out.

**/
_legend.horizontal = function (b) {
if (!arguments.length) {
return _horizontal;
}
_horizontal = b;
return _legend;
};

/**
* Set or get the legend text function. The legend widget uses this function to render the legend
* text for each item. If no function is specified the legend widget will display the names
* associated with each group.
* @method legendText
* @memberof dc.htmlLegend
* @instance
* @param {Function} [legendText]
* @returns {Function|dc.htmlLegend}
* @example
* // default legendText
* legend.legendText(dc.pluck('name'))
*
* // create numbered legend items
* chart.legend(dc.htmlLegend().legendText(function(d, i) { return i + '. ' + d.name; }))
*
* // create legend displaying group counts
* chart.legend(dc.htmlLegend().legendText(function(d) { return d.name + ': ' d.data; }))
**/
_legend.legendText = function (legendText) {
if (!arguments.length) {
return _legendText;
}
_legendText = legendText;
return _legend;
};

/**
* Maximum number of legend items to display
* @method maxItems
* @memberof dc.htmlLegend
* @instance
* @param {Number} [maxItems]
* @return {dc.htmlLegend}
*/
_legend.maxItems = function (maxItems) {
if (!arguments.length) {
return _maxItems;
}
_maxItems = dc.utils.isNumber(maxItems) ? maxItems : undefined;
return _legend;
};

return _legend;
};

29 changes: 28 additions & 1 deletion style/dc.scss
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ div.dc-chart {
fill-opacity: .2;
}
&.axis text {
@include no-select
@include no-select;
pointer-events: none;
}
}
Expand Down Expand Up @@ -272,3 +272,30 @@ div.dc-chart {
.dc-hard .number-display {
float: none;
}


div.dc-html-legend {
overflow: auto;
.dc-legend-item-horizontal {
display: inline-block;
margin-left: 5px;
margin-right: 5px;
cursor: pointer;
}
.dc-legend-item-vertical {
display: block;
margin-top: 5px;
cursor: pointer;
}
.dc-legend-item-color {
display: table-cell;
width: 12px;
height: 12px;
}
.dc-legend-item-label {
line-height: 12px;
display: table-cell;
vertical-align: middle;
padding-left: 3px;
}
}
44 changes: 44 additions & 0 deletions web/examples/html-legend.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>dc.js - HTML Legend Example</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="../css/dc.css"/>
</head>
<body>

<div id="test"></div>
<div id="legend"></div>

<script type="text/javascript" src="../js/d3.js"></script>
<script type="text/javascript" src="../js/crossfilter.js"></script>
<script type="text/javascript" src="../js/dc.js"></script>
<script type="text/javascript">

var chart = dc.pieChart("#test");
d3.csv("morley.csv", function (error, experiments) {

var ndx = crossfilter(experiments),
runDimension = ndx.dimension(function (d) {
return "run-" + d.Run;
}),
speedSumGroup = runDimension.group().reduceSum(function (d) {
return d.Speed * d.Run;
});

chart
.width(768)
.height(480)
.slicesCap(4)
.innerRadius(100)
.dimension(runDimension)
.group(speedSumGroup)
.legend(dc.htmlLegend().container('#legend').horizontal(false));

chart.render();
});

</script>

</body>
</html>