Skip to content

Instantly share code, notes, and snippets.

@timwis timwis/grid.js
Last active Apr 23, 2017

Embed
What would you like to do?
Combining HyperList with Nanocomponent
const html = require('choo/html')
const css = require('sheetify')
const HyperListComponent = require('./hyperlist-component')
const prefix = css`
thead, tbody {
display: block;
}
`
module.exports = function grid (state, emit) {
const { fields, rows } = state.store.activeSheet
const tbody = hyperList.render({ fields, rows })
return html`
<div class=${prefix}>
<table class="table is-bordered is-striped is-narrow">
<thead>
<tr>${fields.map(tableHeader)}</tr>
</thead>
${tbody}
</table>
</div>
`
function tableHeader (field) {
return html`
<th>
${field.name}
</th>
`
}
}
const opts = {
height: 500,
itemHeight: 34,
eachItem: tableRow,
getTotal: (state) => state.rows.length
}
const hyperList = new HyperListComponent('tbody', opts)
function tableRow (state, rowIndex) {
const { fields, rows } = state
const row = rows[rowIndex]
return html`
<tr>
${fields.map((field, columnIndex) => {
const value = row[field.name] || ''
return html`
<td data-row-index=${rowIndex}
data-column-index=${columnIndex}>
${value}
</td>
`
})}
</tr>
`
}
const Nanocomponent = require('nanocomponent')
const HyperList = require('hyperlist')
class HyperListComponent extends Nanocomponent {
constructor (tagName, opts) {
super()
this._tagName = tagName
this._opts = opts
}
_render (state) {
this._state = state
const opts = Object.assign({}, this._opts, {
generate: (index) => this._opts.eachItem(state, index),
total: this._opts.getTotal(state)
})
if (this._element && this.hyperlist) {
// Updating existing hyperlist
this.hyperlist.refresh(this._element, opts)
return this._element
} else {
// initial render
const container = document.createElement(this._tagName)
this.hyperlist = HyperList.create(container, opts)
return container
}
}
_update (newState) {
return !isEqualShallow(newState, this._state)
}
}
function isEqualShallow (a, b) {
const keys = Object.keys(a)
return keys.every((key) => a[key] === b[key])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.