import { useRef, useState, useEffect } from 'react'; import { useTranslation } from 'react-i18next'; import { Challenge as ChallengeType } from '@plebbit/plebbit-react-hooks'; import { getPublicationType } from '../../lib/utils/challenge-utils'; import useIsMobile from '../../hooks/use-is-mobile'; import useChallengesStore from '../../stores/use-challenges-store'; import styles from './challenge-modal.module.css'; import _ from 'lodash'; import { useSpring, animated } from '@react-spring/web'; import { useDrag } from '@use-gesture/react'; interface ChallengeProps { challenge: ChallengeType; closeModal: () => void; } const Challenge = ({ challenge, closeModal }: ChallengeProps) => { const { t } = useTranslation(); const challenges = challenge?.[0]?.challenges; const publication = challenge?.[1]; const publicationType = getPublicationType(publication); const { author, content, link, title } = publication || {}; const { displayName } = author || {}; const [currentChallengeIndex, setCurrentChallengeIndex] = useState(0); const [answers, setAnswers] = useState([]); const isTextChallenge = challenges[currentChallengeIndex].type === 'text/plain'; const isImageChallenge = challenges[currentChallengeIndex].type === 'image/png'; const onAnswersChange = (e: React.ChangeEvent) => { setAnswers((prevAnswers) => { const updatedAnswers = [...prevAnswers]; updatedAnswers[currentChallengeIndex] = e.target.value; return updatedAnswers; }); }; const onSubmit = () => { publication.publishChallengeAnswers(answers); setAnswers([]); closeModal(); }; const onEnterKey = (e: React.KeyboardEvent) => { if (e.key !== 'Enter') return; if (!answers[currentChallengeIndex]) return; if (challenges[currentChallengeIndex + 1]) { setCurrentChallengeIndex((prev) => prev + 1); } else { onSubmit(); } }; useEffect(() => { const onEscapeKey = (e: KeyboardEvent) => { if (e.key === 'Escape') { closeModal(); } }; document.addEventListener('keydown', onEscapeKey); return () => document.removeEventListener('keydown', onEscapeKey); }, [closeModal]); const nodeRef = useRef(null); const isMobile = useIsMobile(); const [{ x, y }, api] = useSpring(() => ({ x: window.innerWidth / 2 - 150, y: window.innerHeight / 2 - 200, })); const bind = useDrag( ({ active, event, offset: [ox, oy] }) => { if (active) { event.preventDefault(); document.body.style.userSelect = 'none'; document.body.style.webkitUserSelect = 'none'; } else { document.body.style.userSelect = ''; document.body.style.webkitUserSelect = ''; } api.start({ x: ox, y: oy, immediate: true }); }, { from: () => [x.get(), y.get()], filterTaps: true, bounds: undefined, }, ); const modalContent = (
Challenge for {publicationType}
{title && (
)} {content && (