react-virtualized#Table JavaScript Examples

The following examples show how to use react-virtualized#Table. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: virtual-table-columns.js    From Lynx with MIT License 6 votes vote down vote up
render() {
    const {rows, cols} = this.state;
    return (
      <Table
        width={COL_WIDTH * rows.length}
        height={HEADER_ROW_HEIGHT + (ROW_HEIGHT * rows.length)}
        headerHeight={ROW_HEIGHT}
        rowHeight={ROW_HEIGHT}
        rowCount={rows.length}
        rowGetter={({index}) => rows[index]}
        headerRowRenderer={params => (
          <SortableHeaderRowRenderer
            {...params}
            axis="x"
            lockAxis="x"
            onSortEnd={this.onSortEnd}
          />
        )}
      >
        {cols.map(col => (
          <Column
            {...col}
            key={col.dataKey}
            width={COL_WIDTH}
          />
        ))}
      </Table>
    );
  }
Example #2
Source File: ReactVirtualizedTable.js    From sampo-ui with MIT License 5 votes vote down vote up
render () {
    const { classes, columns, rowHeight, headerHeight, sortDirection, ...tableProps } = this.props
    return (
      <AutoSizer>
        {({ height, width }) => (
          <Table
            height={height}
            width={width}
            rowHeight={rowHeight}
            gridStyle={{
              direction: 'inherit'
            }}
            headerHeight={headerHeight}
            className={classes.table}
            {...tableProps}
            rowClassName={this.getRowClassName}
          >
            {columns.map(({ id, minWidth, ...other }, index) => {
              const label = intl.get(`perspectives.fullTextSearch.properties.${id}.label`)
              return (
                <Column
                  key={id}
                  headerRenderer={(headerProps) =>
                    this.headerRenderer({
                      ...headerProps,
                      label,
                      columnIndex: index,
                      dataKey: id
                    })}
                  className={classes.flexContainer}
                  cellRenderer={this.cellRenderer}
                  dataKey={id}
                  width={minWidth}
                  {...other}
                />
              )
            })}
          </Table>
        )}
      </AutoSizer>
    )
  }
Example #3
Source File: VirtualizedTable.js    From sampo-ui with MIT License 4 votes vote down vote up
render () {
    const { classes, list, perspectiveID } = this.props
    // console.log(list)
    const rowGetter = ({ index }) => this._getDatum(list, index)

    const headerRenderer = ({
      dataKey,
      label,
      sortBy,
      sortDirection
    }) => {
      const showSortIndicator = sortBy === dataKey
      const children = [
        <span
          className='ReactVirtualized__Table__headerTruncatedText'
          style={showSortIndicator ? {} : { marginRight: 16 }}
          key='label'
          title={label}
        >
          {label}
        </span>
      ]
      if (showSortIndicator) {
        children.push(
          <SortIndicator key='SortIndicator' sortDirection={sortDirection} />
        )
      }
      return children
    }

    const labelRenderer = ({ cellData, rowData }) => {
      if (cellData == null) return ''
      const label = <a target='_blank' rel='noopener noreferrer' href={rowData.id}>{cellData}</a>
      let marker = ''
      if (typeof rowData.lat !== 'undefined' || typeof rowData.long !== 'undefined') {
        marker = (
          <IconButton disabled aria-label='Marker' size="large">
            <PlaceIcon />
          </IconButton>
        )
      }
      return (
        <div key={rowData.id}>
          {label}{marker}
        </div>
      )
    }

    const sourceRenderer = ({ cellData, rowData }) => {
      if (cellData == null) return ''
      if (has(rowData, 'namesArchiveLink')) {
        return (
          <div key={rowData.s}>
            <a target='_blank' rel='noopener noreferrer' href={rowData.namesArchiveLink}>{cellData}</a>
          </div>
        )
      } else {
        return (
          <div key={rowData.s}>{cellData}</div>
        )
      }
    }

    return (
      <div className={classes.root}>
        {this.props.list.size > 0 &&
          <AutoSizer>
            {({ height, width }) => (
              <Table
                overscanRowCount={10}
                rowHeight={40}
                rowGetter={rowGetter}
                rowCount={this.props.list.size}
                sort={this._sort}
                sortBy={this.props.clientFSState.sortBy}
                sortDirection={this.props.clientFSState.sortDirection.toUpperCase()}
                width={width}
                height={height}
                headerHeight={50}
                noRowsRenderer={this._noRowsRenderer}
                style={tableStyles.tableRoot}
                rowStyle={calculateRowStyle}
              >
                <Column
                  label={intl.get(`perspectives.${perspectiveID}.properties.prefLabel.label`)}
                  cellDataGetter={({ rowData }) => rowData.prefLabel}
                  dataKey='prefLabel'
                  headerRenderer={headerRenderer}
                  cellRenderer={labelRenderer}
                  width={columnWidth + 70}
                />
                <Column
                  label={intl.get(`perspectives.${perspectiveID}.properties.broaderTypeLabel.label`)}
                  cellDataGetter={({ rowData }) => has(rowData, 'broaderTypeLabel') ? rowData.broaderTypeLabel.toLowerCase() : ''}
                  dataKey='broaderTypeLabel'
                  headerRenderer={headerRenderer}
                  width={columnWidth + 10}
                />
                {/* <Column
                    label="NA type"
                    cellDataGetter={({rowData}) => has(rowData,'typeLabel') ? rowData.typeLabel.toLowerCase() : ''}
                    dataKey="typeLabel"
                    headerRenderer={headerRenderer}
                    width={columnWidth}
                  /> */}
                <Column
                  label={intl.get(`perspectives.${perspectiveID}.properties.broaderAreaLabel.label`)}
                  cellDataGetter={({ rowData }) => rowData.broaderAreaLabel}
                  dataKey='broaderAreaLabel'
                  headerRenderer={headerRenderer}
                  width={columnWidth}
                />
                <Column
                  label={intl.get(`perspectives.${perspectiveID}.properties.modifier.label`)}
                  cellDataGetter={({ rowData }) => rowData.modifier}
                  dataKey='modifier'
                  headerRenderer={headerRenderer}
                  width={columnWidth + 10}
                />
                <Column
                  label={intl.get(`perspectives.${perspectiveID}.properties.basicElement.label`)}
                  cellDataGetter={({ rowData }) => rowData.basicElement}
                  dataKey='basicElement'
                  headerRenderer={headerRenderer}
                  width={columnWidth}
                />
                {/*
                  <Column
                    label="Collector"
                    cellDataGetter={({rowData}) => rowData.collector}
                    dataKey="collector"
                    headerRenderer={headerRenderer}
                    width={columnWidth}
                  /> */}
                <Column
                  label={intl.get(`perspectives.${perspectiveID}.properties.collectionYear.label`)}
                  cellDataGetter={({ rowData }) => rowData.collectionYear}
                  dataKey='collectionYear'
                  headerRenderer={headerRenderer}
                  width={columnWidth}
                />
                <Column
                  label={intl.get(`perspectives.${perspectiveID}.properties.source.label`)}
                  cellDataGetter={({ rowData }) => rowData.source}
                  dataKey='source'
                  headerRenderer={headerRenderer}
                  cellRenderer={sourceRenderer}
                  width={columnWidth}
                />
              </Table>
            )}
          </AutoSizer>}
      </div>
    )
  }
Example #4
Source File: LogTable.js    From binary-bot with MIT License 4 votes vote down vote up
Logtable = () => {
    const [id, setId] = React.useState(0);
    const [rows, setRows] = React.useState([]);
    const [widths, setWidths] = React.useState({
        timestamp: 0.25,
        message: 0.75,
    });

    const total_width = 1150;
    const min_height = 550;
    const cache = new CellMeasurerCache({
        defaultHeight: 35,
    });

    const columns = [
        { label: translate('Timestamp'), dataKey: 'timestamp' },
        { label: translate('Message'), dataKey: 'message' },
    ];

    React.useEffect(() => {
        globalObserver.register('log.export', exportLogs);
        globalObserver.register('bot.notify', notify);
        return () => {
            globalObserver.unregister('log.export', exportLogs);
            globalObserver.unregister('bot.notify', notify);
        };
    }, [rows]);

    const exportLogs = () => {
        const json2csvParser = new Parser({
            fields: ['timestamp', 'message'],
        });
        const data = json2csvParser.parse(rows);

        saveAs({ data, filename: 'logs.csv', type: 'text/csv;charset=utf-8' });
    };

    const notify = log => {
        if (!log) return;
        const { id: updated_id, rows: updated_rows } = appendRow(log, { id, rows }, true);
        setId(updated_id);
        setRows(updated_rows);
    };

    const headerRenderer = ({ dataKey, label }) => {
        const index = columns.findIndex(col => col.dataKey === dataKey);
        const is_last_column = index + 1 === columns.length;

        return (
            <React.Fragment key={dataKey}>
                <div className="ReactVirtualized__Table__headerTruncatedText">{label}</div>
                {!is_last_column && (
                    <Draggable
                        axis="x"
                        defaultClassName="DragHandle"
                        defaultClassNameDragging="DragHandleActive"
                        onDrag={(e, { deltaX }) =>
                            resizeRow({
                                dataKey,
                                deltaX,
                            })
                        }
                        position={{ x: 0 }}
                        zIndex={999}
                    >
                        <span className="DragHandleIcon log-table" />
                    </Draggable>
                )}
            </React.Fragment>
        );
    };

    const resizeRow = ({ deltaX }) => {
        const prev_widths = { ...widths };
        const percent_delta = deltaX / total_width;

        setWidths({
            message: prev_widths.message - percent_delta,
            timestamp: prev_widths.timestamp + percent_delta,
        });
    };

    const rowRenderer = ({ rowData, columns: cols, className, key }) => (
        <div className={`${className} ${rowData.type}`} key={key}>
            {cols?.map(({ props, key: inner_key }) => (
                <div style={props.style} className={props.className} role={props.role} key={inner_key}>
                    {props.title}
                </div>
            ))}
        </div>
    );

    return (
        <span id="logPanel" className="draggable-dialog" title={translate("Log")}>
            <div id="logTable" className="logTable-scroll">
                <div className="content-row">
                    <div>
                        <div className="content-row-table">
                            <div style={{ height: min_height }}>
                                <Table
                                    width={760}
                                    height={min_height}
                                    headerHeight={35}
                                    rowHeight={35}
                                    rowCount={rows.length}
                                    rowGetter={({ index }) => rows[index]}
                                    headerStyle={{
                                        fontSize: 11,
                                        textTransform: 'capitalize',
                                    }}
                                    rowRenderer={rowRenderer}
                                    deferredMeasurementCache={cache}
                                >
                                    {columns.map(({ label, dataKey }, index) => (
                                        <Column
                                            key={index}
                                            headerRenderer={headerRenderer}
                                            width={widths[dataKey] * total_width}
                                            label={label}
                                            dataKey={dataKey}
                                        />
                                    ))}
                                </Table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </span>
    );
}
Example #5
Source File: TradeTable.js    From binary-bot with MIT License 4 votes vote down vote up
TradeTable = ({ account_id, api }) => {
    const initial_state = { id: 0, rows: [] };
    const [account_state, setAccountState] = React.useState({ [account_id]: initial_state });

    const actual_account_state_ref = React.useRef(account_state);
    actual_account_state_ref.current = account_state;

    const rows = account_id in account_state ? account_state[account_id].rows : [];

    const total_width = 750;
    const min_height = 290;
    const row_height = 25;

    const columns = [
        { key: 'timestamp', label: translate('Timestamp'), width: 196 },
        { key: 'reference', label: translate('Reference'), width: 88 },
        { key: 'contract_type', label: translate('Trade type'), width: 70 },
        { key: 'entry_tick', label: translate('Entry spot'), width: 71 },
        { key: 'exit_tick', label: translate('Exit spot'), width: 71 },
        { key: 'buy_price', label: translate('Buy price'), width: 84 },
        { key: 'profit', label: translate('Profit/Loss'), width: 89 },
        { key: 'contract_status', label: translate('Status'), width: 73 },
    ];

    const getTradeObject = contract => {
        const trade_obj = {
            ...contract,
            reference: contract.transaction_ids.buy,
            buy_price: roundBalance({ balance: contract.buy_price, currency: contract.currency }),
            timestamp: getTimestamp(contract.date_start),
        };
        if (contract.entry_tick) {
            trade_obj.entry_tick = contract.entry_spot_display_value;
        }
        if (contract.exit_tick) {
            trade_obj.exit_tick = contract.exit_tick_display_value;
        }
        return trade_obj;
    };

    const exportSummary = () => {
        if (account_state[account_id]?.rows?.length > 0) data_export();
    };

    const clearBot = () => {
        setAccountState({ [account_id]: { ...initial_state } });
        global_observer.emit('summary.disable_clear');
    };

    const stopBot = () => {
        if (account_state[account_id]?.rows?.length > 0) global_observer.emit('summary.enable_clear');
    };

    const contractBot = contract => {
        if (!contract) return;
        const trade_obj = getTradeObject(contract);
        const trade = {
            ...trade_obj,
            profit: getProfit(trade_obj),
            contract_status: translate('Pending'),
            contract_settled: false,
        };
        const trade_obj_account_id = trade_obj.accountID;
        const account_state_by_id = getAccountStateById(trade_obj_account_id);
        const trade_obj_state_rows = account_state_by_id.rows;
        const prev_row_index = trade_obj_state_rows.findIndex(t => t.reference === trade.reference);
        if (trade.is_expired && trade.is_sold && !trade.exit_tick) {
            trade.exit_tick = '-';
        }
        if (prev_row_index >= 0) {
            setAccountState({ [trade_obj_account_id]: updateRow(prev_row_index, trade, account_state_by_id) });
        } else {
            setAccountState({ [trade_obj_account_id]: appendRow(trade, account_state_by_id) });
        }
    };

    const settledContract = async ({ contract_id }) => {
        let settled = false;
        let delay = 3000;
        const sleep = () => new Promise(resolve => setTimeout(() => resolve(), delay));

        while (!settled) {
            await sleep();
            try {
                await refreshContract(api, contract_id);
                const rows = account_state[account_id].rows; //eslint-disable-line
                const contract_row = rows.find(row => row.contract_id === contract_id); //eslint-disable-line
                if (contract_row && contract_row.contract_settled) {
                    settled = true;
                }
            } catch (e) {
                // Do nothing. Loop again.
            } finally {
                delay *= 1.5;
            }
        }
    };

    const refreshContract = async (_api, contract_id) => {
        const contract_info = await _api.send({ proposal_open_contract: 1, contract_id });
        const contract = contract_info.proposal_open_contract;
        const trade_obj = getTradeObject(contract);
        const trade = {
            ...trade_obj,
            profit: getProfit(trade_obj),
        };
        if (trade.is_expired && trade.is_sold && !trade.exit_tick) {
            trade.exit_tick = '-';
        }

        const actual_rows = actual_account_state_ref.current[account_id].rows;
        const updated_rows = actual_rows.map(row => {
            const { reference } = row;
            if (reference === trade.reference) {
                return {
                    contract_status: translate('Settled'),
                    contract_settled: true,
                    reference,
                    ...trade,
                };
            }
            return row;
        });
        setAccountState({ [account_id]: { rows: updated_rows } });
    };

    React.useEffect(() => {
        global_observer.register('summary.export', exportSummary);
        global_observer.register('summary.clear', clearBot);
        global_observer.register('bot.stop', stopBot);
        global_observer.register('bot.contract', contractBot);
        global_observer.register('contract.settled', settledContract);

        return () => {
            global_observer.unregister('summary.export', exportSummary);
            global_observer.unregister('summary.clear', clearBot);
            global_observer.unregister('bot.stop', stopBot);
            global_observer.unregister('bot.contract', contractBot);
            global_observer.unregister('contract.settled', settledContract);
        };
    }, [account_state]);

    const rowGetter = ({ index }) => {
        const got_rows = account_state[account_id].rows;
        return got_rows[got_rows.length - 1 - index];
    };

    const data_export = () => {
        const to_data_rows = account_state[account_id].rows.map((item, index) => {
            const to_data_row = item;
            to_data_row.id = index + 1;
            return to_data_row;
        });

        const json2csvParser = new Parser({ fields: [
            'id',
            'timestamp',
            'reference',
            'contract_type',
            'entry_tick',
            'exit_tick',
            'buy_price',
            'sell_price',
            'profit',
        ] });
        const data = json2csvParser.parse(to_data_rows);

        saveAs({ data, filename: 'logs.csv', type: 'text/csv;charset=utf-8' });
    };

    const getAccountStateById = _account_id => {
        if (account_id in account_state) return account_state[account_id];
        setAccountState({ [_account_id]: { ...initial_state } });
        return initial_state;
    };

    const headerRenderer = ({ dataKey, label }) => {
        const headerIndex = columns.findIndex(col => col.key === dataKey);
        const isLastColumn = headerIndex + 1 === columns.length;

        return (
            <React.Fragment key={dataKey}>
                <div className="ReactVirtualized__Table__headerTruncatedText">{label}</div>
                {!isLastColumn && (
                    <Draggable
                        axis="x"
                        defaultClassName="DragHandle"
                        defaultClassNameDragging="DragHandleActive"
                        position={{ x: 0 }}
                        zIndex={999}
                    >
                        <span className="DragHandleIcon" />
                    </Draggable>
                )}
            </React.Fragment>
        );
    };

    const cellRenderer = ({ cellData, dataKey }) => {
        if (dataKey === 'profit') return <ProfitColor value={cellData} />;
        if (dataKey === 'contract_status') return <StatusFormat value={cellData} />;
        return <div>{cellData}</div>;
    };

    return (
        <div>
            <Table
                width={total_width}
                height={min_height}
                headerHeight={row_height}
                rowHeight={row_height}
                rowCount={rows.length}
                rowGetter={rowGetter}
                headerStyle={{
                    fontSize: 11,
                    textTransform: 'capitalize',
                }}
            >
                {columns.map(({ label, key, width }, index) => (
                    <Column
                        headerRenderer={headerRenderer}
                        cellRenderer={cellRenderer}
                        width={width}
                        key={index}
                        label={label}
                        dataKey={key}
                    />
                ))}
            </Table>
        </div>
    );
}