import React, { Fragment, useCallback, useEffect, useMemo, useState, useRef } from 'react'; import { confirmAlert } from 'react-confirm-alert'; import { createPortal } from 'react-dom'; import { Helmet } from 'react-helmet-async'; import { Link, useNavigate } from 'react-router-dom'; import { Tooltip } from 'react-tooltip'; import { Virtuoso } from 'react-virtuoso'; import { useAccount, useAccountComments, useFeed, usePublishCommentEdit, useSubplebbits } 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, TopBar, BoardForm, PostMenu } from '../styled/views/Board.styled'; import { Footer } from '../styled/views/Thread.styled'; import { AlertModal } from '../styled/modals/AlertModal.styled'; import { PostMenuCatalog } from '../styled/views/Catalog.styled'; import EditModal from '../modals/EditModal'; import EditLabel from '../EditLabel'; import ImageBanner from '../ImageBanner'; import ModerationModal from '../modals/ModerationModal'; 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 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 useAnonModeRef from '../../hooks/useAnonModeRef'; import useError from '../../hooks/useError'; import useFeedStateString from '../../hooks/useFeedStateString'; import useSuccess from '../../hooks/useSuccess'; import useAnonModeStore from '../../hooks/stores/useAnonModeStore'; import packageJson from '../../../package.json'; const {version} = packageJson; let lastVirtuosoStates = {}; const Subscriptions = () => { const { defaultSubplebbits, editedComment, feedCacheStates, setFeedCacheState, isSettingsOpen, setIsSettingsOpen, setModeratingCommentCid, selectedAddress, setCaptchaResponse, setChallengesArray, setIsAuthorDelete, setIsAuthorEdit, setIsCaptchaOpen, isModerationOpen, setIsModerationOpen, setReplyQuoteCid, setResolveCaptchaPromise, setSelectedAddress, setSelectedParentCid, setSelectedShortCid, selectedStyle, setSelectedThread, setSelectedText, setSelectedTitle, setTriggerInsertion, } = useGeneralStore(state => state); const { anonymousMode } = useAnonModeStore(); const account = useAccount(); const navigate = useNavigate(); const [, setNewErrorMessage] = useError(); const [, setNewSuccessMessage] = useSuccess(); const threadMenuRefs = useRef({}); const replyMenuRefs = useRef({}); const postMenuCatalogRef = useRef(null); const backlinkRefs = useRef({}); const quoteRefs = useRef({}); const postRefs = useRef({}); const backlinkRefsMobile = useRef({}); const quoteRefsMobile = useRef({}); const postOnHoverRef = useRef(null); const selectedThreadCidRef = useRef(null); const virtuosoRef = useRef(); 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 [commentCid, setCommentCid] = useState(null); const [menuPosition, setMenuPosition] = useState({top: 0, left: 0}); const [triggerPublishCommentEdit, setTriggerPublishCommentEdit] = useState(false); const [openMenuCid, setOpenMenuCid] = useState(null); const [outOfViewCid, setOutOfViewCid] = useState(null); const [outOfViewPosition, setOutOfViewPosition] = useState({top: 0, left: 0}); const [postOnHoverHeight, setPostOnHoverHeight] = useState(0); const [deletePost, setDeletePost] = useState(false); const [moderatorPermissions, setModeratorPermissions] = useState({}); 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); const setSelectedThreadCid = (cid) => { selectedThreadCidRef.current = cid }; const isFeedCached = feedCacheStates['subscriptions']; useAnonModeRef(selectedThreadCidRef, anonymousMode && executeAnonMode); const { feed, loadMore } = useFeed({subplebbitAddresses: account?.subscriptions, sortType: 'active'}); const [selectedFeed, setSelectedFeed] = useState(feed.sort((a, b) => b.timestamp - a.timestamp)); const {subplebbits} = useSubplebbits({subplebbitAddresses: account?.subscriptions, sortType: 'active'}); const stateString = useFeedStateString(subplebbits); useEffect(() => { if (feed) { setFeedCacheState('subscriptions', true); } }, [feed, setFeedCacheState]); 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(() => { let permissions = {}; selectedFeed.forEach(thread => { const subplebbit = subplebbits.find(s => s && s.address === thread.subplebbitAddress); if (subplebbit && subplebbit.roles) { const role = subplebbit.roles[account?.author.address]?.role; if (role === 'moderator' || role === 'admin' || role === 'owner') { permissions[thread.subplebbitAddress] = true; } else { permissions[thread.subplebbitAddress] = false; } } }); setModeratorPermissions(permissions); }, [account?.author.address, selectedFeed, subplebbits]); const handleOptionClick = () => { setOpenMenuCid(null); }; const handleOutsideClick = useCallback((e) => { if (openMenuCid !== null && !postMenuCatalogRef.current.contains(e.target)) { setOpenMenuCid(null); } }, [openMenuCid, postMenuCatalogRef]); useEffect(() => { if (openMenuCid !== null) { document.addEventListener('click', handleOutsideClick); } else { document.removeEventListener('click', handleOutsideClick); } return () => { document.removeEventListener('click', handleOutsideClick); }; }, [openMenuCid, handleOutsideClick]); useEffect(() => { if (postOnHoverRef.current) { const rect = postOnHoverRef.current.getBoundingClientRect(); setPostOnHoverHeight(rect.height); } }, [outOfViewCid]); const errorString = useMemo(() => { for (const subplebbit of subplebbits) { if (subplebbit?.updatingState !== 'failed') { return } } for (const subplebbit of subplebbits) { if (subplebbit?.error) { return `Failed fetching subplebbit: ${subplebbit?.error.toString().slice(0, 300)}` } } }, [subplebbits]) useEffect(() => { if (errorString) { setNewErrorMessage(errorString); } }, [errorString, setNewErrorMessage]); useEffect(() => { setSelectedFeed(feed.sort((a, b) => b.timestamp - a.timestamp)); }, [feed]); const flattenedRepliesByThread = useMemo(() => { return selectedFeed.reduce((acc, thread) => { const replies = flattenCommentsPages(thread.replies); acc[thread.cid] = replies; return acc; }, {}); }, [selectedFeed]); const allParentCids = useMemo(() => { const allRepliesCids = Object.values(flattenedRepliesByThread).flatMap(replies => replies.map(reply => reply.cid)); const allThreadCids = selectedFeed.map(thread => thread.cid); return [...allThreadCids, ...allRepliesCids]; }, [flattenedRepliesByThread, selectedFeed]); const filter = useMemo(() => ({ parentCids: allParentCids }), [allParentCids]); const { accountComments } = useAccountComments({ filter }); const filteredRepliesByThread = useMemo(() => { const maxRepliesPerThread = 5; const accountRepliesNotYetInCommentReplies = selectedFeed.reduce((acc, thread) => { const replyCids = new Set(flattenedRepliesByThread[thread.cid].map(reply => reply.cid)); acc[thread.cid] = accountComments.filter(accountReply => !replyCids.has(accountReply.cid) && accountReply.parentCid === thread.cid); return acc; }, {}); return selectedFeed.reduce((acc, thread) => { const combinedReplies = [...flattenedRepliesByThread[thread.cid], ...accountRepliesNotYetInCommentReplies[thread.cid]].sort((a, b) => a.timestamp - b.timestamp); acc[thread.cid] = { displayedReplies: combinedReplies.slice(0, maxRepliesPerThread), omittedCount: Math.max(combinedReplies.length - maxRepliesPerThread, 0), }; return acc; }, {}); }, [flattenedRepliesByThread, accountComments, selectedFeed]); const pendingReplyCounts = useMemo(() => { return selectedFeed.reduce((acc, thread) => { const replyCids = new Set(flattenedRepliesByThread[thread.cid].map(reply => reply.cid)); acc[thread.cid] = accountComments.filter(accountReply => !replyCids.has(accountReply.cid) && accountReply.parentCid === thread.cid).length; return acc; }, {}); }, [flattenedRepliesByThread, accountComments, selectedFeed]); const allReplies = useMemo(() => { return selectedFeed.flatMap(thread => filteredRepliesByThread[thread.cid]?.displayedReplies || []); }, [selectedFeed, filteredRepliesByThread]); // let post.jsx access full cid of user-typed short cid useEffect(() => { const newCidTracker = {}; allReplies.forEach((reply) => { newCidTracker[reply.shortCid] = reply.cid; }); setCidTracker(newCidTracker); }, [allReplies]); // 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 tryLoadMore = async () => { try { await loadMore(); } catch (e) { await new Promise(resolve => setTimeout(resolve, 1000)); } }; const onChallengeVerification = (challengeVerification) => { if (challengeVerification.challengeSuccess === true) { 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) => { let challengeAnswers = []; try { challengeAnswers = await getChallengeAnswersFromUser(challenges) } catch (error) { setNewErrorMessage(error.message); console.log(error); } if (challengeAnswers) { await comment.publishChallengeAnswers(challengeAnswers) } }; 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 = useGeneralStore.getState().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: selectedAddress, onChallenge, onChallengeVerification, onError: (error) => { setNewErrorMessage(error.message); console.log(error); }, }); useEffect(() => { if (anonymousMode) { setExecuteAnonMode(true); } }, [anonymousMode, selectedThreadCidRef]); 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, setIsAuthorEdit]); useEffect(() => { let isActive = true; if (publishCommentEditOptions && triggerPublishCommentEdit) { (async () => { await publishCommentEdit(); if (isActive) { setTriggerPublishCommentEdit(false); } })(); } return () => { isActive = false; }; }, [triggerPublishCommentEdit, publishCommentEdit, publishCommentEditOptions]); // desktop navbar board select functionality const handleClickTitle = (title, address) => { setSelectedTitle(title); setSelectedAddress(address); setSelectedFeed(feed.filter(feed => feed.title === title)); }; // 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}`); }; useEffect(() => { const setLastVirtuosoState = () => { virtuosoRef.current?.getState((snapshot) => { if (snapshot?.scrollTop === 0 || snapshot?.ranges?.length) { lastVirtuosoStates['subscriptions'] = snapshot; } }); }; window.addEventListener('scroll', setLastVirtuosoState); return () => window.removeEventListener('scroll', setLastVirtuosoState); }, []); const lastVirtuosoState = lastVirtuosoStates['subscriptions']; return ( <> Subscriptions - 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"} handleClickTitle(subplebbit.title, 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
 
 
<>
<>
Subscriptions
{account?.subscriptions.length < 1 ? (
You haven't subscribed to any board yet.
) : (
You have subscribed to {account?.subscriptions.length} board{account?.subscriptions.length > 1 ? "s" : null}.
)}

Style:  
[ Catalog ]
{subplebbits.state === "succeeded" ? ( null ) : (
{stateString}
)}
Catalog
{ !feed ? ( null ) : ( { const { displayedReplies, omittedCount } = filteredRepliesByThread[thread.cid] || {}; const commentMediaInfo = getCommentMediaInfo(thread); const fallbackImgUrl = "assets/filedeleted-res.gif"; const isModerator = moderatorPermissions[thread.subplebbitAddress]; let displayWidth, displayHeight, displayWidthMobile, displayHeightMobile; if (thread.linkWidth && thread.linkHeight) { let scale = Math.min(1, 250 / Math.max(thread.linkWidth, thread.linkHeight)); displayWidth = `${thread.linkWidth * scale}px`; displayHeight = `${thread.linkHeight * scale}px`; scale = Math.min(1, 100 / Math.max(thread.linkWidth, thread.linkHeight)); displayWidthMobile = `${thread.linkWidth * scale}px`; displayHeightMobile = `${thread.linkHeight * scale}px`; } else { displayWidth = '250px'; displayHeight = '250px'; displayWidthMobile = '100px'; displayHeightMobile = '100px'; } return (

{commentMediaInfo?.url ? (
Link:  { commentMediaInfo?.url.length > 30 ? commentMediaInfo?.url.slice(0, 30) + "(...)" : commentMediaInfo?.url } ({commentMediaInfo?.type === "iframe" ? "video" : commentMediaInfo?.type}) {isThreadThumbnailClicked[index] && commentMediaInfo.type !== "image" ? ( -[ {handleThumbnailClick(index, 'thread')}}>Close ] ) : null}
{commentMediaInfo?.type === 'iframe' && (
{(isThreadThumbnailClicked[index] || !commentMediaInfo.thumbnail) && commentMediaInfo.embedUrl ? (