import React, { useCallback, useEffect, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import { Helmet } from 'react-helmet-async'; import InfiniteScroll from 'react-infinite-scroller'; import { Link, useNavigate} from 'react-router-dom'; import { confirmAlert } from 'react-confirm-alert'; import { Tooltip } from 'react-tooltip'; import { useAccount, useFeed, usePublishCommentEdit, useSubplebbits } from '@plebbit/plebbit-react-hooks'; import { debounce } from 'lodash'; import useGeneralStore from '../../hooks/stores/useGeneralStore'; import { Container, NavBar, Header, Break, PostMenu, BoardForm } from '../styled/views/Board.styled'; import { Threads, PostMenuCatalog } from '../styled/views/Catalog.styled'; import { TopBar, Footer, AuthorDeleteAlert } from '../styled/views/Thread.styled'; import CatalogLoader from '../CatalogLoader'; import EditModal from '../modals/EditModal'; import ImageBanner from '../ImageBanner'; import ModerationModal from '../modals/ModerationModal'; import OfflineIndicator from '../OfflineIndicator'; import SettingsModal from '../modals/SettingsModal'; import getCommentMediaInfo from '../../utils/getCommentMediaInfo'; import handleStyleChange from '../../utils/handleStyleChange'; import useError from '../../hooks/useError'; import useFeedStateString from '../../hooks/useFeedStateString'; import useSuccess from '../../hooks/useSuccess'; import packageJson from '../../../package.json' const {version} = packageJson const SubscriptionsCatalog = () => { const { setCaptchaResponse, setChallengesArray, defaultSubplebbits, editedComment, setIsAuthorDelete, setIsAuthorEdit, setIsCaptchaOpen, isModerationOpen, setIsModerationOpen, isSettingsOpen, setIsSettingsOpen, setModeratingCommentCid, setResolveCaptchaPromise, selectedAddress, setSelectedAddress, selectedStyle, setSelectedThread, setSelectedTitle, } = useGeneralStore(state => state); const threadMenuRefs = useRef({}); const postMenuRef = useRef(null); const postMenuCatalogRef = useRef(null); const account = useAccount(); const navigate = useNavigate(); const [, setNewErrorMessage] = useError(); const [, setNewSuccessMessage] = useSuccess(); const [prevScrollPos, setPrevScrollPos] = useState(0); const [visible, setVisible] = useState(true); const [isHoveringOnThread, setIsHoveringOnThread] = useState(false); const [isEditModalOpen, setIsEditModalOpen] = useState(false); const [originalCommentContent, setOriginalCommentContent] = useState(null); const [triggerPublishCommentEdit, setTriggerPublishCommentEdit] = useState(false); const [deletePost, setDeletePost] = useState(false); const [isImageSearchOpen, setIsImageSearchOpen] = useState(false); const [commentCid, setCommentCid] = useState(null); const [menuPosition, setMenuPosition] = useState({top: 0, left: 0}); const [openMenuCid, setOpenMenuCid] = useState(null); const [moderatorPermissions, setModeratorPermissions] = useState({}); const { feed, hasMore, 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(() => { 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 && !postMenuRef.current.contains(e.target) && !postMenuCatalogRef.current.contains(e.target)) { setOpenMenuCid(null); } }, [openMenuCid, postMenuRef, postMenuCatalogRef]); useEffect(() => { if (openMenuCid !== null) { document.addEventListener('click', handleOutsideClick); } else { document.removeEventListener('click', handleOutsideClick); } return () => { document.removeEventListener('click', handleOutsideClick); }; }, [openMenuCid, handleOutsideClick]); // 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 {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}); } }; const onChallenge = async (challenges, comment) => { let challengeAnswers = []; try { challengeAnswers = await getChallengeAnswersFromUser(challenges) } catch (error) { setNewErrorMessage(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); }, }); 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(() => { if (publishCommentEditOptions && triggerPublishCommentEdit) { (async () => { await publishCommentEdit(); setTriggerPublishCommentEdit(false); })(); } }, [publishCommentEditOptions, triggerPublishCommentEdit, publishCommentEdit]); // 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}`); }; return ( <> Subscriptions - Catalog - plebchan setIsSettingsOpen(false)} /> {setIsModerationOpen(false); setDeletePost(false)}} deletePost={deletePost} /> setIsEditModalOpen(false)} originalCommentContent={originalCommentContent} /> <> [ All  /  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} ))} ] [ alert( 'To create a board, first you have to run a full node.\nYou can run a full node by simply browsing with the plebbit desktop app. After you download it, open it, wait for it loading, then click on "Home" in the top left, then "Create Community".\n\nAfter you create the community, you can go back to plebchan at any time to see it as a board by pasting its address (begins with p/12D3KooW...) in the search bar, which is in the Home.\n\nNote:\n\n- Your community will be online for as long as you leave the app open, because it functions like a server for the community.\n- The longer you leave the app open, the more data you are seeding to the protocol, which helps performance for everybody.\n - All the data in the plebbit protocol is just text, which is extremely lightweight. All media is generated by links, which is text, embedded by the clients.\n\nDownload the plebbit app here: https://github.com/plebbit/plebbit-react/releases\n\nYou can also use a CLI: https://github.com/plebbit/plebbit-cli\n\nRunning boards in the plebchan app is a planned feature.\n\n' ) }>Create Board ] [ setIsSettingsOpen(true)}>Settings ] [ Home ]
Board     alert( 'To create a board, first you have to run a full node.\nYou can run a full node by simply browsing with the plebbit desktop app. After you download it, open it, wait for it loading, then click on "Home" in the top left, then "Create Community".\n\nAfter you create the community, you can go back to plebchan at any time to see it as a board by pasting its address (begins with p/12D3KooW...) in the search bar, which is in the Home.\n\nNote:\n\n- Your community will be online for as long as you leave the app open, because it functions like a server for the community.\n- The longer you leave the app open, the more data you are seeding to the protocol, which helps performance for everybody.\n - All the data in the plebbit protocol is just text, which is extremely lightweight. All media is generated by links, which is text, embedded by the clients.\n\nDownload the plebbit app here: https://github.com/plebbit/plebbit-react/releases\n\nYou can also use a CLI: https://github.com/plebbit/plebbit-cli\n\nRunning boards in the plebchan app is a planned feature.\n\n' ) }>Create Board
setIsSettingsOpen(true)}>Settings   {handleStyleChange({target: {value: "Yotsuba"}}); window.scrollTo(0, 0);}}>Home
 
 
<>
<>
Subscriptions
{feed.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:  
[ Return ]
Return
{feed.length > 0 ? ( null ) : (
{stateString}
)}
{feed.length > 0 ? ( {feed.map((thread, index) => { const commentMediaInfo = getCommentMediaInfo(thread); const fallbackImgUrl = "assets/filedeleted-res.gif"; const isModerator = moderatorPermissions[thread.subplebbitAddress]; return (
{setIsHoveringOnThread(thread.cid)}} onMouseLeave={() => {setIsHoveringOnThread('')}}> {commentMediaInfo?.url ? ( setSelectedThread(thread.cid)}> {commentMediaInfo?.type === "webpage" ? ( thread.thumbnailUrl ? ( {commentMediaInfo.type} { e.target.src = fallbackImgUrl e.target.onerror = null; }} /> ) : null ) : null} {commentMediaInfo?.type === "image" ? ( {commentMediaInfo.type} { e.target.src = fallbackImgUrl e.target.onerror = null;}} /> ) : null} {commentMediaInfo?.type === "video" ? (
)})}
) : ( )}
); } export default SubscriptionsCatalog;