Skip to content

Instantly share code, notes, and snippets.

@timwis
Last active April 23, 2017 16:13
Show Gist options
  • Save timwis/4ba8eab0ca63ecf0885d331d26fd18cf to your computer and use it in GitHub Desktop.
Save timwis/4ba8eab0ca63ecf0885d331d26fd18cf to your computer and use it in GitHub Desktop.
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