Skip to content

Instantly share code, notes, and snippets.

@gabrielmontagne
Last active March 23, 2017 17:23
Show Gist options
  • Save gabrielmontagne/b8e3ec92c42f3b17c3c2cc59f6752878 to your computer and use it in GitHub Desktop.
Save gabrielmontagne/b8e3ec92c42f3b17c3c2cc59f6752878 to your computer and use it in GitHub Desktop.
Zambezi Grid -- row grouping around predefined rows
license: mit

Row grouping can be extracted from the rows themselves by using row grouping on the Zambezi grid directly. But sometimes we might have the groups first, and we would like to gather rows around them, and have them be active even if no rows match.

The gatherRows component is designed for this: you pre-define the groups, and create a predicate for each that will be tested for each row to determine on which group it belongs. Groups are tested in order, and the first one that matches will be used.

<!doctype html>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="https://npmcdn.com/normalize.css@4">
<div class="grid-target"></div>
<script src="https://npmcdn.com/underscore@1"></script>
<script src="https://npmcdn.com/faker@1.0.0/faker.js"></script>
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://npmcdn.com/@zambezi/fun@2"></script>
<script src="https://npmcdn.com/@zambezi/d3-utils@3"></script>
<script src="https://npmcdn.com/@zambezi/grid@0"></script>
<script src="https://npmcdn.com/@zambezi/grid-components@0.12.0-constrain-gather-rows-toggle-area.1"></script>
<script>
const price = d3.randomNormal(1000, 100)
, rows = _.range(1, 50).map(faker.Helpers.createCard).map(addPrice)
, gatherRows = gridComponents.createGatherRows()
.groups(
[
{
label: 'Usernames with dots'
, predicate: row => row.username.indexOf('.') >= 0
}
, {
label: 'Usernames with underscores'
, predicate: row => row.username.indexOf('_') >= 0
}
, {
label: 'Something that does not match on this dataset'
, predicate: () => false
}
, { label: 'Other usernames' }
]
)
, table = grid.createGrid()
.columns(
[
{ key: 'name', width: 200 }
, { key: 'username' }
, { key: 'email' }
, {
key: 'phone'
, components: [ callMeAll, grid.updateTextIfChanged ]
}
, {
label: 'Price'
, format: gridComponents.nestedRowFormat(
priceSummary
, r => r.price
)
, sort: (a, b) => a.price - b.price
}
]
)
.usePre(gatherRows)
, target = d3.select('.grid-target')
.style('height', '800px')
.datum(rows)
.call(table)
function priceSummary(r) {
return `Total: ${ r.children.reduce((acc, r) => acc + r.price, 0)}`
}
function addPrice(r) {
r.price = Math.round(price() / 10) * 10
return r
}
function callMeAll(d) {
const target = d3.select(this)
if (!d.row.isGroupRow) {
target.select('button').remove()
} else {
target.select(d3Utils.appendIfMissing('button'))
.on(
'click.debug',
d => console.log('grouped rows component', d)
)
.text(_.uniqueId('ran_'))
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment