2016-03-18 02:44:58 -04:00
|
|
|
var d3 = window.d3 || require('d3');
|
2016-08-12 00:39:10 -04:00
|
|
|
import cloudLayout from 'd3-cloud'
|
|
|
|
import { category21 } from '../javascripts/modules/colors'
|
2016-03-18 02:44:58 -04:00
|
|
|
|
|
|
|
function wordCloudChart(slice) {
|
|
|
|
var chart = d3.select(slice.selector);
|
|
|
|
|
|
|
|
function refresh() {
|
|
|
|
d3.json(slice.jsonEndpoint(), function (error, json) {
|
|
|
|
if (error !== null) {
|
2016-06-21 12:42:44 -04:00
|
|
|
slice.error(error.responseText, error);
|
2016-03-18 02:44:58 -04:00
|
|
|
return '';
|
|
|
|
}
|
|
|
|
var data = json.data;
|
|
|
|
var range = [
|
|
|
|
json.form_data.size_from,
|
2016-07-21 00:32:20 -04:00
|
|
|
json.form_data.size_to,
|
2016-03-18 02:44:58 -04:00
|
|
|
];
|
|
|
|
var rotation = json.form_data.rotation;
|
|
|
|
var f_rotation;
|
|
|
|
if (rotation === "square") {
|
|
|
|
f_rotation = function () {
|
|
|
|
return ~~(Math.random() * 2) * 90;
|
|
|
|
};
|
|
|
|
} else if (rotation === "flat") {
|
|
|
|
f_rotation = function () {
|
|
|
|
return 0;
|
|
|
|
};
|
|
|
|
} else {
|
|
|
|
f_rotation = function () {
|
|
|
|
return (~~(Math.random() * 6) - 3) * 30;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
var size = [slice.width(), slice.height()];
|
|
|
|
|
|
|
|
var scale = d3.scale.linear()
|
|
|
|
.range(range)
|
|
|
|
.domain(d3.extent(data, function (d) {
|
|
|
|
return d.size;
|
|
|
|
}));
|
|
|
|
|
|
|
|
var layout = cloudLayout()
|
|
|
|
.size(size)
|
|
|
|
.words(data)
|
|
|
|
.padding(5)
|
|
|
|
.rotate(f_rotation)
|
|
|
|
.font("serif")
|
|
|
|
.fontSize(function (d) {
|
|
|
|
return scale(d.size);
|
|
|
|
})
|
|
|
|
.on("end", draw);
|
|
|
|
|
|
|
|
layout.start();
|
|
|
|
|
|
|
|
function draw(words) {
|
|
|
|
chart.selectAll("*").remove();
|
|
|
|
|
|
|
|
chart.append("svg")
|
|
|
|
.attr("width", layout.size()[0])
|
|
|
|
.attr("height", layout.size()[1])
|
|
|
|
.append("g")
|
|
|
|
.attr("transform", "translate(" + layout.size()[0] / 2 + "," + layout.size()[1] / 2 + ")")
|
|
|
|
.selectAll("text")
|
|
|
|
.data(words)
|
|
|
|
.enter().append("text")
|
|
|
|
.style("font-size", function (d) {
|
|
|
|
return d.size + "px";
|
|
|
|
})
|
|
|
|
.style("font-family", "Impact")
|
|
|
|
.style("fill", function (d) {
|
2016-08-12 00:39:10 -04:00
|
|
|
return category21(d.text);
|
2016-03-18 02:44:58 -04:00
|
|
|
})
|
|
|
|
.attr("text-anchor", "middle")
|
|
|
|
.attr("transform", function (d) {
|
|
|
|
return "translate(" + [d.x, d.y] + ") rotate(" + d.rotate + ")";
|
|
|
|
})
|
|
|
|
.text(function (d) {
|
|
|
|
return d.text;
|
|
|
|
});
|
|
|
|
}
|
2016-03-16 23:25:41 -04:00
|
|
|
slice.done(json);
|
2016-03-18 02:44:58 -04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
render: refresh,
|
2016-07-21 00:32:20 -04:00
|
|
|
resize: refresh,
|
2016-03-18 02:44:58 -04:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = wordCloudChart;
|