import React from 'react'; import classnames from 'classnames'; import IconButton from './IconButton'; import styled from 'styled-components'; import { Editor } from './editor-types'; const StyledUl = styled.ul` list-style-type: none; margin: 0; padding: 0; li { margin-bottom: 2px; } &.inline { > li { border: 1px solid #e5e5e5; padding: 2px 0 2px 5px; margin-right: 5px; display: inline-block; &.add { border: none; } } } `; interface ArrayEditorProps { value: T[]; onChange: (value: T[]) => any; disabled?: boolean; inline?: boolean; newItemValue: T | ((value: T[]) => T); editor: Editor; className?: string; } /** * Renders an editor for generic items. * The 'editor' is a React component that accepts 'value' and 'onChange'. */ const ArrayEditor = ( props: ArrayEditorProps ): React.ReactElement> => { const { value = [], inline = false, newItemValue, editor: Editor, className, onChange = () => {}, disabled } = props; const handleChange = (index: number, newValue: T) => { if (disabled) return; const newList = value.slice(); newList[index] = newValue; onChange(newList); }; const handleAdd = () => { const newItem = newItemValue instanceof Function ? newItemValue(value) : newItemValue; const newList = value.concat(newItem); onChange(newList); }; const handleRemove = (index: number) => { const newList = value.slice(); newList.splice(index, 1); onChange(newList); }; const classNames = classnames('array-editor', { inline: inline }, className); return ( {value.map((item, i) => (
  • handleChange(i, val)} disabled={disabled} /> handleRemove(i)} disabled={disabled} />
  • ))}
  • Add
  • ); }; export default React.memo(ArrayEditor) as ( props: ArrayEditorProps ) => React.ReactElement>;