JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<div data-toggle="parsetree"></div>
</body>
JavaScript
var parsetree = function(selector, options) {
this.el = document.querySelector(selector);
this.options = options || {};
if (this.el == null)
console.log("Could not find DOM object");
return this;
};
// For our purposes, I'll hardcode our data in.
parsetree.prototype.init = function() {
words = [
{ id: 1, head: 3, relation: "OBJ", value: "ταῦτα" },
{ id: 2, head: 3, relation: "AuxY", value: "γὰρ" },
{ id: 3, head: 0, relation: "PRED", value: "εἶχον", },
{ id: 4, head: 3, relation: "SBJ", value: "Ἀθηναῖοι" },
{ id: 5, head: 1, relation: "ATR", value: "Πελοποννησίων" },
{ id: 6, head: 0, relation: "AuxK", value: "." }
];
// We'll convert our flat word object into hierarchical data -- read on to find out how!
this.data = this.convertData(words);
this.render();
return this;
};
parsetree.prototype.convertData = function(words) {
// Create a root node
var rootNode = { 'id': 0, 'value': 'root', 'pos': 'root' };
words.push(rootNode);
var dataMap = words.reduce(function(map, node) {
map[node.id] = node;
return map;
}, {});
var treeData = [];
words.forEach(function(node) {
var head = dataMap[node.head];
// Then, create the hierarchical data d3 needs
if (head)
(head.children || (head.children = [])).push(node);
else
treeData.push(node);
});
return treeData;
};
parsetree.prototype.render = function () {
// To keep multiple instances from stomping on each other's data/d3 references
this.tree = d3.layout.tree().nodeSize([100, 50]);
// Tell our tree how to decide how to separate the nodes
...