import { useState, useEffect, useRef, KeyboardEvent } from 'react'; import { Row, Col, Label, Input, Modal, ModalBody, Form } from 'reactstrap'; import { faPlus, faArrowLeft } from '@fortawesome/free-solid-svg-icons'; import { useTranslation } from 'next-i18next'; import Image from 'next/image'; import { ElectionTypes, useElection } from '@services/ElectionContext'; import Button from '@components/Button'; import { upload } from '@services/imgpush'; import { IMGPUSH_URL } from '@services/constants'; import { AppTypes, useAppContext } from '@services/context'; import defaultAvatar from '../../public/default-avatar.svg'; const CandidateModal = ({ isOpen, position, toggle }) => { const { t } = useTranslation(); const [election, dispatch] = useElection(); const candidate = election.candidates[position]; const [state, setState] = useState(candidate); const image = state.image && state.image != '' ? state.image : defaultAvatar; const handleFile = async (event) => { const payload = await upload(event.target.files[0]); setState((s) => ({ ...s, image: `${IMGPUSH_URL}/${payload['filename']}` })); }; const [app, dispatchApp] = useAppContext(); // to manage the hidden ugly file input const hiddenFileInput = useRef(null); const inputRef = useRef(null); const names = election.candidates .filter((_, i) => i != position) .map((c) => c.name); const disabled = state.name === '' || names.includes(state.name); useEffect(() => { setState(election.candidates[position]); }, [election]); useEffect(() => { // When isOpen got active, we put the focus on the input field setTimeout(() => { console.log(inputRef.current); if (isOpen && inputRef && inputRef.current) { inputRef.current.focus(); } }, 100); }, [isOpen]); // check if key down is enter const handleKeyDown = (e: KeyboardEvent) => { if (e.key == 'Enter') { save(e); } }; const save = (e) => { e.preventDefault(); if (state.name === '') { dispatchApp({ type: AppTypes.TOAST_ADD, status: 'error', message: t('error.empty-name'), }); return; } if (names.includes(state.name)) { alert('foo'); dispatchApp({ type: AppTypes.TOAST_ADD, status: 'error', message: t('error.twice-same-names'), }); return; } dispatch({ type: ElectionTypes.CANDIDATE_SET, position: position, field: 'image', value: state.image, }); dispatch({ type: ElectionTypes.CANDIDATE_SET, position: position, field: 'name', value: state.name, }); dispatch({ type: ElectionTypes.CANDIDATE_SET, position: position, field: 'description', value: state.description, }); toggle(); }; const handleName = (e) => { setState((s) => ({ ...s, name: e.target.value })); }; const handleDescription = (e) => { setState((s) => ({ ...s, description: e.target.value })); }; return (

{t('admin.add-candidate')}

{t('admin.add-candidate-desc')}

{t('admin.photo')}

{t('admin.photo-type')} jpg, png, pdf