license import { format as d3Format } from 'd3-format' ; import { select as d3Select } from 'd3-selection' ; import { css } from 'glamor' ; import { tachyons as tac } from 'glamor-tachyons' ; import { Drawable , TableData } from '../types' ; import { getDrawArea } from './render_utils' ; param opts . fontSize doc export function table ( container , data , opts = { } ) { if ( data && data . headers == null ) { throw new Error ( 'Data to render must have a "headers" property' ) ; } if ( data && data . values == null ) { throw new Error ( 'Data to render must have a "values" property' ) ; } const drawArea = getDrawArea ( container ) ; const options = Object . assign ( { } , defaultOpts , opts ) ; let table = d3Select ( drawArea ) . select ( 'table.tf-table' ) ; const tableStyle = css ( { ... tac ( 'f6 w-100 mw8 center' ) , fontSize : options . fontSize , } ) ; if ( table . size ( ) === 0 ) { table = d3Select ( drawArea ) . append ( 'table' ) ; table . attr ( 'class' , ` ${ tableStyle } tf-table` ) ; table . append ( 'thead' ) . append ( 'tr' ) ; table . append ( 'tbody' ) ; } if ( table . size ( ) !== 1 ) { throw new Error ( 'Error inserting table' ) ; } const headerRowStyle = css ( { ... tac ( 'fw6 bb b--black-20 tl pb3 pr3 bg-white' ) } ) ; const headers = table . select ( 'thead' ) . select ( 'tr' ) . selectAll ( 'th' ) . data ( data . headers ) ; const headersEnter = headers . enter ( ) . append ( 'th' ) . attr ( 'class' , `${ headerRowStyle }` ) ; headers . merge ( headersEnter ) . html ( d => d ) ; headers . exit ( ) . remove ( ) ; const format = d3Format ( ',.4~f' ) ; const rows = table . select ( 'tbody' ) . selectAll ( 'tr' ) . data ( data . values ) ; const rowsEnter = rows . enter ( ) . append ( 'tr' ) ; const cellStyle = css ( { ... tac ( 'pa1 bb b--black-20' ) } ) ; const cells = rows . merge ( rowsEnter ) . selectAll ( 'td' ) . data ( d => d ) ; const cellsEnter = cells . enter ( ) . append ( 'td' ) . attr ( 'class' , `${ cellStyle }` ) ; cells . merge ( cellsEnter ) . html ( d => typeof d === 'number' ? format ( d ) : d ) ; cells . exit ( ) . remove ( ) ; rows . exit ( ) . remove ( ) ; } const defaultOpts = { fontSize : 14 , } ;