Public
Edited
Sep 4, 2018
5 forks
20 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
res = {
// Node content
function renderNode(selection, rcd) {
selection.append('input')
.attr('type', 'checkbox')
.on('change', function () {
d3.select('#selected').text(checkboxValues(d3.select('#view')));
});
selection.append('span')
.text(rcd.id);
}

// Return array of ids that is checked
function checkboxValues(selection) {
return selection.select('.body')
.selectAll('input:checked').data().map(d => d.id);
}

// Recursively append child nodes
function nextLevel(selection, node) {
const label = selection.append('span');
const arrow = label.append('span').classed('arrow', true);
label.call(renderNode, node.data);
if (!node.hasOwnProperty('children')) return;
const items = selection.append('ul')
.style('list-style-type', 'none')
.selectAll('li')
.data(node.children, d => d.id);
items.exit().remove();
items.enter()
.append('li').merge(items)
.each(function (d) {
d3.select(this).call(nextLevel, d);
});
label.select('.arrow')
.text('▼ ')
.on('click', function () { // Collapse on click
const childList = selection.select('ul');
if (!childList.size()) return;
const expanded = childList.style('display') !== 'none';
d3.select(this).text(expanded ? '▶ ' : '▼ ');
childList.style('display', expanded ? 'none' : 'inherit');
});
}

// Generate tree view
function tree(selection) {
selection
.classed('viewport', true)
.style('overflow-y', 'scroll')
.style('height', '500px')
.append('div')
.classed('body', true)
.style('transform', 'scale(1.5)')
.style('transform-origin', 'top left');
}

// Update tree data
function updateTree(selection, items) {
const root = d3.stratify()
.id(d => d.id)
.parentId(d => d.parent)(items);
selection.select('.body')
.call(nextLevel, root);
// Remove dummy root node
selection.select('.body > span').remove();
selection.select('.body > ul').style('padding-left', 0);
}

// Render
d3.select('#view div').remove();
d3.select('#view').append('div')
.call(tree)
.call(updateTree, data);
}
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more