UNPKG

@bigfishtv/cockpit

Version:

79 lines (71 loc) 2.12 kB
import PropTypes from 'prop-types' import React, { Component } from 'react' import { withFormValue } from '@bigfishtv/react-forms' import newId from '../../utils/newId' @withFormValue export default class RepeatableFieldset extends Component { static propTypes = { Item: PropTypes.func.isRequired, formValue: PropTypes.object.isRequired, removable: PropTypes.bool, reorderable: PropTypes.bool, duplicable: PropTypes.bool, itemKey: PropTypes.func, } static defaultProps = { removable: true, reorderable: true, duplicable: false, className: '', itemProps: {}, itemKey: (item, i) => item.id || 'cell' + i, } handleRemove(index) { const value = this.props.formValue.value.filter((val, i) => i !== index) this.props.formValue.update(value) } handleMove = (id, afterId) => { let Cells = this.props.formValue.value.slice() const cell = Cells.filter(c => c.id === id)[0] const afterCell = Cells.filter(c => c.id === afterId)[0] const cellIndex = Cells.indexOf(cell) const afterIndex = Cells.indexOf(afterCell) Cells.splice(cellIndex, 1) Cells.splice(afterIndex, 0, cell) this.props.formValue.update(Cells) } handleDuplicate(index) { const formValue = this.props.formValue.value || [] const items = formValue.filter((val, i) => i === index) if (!items.length) { console.warn('No item to duplicate???') return } const item = { ...items[0] } item.id = newId() if (typeof item.title == 'string') item.title += ' copy' formValue.push(item) this.props.formValue.update(formValue) } render() { const { Item, removable, reorderable, duplicable, className, itemProps, itemKey } = this.props return ( <div className={'cells ' + className}> {(this.props.formValue.value || []).map((item, i) => ( <Item key={itemKey(item, i)} id={item.id} select={[i]} removable={removable} reorderable={reorderable} duplicable={duplicable} onRemove={() => this.handleRemove(i)} onMove={this.handleMove} onDuplicate={() => this.handleDuplicate(i)} {...itemProps} /> ))} </div> ) } }