UNPKG

@eureca/eureca-ui

Version:

UI component library of Eureca's user and admin apps

126 lines (109 loc) 3.14 kB
import React, { useState, useEffect, useCallback } from 'react'; import PropTypes from 'prop-types'; import { FiX } from 'react-icons/fi'; import { Box, Typography } from '@material-ui/core'; import { Flex } from '../Flex'; import { TextInput } from '../Inputs'; import { Radio } from '../Radio'; import { Checkbox } from '../Checkbox'; import { colors } from '../../theme/colors'; import { useToggle } from '../../hooks/useToggle'; const IndexComponent = ({ type, index }) => { return { checkbox: <Checkbox name={`checkbox-${index}`} value={false} disabled />, radio: <Radio name={`radio-${index}`} value={false} disabled />, number: ( <Box mr={1}> <Typography variant="body1">{index + 1}.</Typography> </Box> ), }[type]; }; function ListItem({ element, index, onChange, type, onDelete }) { const [close, toggleClose] = useToggle(); return ( <Flex directionRow alignCenter onMouseEnter={toggleClose} onMouseLeave={toggleClose} width={1}> <IndexComponent type={type} index={index} /> <TextInput inputProps={{ 'data-testid': `input-testid` }} variant="standard" name="answer" onChange={e => onChange(e.target.value, index)} placeholder={`Opção ${index + 1}`} value={element} /> {close && ( <Flex p={2} justifyCenter alignCenter data-testid="close-testid" onClick={() => onDelete(index)} cursorPointer > <FiX color={colors.gray3} size={22} /> </Flex> )} </Flex> ); } function List({ type, updateList }) { const [list, setList] = useState([]); const addQuestion = useCallback(function() { const emptyItem = ''; setList(oldList => [...oldList, emptyItem]); }, []); function deleteQuestion(index) { const tempList = [...list]; tempList.splice(index, 1); setList([...tempList]); } function onChange(value, index) { const tempList = [...list]; tempList[index] = value; setList([...tempList]); } useEffect(() => { updateList(list); }, [list, updateList]); // Adds the first empty item at mount useEffect(() => { addQuestion(); }, [addQuestion]); return ( <Flex> {list.map((element, index) => ( <ListItem key={`item-${index}`} element={element} index={index} type={type} onDelete={deleteQuestion} onChange={onChange} /> ))} <Flex directionRow alignCenter cursorPointer> <IndexComponent type={type} index={list.length} /> <TextInput data-testid="add-question-testid" variant="standard" name="add-option" disabled onChange={() => {}} label="Adicionar opção" onClick={addQuestion} inputProps={{ style: { cursor: 'pointer' } }} /> </Flex> </Flex> ); } List.defaultProps = { type: 'number', updateList: () => {}, }; List.propTypes = { type: PropTypes.string, updateList: PropTypes.func.isRequired, }; export { List };