import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import { Helmet } from 'react-helmet-async'; import { Link, useNavigate, useParams } from 'react-router-dom'; import { confirmAlert } from 'react-confirm-alert'; import { Tooltip } from 'react-tooltip'; import { useAccount, useAccountComments, useComment, usePublishComment, usePublishCommentEdit, useSubplebbit } from '@plebbit/plebbit-react-hooks'; import { flattenCommentsPages } from '@plebbit/plebbit-react-hooks/dist/lib/utils' import { debounce } from 'lodash'; import { Container, NavBar, Header, Break, PostForm, PostFormTable, PostMenu, PostMenuMobile } from '../styled/views/Board.styled'; import { ReplyFormLink, TopBar, BottomBar, BoardForm, Footer } from '../styled/views/Thread.styled'; import { AlertModal } from '../styled/modals/AlertModal.styled'; import { PostMenuCatalog } from '../styled/views/Catalog.styled'; import BoardStats from '../BoardStats'; import EditLabel from '../EditLabel'; import Embed from '../Embed'; import ImageBanner from '../ImageBanner'; import OfflineIndicator from '../OfflineIndicator'; import PendingLabel from '../PendingLabel'; import Post from '../Post'; import PostLoader from '../PostLoader'; import PostOnHover from '../PostOnHover'; import StateLabel from '../StateLabel'; import VerifiedAuthor from '../VerifiedAuthor'; import CreateBoardModal from '../modals/CreateBoardModal'; import EditModal from '../modals/EditModal'; import ModerationModal from '../modals/ModerationModal'; import ReplyModal from '../modals/ReplyModal'; import SettingsModal from '../modals/SettingsModal'; import findShortParentCid from '../../utils/findShortParentCid'; import getCommentMediaInfo from '../../utils/getCommentMediaInfo'; import getDate from '../../utils/getDate'; import getFormattedTime from '../../utils/getFormattedTime'; import handleAddressClick from '../../utils/handleAddressClick'; import handleImageClick from '../../utils/handleImageClick'; import handleQuoteClick from '../../utils/handleQuoteClick'; import handleQuoteHover from '../../utils/handleQuoteHover'; import handleShareClick from '../../utils/handleShareClick'; import handleStyleChange from '../../utils/handleStyleChange'; import removeHighlight from '../../utils/removeHighlight'; import useAnonMode from '../../hooks/useAnonMode'; import useClickForm from '../../hooks/useClickForm'; import useError from '../../hooks/useError'; import useStateString from '../../hooks/useStateString'; import useSuccess from '../../hooks/useSuccess'; import useAnonModeStore from '../../hooks/stores/useAnonModeStore'; import useGeneralStore from '../../hooks/stores/useGeneralStore'; import packageJson from '../../../package.json'; const {version} = packageJson; const commitRef = process?.env?.REACT_APP_COMMIT_REF ? ` ${process.env.REACT_APP_COMMIT_REF.slice(0, 7)}` : ''; const Thread = () => { const { captchaResponse, setCaptchaResponse, setChallengesArray, defaultSubplebbits, editedComment, setIsAuthorDelete, setIsAuthorEdit, setIsCaptchaOpen, isModerationOpen, setIsModerationOpen, isSettingsOpen, setIsSettingsOpen, setModeratingCommentCid, setReplyQuoteCid, setResolveCaptchaPromise, setPendingComment, setPendingCommentIndex, setSelectedAddress, setSelectedParentCid, setSelectedShortCid, selectedStyle, selectedThread, setSelectedThread, setSelectedText, selectedTitle, setSelectedTitle, showPostForm, showPostFormLink, setTriggerInsertion, } = useGeneralStore(state => state); const { anonymousMode } = useAnonModeStore(); const account = useAccount(); const navigate = useNavigate(); const handleClickForm = useClickForm(); const [, setNewErrorMessage] = useError(); const [, setNewSuccessMessage] = useSuccess(); const nameRef = useRef(); const commentRef = useRef(); const linkRef = useRef(); const threadMenuRefs = useRef({}); const threadMenuRefsMobile = useRef({}); const replyMenuRefs = useRef({}); const replyMenuRefsMobile = useRef({}); const postMenuRef = useRef(null); const postMenuMobileRef = useRef(null); const postMenuCatalogRef = useRef(null); const backlinkRefs = useRef({}); const quoteRefs = useRef({}); const postRefs = useRef({}); const postOnHoverRef = useRef(null); const backlinkRefsMobile = useRef({}); const quoteRefsMobile = useRef({}); const [triggerPublishComment, setTriggerPublishComment] = useState(false); const [triggerPublishCommentEdit, setTriggerPublishCommentEdit] = useState(false); const [deletePost, setDeletePost] = useState(false); const [isReplyOpen, setIsReplyOpen] = useState(false); const [isEditModalOpen, setIsEditModalOpen] = useState(false); const [originalCommentContent, setOriginalCommentContent] = useState(null); const [prevScrollPos, setPrevScrollPos] = useState(0); const [visible, setVisible] = useState(true); const [isImageSearchOpen, setIsImageSearchOpen] = useState(false); const [isClientRedirectMenuOpen, setIsClientRedirectMenuOpen] = useState(false); const [isModerator, setIsModerator] = useState(false); const [commentCid, setCommentCid] = useState(null); const [menuPosition, setMenuPosition] = useState({top: 0, left: 0}); const [mobileMenuPosition, setMobileMenuPosition] = useState({top: 0, left: 0}); const [openMenuCid, setOpenMenuCid] = useState(null); const [openMobileMenuCid, setOpenMobileMenuCid] = useState(null); const [outOfViewCid, setOutOfViewCid] = useState(null); const [outOfViewPosition, setOutOfViewPosition] = useState({top: 0, left: 0}); const [postOnHoverHeight, setPostOnHoverHeight] = useState(0); const [executeAnonMode, setExecuteAnonMode] = useState(false); const [cidTracker, setCidTracker] = useState({}); const [isThreadThumbnailClicked, setIsThreadThumbnailClicked] = useState({}); const [isReplyThumbnailClicked, setIsReplyThumbnailClicked] = useState({}); const [isMobileThreadThumbnailClicked, setIsMobileThreadThumbnailClicked] = useState({}); const [isMobileReplyThumbnailClicked, setIsMobileReplyThumbnailClicked] = useState({}); const [isCreateBoardOpen, setIsCreateBoardOpen] = useState(false); useAnonMode(selectedThread, anonymousMode && executeAnonMode); const comment = useComment({commentCid: selectedThread}); const { subplebbitAddress, threadCid } = useParams(); const subplebbit = useSubplebbit({subplebbitAddress: comment.subplebbitAddress}); const selectedAddress = subplebbit.address; const stateString = useStateString(comment); const commentMediaInfo = getCommentMediaInfo(comment); const fallbackImgUrl = "assets/filedeleted-res.gif"; const handleThumbnailClick = (index, type) => { switch(type) { case 'thread': setIsThreadThumbnailClicked(prevState => ({ ...prevState, [index]: !prevState[index], })); break; case 'reply': setIsReplyThumbnailClicked(prevState => ({ ...prevState, [index]: !prevState[index], })); break; case 'mobileThread': setIsMobileThreadThumbnailClicked(prevState => ({ ...prevState, [index]: !prevState[index], })); break; case 'mobileReply': setIsMobileReplyThumbnailClicked(prevState => ({ ...prevState, [index]: !prevState[index], })); break; default: break; } }; useEffect(() => { if (subplebbit.roles !== undefined) { const role = subplebbit.roles[account?.author?.address]?.role; if (role === 'moderator' || role === 'admin' || role === 'owner') { setIsModerator(true); } else { setIsModerator(false); } } }, [account?.author.address, subplebbit.roles]); const handleOptionClick = () => { setOpenMenuCid(null); }; const handleMobileOptionClick = () => { setOpenMobileMenuCid(null); }; const handleOutsideClick = useCallback((e) => { if (openMenuCid !== null && !postMenuRef.current.contains(e.target) && !postMenuCatalogRef.current.contains(e.target)) { setOpenMenuCid(null); } }, [openMenuCid, postMenuRef, postMenuCatalogRef]); const handleMobileOutsideClick = useCallback((e) => { if (openMobileMenuCid !== null && !postMenuMobileRef.current.contains(e.target)) { setOpenMobileMenuCid(null); } }, [openMobileMenuCid, postMenuMobileRef]); useEffect(() => { if (openMenuCid !== null) { document.addEventListener('click', handleOutsideClick); } else { document.removeEventListener('click', handleOutsideClick); } return () => { document.removeEventListener('click', handleOutsideClick); }; }, [openMenuCid, handleOutsideClick]); useEffect(() => { if (openMobileMenuCid !== null) { document.addEventListener('click', handleMobileOutsideClick); } else { document.removeEventListener('click', handleMobileOutsideClick); } return () => { document.removeEventListener('click', handleMobileOutsideClick); }; }, [openMobileMenuCid, handleMobileOutsideClick]); useEffect(() => { if (postOnHoverRef.current) { const rect = postOnHoverRef.current.getBoundingClientRect(); setPostOnHoverHeight(rect.height); } }, [outOfViewCid]); useEffect(() => { window.scrollTo(0, 0); }, []); useEffect(() => { if ( comment.state === "failed" && selectedAddress === undefined) { navigate('/404'); } }, [selectedAddress, navigate, comment.state]); const errorString = useMemo(() => { if (comment?.state === 'failed') { let errorString = 'Failed fetching thread.' if (comment.error) { errorString += `: ${comment.error.toString().slice(0, 300)}` } return errorString } }, [comment?.state, comment?.error]) useEffect(() => { if (errorString) { setNewErrorMessage(errorString); } }, [errorString, setNewErrorMessage]); const flattenedReplies = useMemo(() => flattenCommentsPages(comment.replies), [comment.replies] ); const threadAndRepliesCids = useMemo(() => new Set([(selectedThread || 'n/a'), ...flattenedReplies.map(reply => reply.cid)]), [selectedThread, flattenedReplies]); const filter = useCallback((accountComment) => threadAndRepliesCids.has(accountComment.parentCid), [threadAndRepliesCids]); 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]); // let post.jsx access full cid of user-typed short cid useEffect(() => { const newCidTracker = {}; sortedReplies.forEach((reply) => { newCidTracker[reply.shortCid] = reply.cid; }); setCidTracker(newCidTracker); }, [sortedReplies]); useEffect(() => { const selectedSubplebbit = defaultSubplebbits.find((subplebbit) => subplebbit.address === subplebbitAddress); if (threadCid) { setSelectedThread(threadCid); } if (subplebbitAddress) { setSelectedAddress(subplebbitAddress); } else if (subplebbit?.address) { setSelectedAddress(subplebbit.address) } if (selectedSubplebbit) { setSelectedTitle(selectedSubplebbit.title); } else if (subplebbit?.title) { setSelectedTitle(subplebbit.title); } }, [subplebbitAddress, threadCid, defaultSubplebbits, subplebbit, setSelectedThread, setSelectedAddress, setSelectedTitle]); // mobile navbar scroll effect useEffect(() => { const debouncedHandleScroll = debounce(() => { const currentScrollPos = window.scrollY; 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) { if (challengeVerification.publication?.cid !== undefined) { return; } else { setNewSuccessMessage('Challenge Success'); } } else if (challengeVerification.challengeSuccess === false) { setNewErrorMessage(`Challenge Failed, reason: ${challengeVerification.reason}. Errors: ${challengeVerification.errors}`); console.log('challenge failed', challengeVerification); } }; const onChallenge = async (challenges, comment) => { setPendingComment(comment); let challengeAnswers = []; try { challengeAnswers = await getChallengeAnswersFromUser(challenges) } catch (error) { setNewErrorMessage(error.message); console.log(error); } if (challengeAnswers) { await comment.publishChallengeAnswers(challengeAnswers) } }; useEffect(() => { setPublishCommentOptions((prevPublishCommentOptions) => ({ ...prevPublishCommentOptions, subplebbitAddress: comment.subplebbitAddress, })); }, [comment.subplebbitAddress]); const [publishCommentOptions, setPublishCommentOptions] = useState({ subplebbitAddress: comment.subplebbitAddress, onChallenge, onChallengeVerification, onError: (error) => { setNewErrorMessage(error.message); console.log(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(); if ( commentRef.current.value === "" && linkRef.current.value === "" ) { setNewErrorMessage("Please enter a comment or link."); return; } setPublishCommentOptions((prevPublishCommentOptions) => ({ ...prevPublishCommentOptions, author: { displayName: nameRef.current.value || undefined, ...(anonymousMode ? {} : {address: account?.author.address}), }, content: commentRef.current.value || undefined, link: linkRef.current.value || undefined, parentCid: selectedThread, })); setTriggerPublishComment(true); }; const updateSigner = useCallback(async () => { if (anonymousMode) { setExecuteAnonMode(true); let storedSigners = JSON.parse(localStorage.getItem('storedSigners')) || {}; let signer; if (!storedSigners[selectedThread]) { signer = await account?.plebbit.createSigner(); storedSigners[selectedThread] = { privateKey: signer?.privateKey, address: signer?.address }; localStorage.setItem('storedSigners', JSON.stringify(storedSigners)); } else { const signerPrivateKey = storedSigners[selectedThread].privateKey; try { signer = await account?.plebbit.createSigner({type: 'ed25519', privateKey: signerPrivateKey}); } catch (error) { console.log(error); } } setPublishCommentOptions(prevPublishCommentOptions => { const newPublishCommentOptions = { ...prevPublishCommentOptions, signer, author: { ...prevPublishCommentOptions.author, address: signer?.address, }, }; if (JSON.stringify(prevPublishCommentOptions) !== JSON.stringify(newPublishCommentOptions)) { return newPublishCommentOptions; } return prevPublishCommentOptions; }); } }, [selectedThread, anonymousMode, account]); useEffect(() => { if (anonymousMode) { updateSigner(); } }, [updateSigner, anonymousMode]); useEffect(() => { if (publishCommentOptions && triggerPublishComment) { (async () => { await publishComment(); resetFields(); })(); setTriggerPublishComment(false); setExecuteAnonMode(false); } }, [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(setNewErrorMessage('Could not load challenges')); }; }); }; const [publishCommentEditOptions, setPublishCommentEditOptions] = useState({ commentCid: commentCid, content: editedComment || undefined, subplebbitAddress: comment.subplebbitAddress, onChallenge, onChallengeVerification, onError: (error) => { setNewErrorMessage(error.message); console.log(error); }, }); const { publishCommentEdit } = usePublishCommentEdit(publishCommentEditOptions); const handleAuthorDeleteClick = (comment) => { handleOptionClick(comment.cid); confirmAlert({ customUI: ({ onClose }) => { return (

Are you sure you want to delete this post?

); } }); }; const handleAuthorEditClick = (comment) => { handleOptionClick(comment.cid); setIsAuthorEdit(true); setIsAuthorDelete(false); setCommentCid(comment.cid); setOriginalCommentContent(comment.content); setIsEditModalOpen(true); } useEffect(() => { setPublishCommentEditOptions((prevOptions) => ({ ...prevOptions, commentCid: commentCid, content: editedComment || undefined, })); }, [commentCid, editedComment]); useEffect(() => { if (editedComment !== '') { setTriggerPublishCommentEdit(true); } }, [editedComment]); useEffect(() => { let isActive = true; if (publishCommentEditOptions && triggerPublishCommentEdit) { (async () => { await publishCommentEdit(); if (isActive) { setTriggerPublishCommentEdit(false); } })(); } return () => { isActive = false; }; }, [triggerPublishCommentEdit, publishCommentEdit, publishCommentEditOptions]); // mobile navbar board select functionality const handleSelectChange = (event) => { const selected = event.target.value; if (selected === 'subscriptions') { navigate(`/p/subscriptions`); return; } else if (selected === 'all') { navigate(`/p/all`); return; } 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" )} setIsCreateBoardOpen(false)} /> setIsReplyOpen(false)} /> setIsSettingsOpen(false)} /> {setIsModerationOpen(false); setDeletePost(false)}} deletePost={deletePost} /> setIsEditModalOpen(false)} originalCommentContent={originalCommentContent} /> <> [ window.scrollTo(0, 0)}>All  /  window.scrollTo(0, 0)}>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} ))} ] [ { window.electron && window.electron.isElectron ? ( setIsCreateBoardOpen(true) ) : ( alert( 'You can create a board with the desktop version of plebchan:\nhttps://github.com/plebbit/plebchan/releases/latest\n\nIf you are comfortable with the command line, use plebbit-cli:\nhttps://github.com/plebbit/plebbit-cli\n\n' ) ) } }>Create Board ] [ setIsSettingsOpen(true)}>Settings ] [ Home ]
Board     alert( 'You can create a board with the desktop version of plebchan:\nhttps://github.com/plebbit/plebchan/releases/latest\n\nIf you are comfortable with the command line, use plebbit-cli:\nhttps://github.com/plebbit/plebbit-cli\n\n' ) }>Create Board
setIsSettingsOpen(true)}>Settings   {handleStyleChange({target: {value: "Yotsuba"}}); window.scrollTo(0, 0);}}>Home
 
 
<>
<>
{subplebbit.title ?? null}
p/{subplebbit.address}
{window.scrollTo(0, 0)}}> Return
{window.scrollTo(0, 0)}}>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 {account && account?.author && account?.author.displayName ? ( ) : ( )} Comment