import React, { useState } from 'react' import { useDispatch } from 'react-redux' import { DndContext, closestCenter, PointerSensor, useSensor, useSensors } from '@dnd-kit/core' import { SortableContext, arrayMove, verticalListSortingStrategy } from '@dnd-kit/sortable' import { State } from 'country-state-city' import { updateComponentProperties, updateComponentProperty } from '@epicformbuilder/admin/data' const SortableElement = ({ id, value, handleOptionChange, handleOptionRemove, handleOptionRadio, checked }) => { const onChange = event => handleOptionChange(event) const onRemove = event => handleOptionRemove(event) return (
  • handleOptionRadio(value)} />
  • ) } export default function StateOptions ({ id, country, options, defaults }) { const dispatch = useDispatch() const [option, setOption] = useState('') const sensors = useSensors( useSensor(PointerSensor) ) function handleSortEnd({ oldIndex, newIndex }) { dispatch( updateComponentProperty( id, 'options', Object.assign({}, options, { [country]: arrayMove(getOptions(), oldIndex, newIndex) }))) } function handleOptionChange( optionIndex ) { return ( event ) => { const oldValue = options[ optionIndex ] const newValue = event.target.value dispatch( updateComponentProperties( id, { options: Object.assign({}, options, { [country]: getOptions().map((item, index) => { if (index === optionIndex) return newValue; return item }) }), defaults: Object.assign({}, defaults, { [country]: defaults[country] ? defaults[country].map(item => { if (item === oldValue) return newValue; return item }): [] }), } )) } } function handleOptionRemove( optionIndex ) { return event => { event.preventDefault() const value = getOptions()[ optionIndex ] dispatch( updateComponentProperties( id, { options: Object.assign({}, options, { [country]: getOptions().filter((item, index) => index !== optionIndex) }), defaults: Object.assign({}, defaults, { [country]: defaults[country] ? defaults[country].filter(state => state !== value): [] }) } )) } } function handleOptionRadio(value) { dispatch(updateComponentProperty(id, 'defaults', Object.assign({}, defaults, { [country]: [value] }))) } function getOptions() { return country ? (options.hasOwnProperty( country ) ? options[country] : State.getStatesOfCountry( country ).map( state => state.name ) ) : [] } function addOption(event) { event.preventDefault() if ('' !== option && Boolean(country)) { dispatch( updateComponentProperty( id,'options', Object.assign( {}, options, { [country]: getOptions().concat( [option] ) } ) ) ) setOption('') } } function addOptionChange(event) { setOption(event.target.value) } const opts = getOptions().map((value, index) => ) return ( 0 < opts.length ? ( <> index ) } strategy={ verticalListSortingStrategy } >
      { opts }
    ) : (
    No Options. Please, choose a Country.
    ) ) }