import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Helmet } from 'react-helmet-async'; import { Link, useNavigate, useParams } from 'react-router-dom'; import { Tooltip } from 'react-tooltip'; import { useAccount, useAccountComments, useComment, usePublishComment } from '@plebbit/plebbit-react-hooks'; import { flattenCommentsPages } from '@plebbit/plebbit-react-hooks/dist/lib/utils' import { debounce } from 'lodash'; import useGeneralStore from '../../hooks/stores/useGeneralStore'; import { Container, NavBar, Header, Break, PostForm, PostFormTable } from '../styled/Board.styled'; import { ReplyFormLink, TopBar, BottomBar, BoardForm, Footer } from '../styled/Thread.styled'; import ImageBanner from '../ImageBanner'; import Post from '../Post'; import PostLoader from '../PostLoader'; import ReplyModal from '../ReplyModal'; import SettingsModal from '../SettingsModal'; import findShortParentCid from '../../utils/findShortParentCid'; import formatState from '../../utils/formatState'; import getCommentMediaInfo from '../../utils/getCommentMediaInfo'; import getDate from '../../utils/getDate'; import handleAddressClick from '../../utils/handleAddressClick'; import handleImageClick from '../../utils/handleImageClick'; import handleQuoteClick from '../../utils/handleQuoteClick'; import handleStyleChange from '../../utils/handleStyleChange'; import useClickForm from '../../hooks/useClickForm'; import useError from '../../hooks/useError'; import packageJson from '../../../package.json' const {version} = packageJson const Thread = () => { const { captchaResponse, setCaptchaResponse, setChallengesArray, defaultSubplebbits, setIsCaptchaOpen, isSettingsOpen, setIsSettingsOpen, setResolveCaptchaPromise, setPendingComment, setPendingCommentIndex, selectedAddress, setSelectedAddress, setSelectedParentCid, setSelectedShortCid, selectedStyle, selectedThread, setSelectedThread, selectedTitle, setSelectedTitle, showPostForm, showPostFormLink, } = useGeneralStore(state => state); const nameRef = useRef(); const commentRef = useRef(); const linkRef = useRef(); const [isReplyOpen, setIsReplyOpen] = useState(false); const navigate = useNavigate(); const [prevScrollPos, setPrevScrollPos] = useState(0); const [visible, setVisible] = useState(true); const account = useAccount(); const comment = useComment({commentCid: selectedThread}); const { subplebbitAddress, threadCid } = useParams(); const handleClickForm = useClickForm(); const commentMediaInfo = getCommentMediaInfo(comment); const fallbackImgUrl = "assets/filedeleted-res.gif"; const [errorMessage, setErrorMessage] = useState(null); useError(errorMessage, [errorMessage]); const [triggerPublishComment, setTriggerPublishComment] = useState(false); const flattenedReplies = useMemo(() => flattenCommentsPages(comment.replies), [comment.replies] ); const filter = useMemo(() => ({ parentCids: [ selectedThread || 'n/a', ...flattenedReplies.map(reply => reply.cid) ] }), [flattenedReplies, selectedThread]); const { accountComments } = useAccountComments({filter}); const accountRepliesNotYetInCommentReplies = useMemo(() => { const commentReplyCids = new Set(flattenedReplies.map(reply => reply.cid)) return accountComments.filter(accountReply => !commentReplyCids.has(accountReply.cid)) }, [flattenedReplies, accountComments]); const sortedReplies = useMemo(() => [ ...accountRepliesNotYetInCommentReplies, ...flattenedReplies ].sort((a, b) => a.timestamp - b.timestamp ), [accountRepliesNotYetInCommentReplies, flattenedReplies]); // temporary title from JSON, gets subplebbitAddress and threadCid from URL useEffect(() => { setSelectedAddress(subplebbitAddress); setSelectedThread(threadCid); const selectedSubplebbit = defaultSubplebbits.find((subplebbit) => subplebbit.address === subplebbitAddress); if (selectedSubplebbit) { setSelectedTitle(selectedSubplebbit.title); } }, [subplebbitAddress, setSelectedAddress, setSelectedTitle, defaultSubplebbits, setSelectedThread, threadCid]); // mobile navbar scroll effect useEffect(() => { const debouncedHandleScroll = debounce(() => { const currentScrollPos = window.pageYOffset; setVisible(prevScrollPos > currentScrollPos || currentScrollPos < 10); setPrevScrollPos(currentScrollPos); }, 50); window.addEventListener('scroll', debouncedHandleScroll); return () => window.removeEventListener('scroll', debouncedHandleScroll); }, [prevScrollPos, visible]); const onChallengeVerification = (challengeVerification) => { if (challengeVerification.challengeSuccess === true) { console.log('challenge success'); } else if (challengeVerification.challengeSuccess === false) { setErrorMessage('challenge failed', {reason: challengeVerification.reason, errors: challengeVerification.errors}); } }; const onChallenge = async (challenges, comment) => { setPendingComment(comment); let challengeAnswers = []; try { challengeAnswers = await getChallengeAnswersFromUser(challenges) } catch (error) { setErrorMessage(error); } if (challengeAnswers) { await comment.publishChallengeAnswers(challengeAnswers) } }; useEffect(() => { setPublishCommentOptions((prevPublishCommentOptions) => ({ ...prevPublishCommentOptions, subplebbitAddress: selectedAddress, })); }, [selectedAddress]); const [publishCommentOptions, setPublishCommentOptions] = useState({ subplebbitAddress: selectedAddress, onChallenge, onChallengeVerification, onError: (error) => { setErrorMessage(error); }, }); const { publishComment, index } = usePublishComment(publishCommentOptions); useEffect(() => { if (index !== undefined) { setPendingCommentIndex(index); } }, [index, setPendingCommentIndex]); const resetFields = useCallback(() => { if (nameRef.current) { nameRef.current.value = ''; } if (commentRef.current) { commentRef.current.value = ''; } if (linkRef.current) { linkRef.current.value = ''; } }, []); const handleSubmit = async (event) => { event.preventDefault(); setPublishCommentOptions((prevPublishCommentOptions) => ({ ...prevPublishCommentOptions, author: { displayName: nameRef.current.value || undefined, }, content: commentRef.current.value || undefined, link: linkRef.current.value || undefined, parentCid: selectedThread, })); setTriggerPublishComment(true); }; useEffect(() => { if (publishCommentOptions.content && triggerPublishComment) { (async () => { await publishComment(); resetFields(); })(); } }, [publishCommentOptions, triggerPublishComment, publishComment, resetFields]); const getChallengeAnswersFromUser = async (challenges) => { setChallengesArray(challenges); return new Promise((resolve, reject) => { const imageString = challenges?.challenges[0].challenge; const imageSource = `data:image/png;base64,${imageString}`; const challengeImg = new Image(); challengeImg.src = imageSource; challengeImg.onload = () => { setIsCaptchaOpen(true); const handleKeyDown = async (event) => { if (event.key === 'Enter') { const currentCaptchaResponse = captchaResponse; resolve(currentCaptchaResponse); setIsCaptchaOpen(false); document.removeEventListener('keydown', handleKeyDown); event.preventDefault(); } }; setCaptchaResponse(''); document.addEventListener('keydown', handleKeyDown); setResolveCaptchaPromise(resolve); }; challengeImg.onerror = () => { reject(setErrorMessage('Could not load challenges')); }; }); }; // mobile navbar board select functionality const handleSelectChange = (event) => { const selected = event.target.value; const selectedTitle = defaultSubplebbits.find((subplebbit) => subplebbit.address === selected).title; setSelectedTitle(selectedTitle); setSelectedAddress(selected); navigate(`/p/${selected}`); }; return ( <> {( (comment.content?.slice(0, 40) ?? comment.title?.slice(0, 40) ?? "Thread") + " - " + (selectedTitle ? selectedTitle : selectedAddress) + " - plebchan" )} setIsReplyOpen(false)} /> setIsSettingsOpen(false)} /> <> [ {}}>Subscriptions ] [ {defaultSubplebbits.map((subplebbit, index) => ( {index === 0 ? null : "\u00a0"} { setSelectedTitle(subplebbit.title); setSelectedAddress(subplebbit.address); }} >{subplebbit.title ? subplebbit.title : subplebbit.address} {index !== defaultSubplebbits.length - 1 ? " /" : null} ))} ] [ ] [ setIsSettingsOpen(true)}>Settings ] [ handleStyleChange({target: {value: "Yotsuba"}} )}>Home ]
Board    
setIsSettingsOpen(true)}>Settings   handleStyleChange({target: {value: "Yotsuba"}} )}>Home
 
 
<>
<>
{selectedTitle}
p/{selectedAddress}
Return
Catalog
window.scrollTo(0, document.body.scrollHeight)} onMouseOver={(event) => event.target.style.cursor='pointer'}>Bottom
[ {handleClickForm(); setSelectedShortCid(comment.shortCid)}} onMouseOver={(event) => event.target.style.cursor='pointer'}>Post a Reply ]
{handleClickForm(); setSelectedShortCid(comment.shortCid)}} onMouseOver={(event) => event.target.style.cursor='pointer'}>Post a Reply
Name Comment