Files
5chan/src/components/Catalog.jsx
T

506 lines
17 KiB
React
Raw Normal View History

2023-02-19 16:48:46 +01:00
import React, { useState, useEffect, useContext } from 'react';
2023-03-06 14:33:31 +01:00
import { Link, useNavigate, useParams, useLocation } from 'react-router-dom';
2023-02-19 16:48:46 +01:00
import { Container, NavBar, Header, Break, PostForm, PostFormLink, PostFormTable } from './styles/Board.styled';
import { TopBar } from './styles/Thread.styled';
import { Threads } from './styles/Catalog.styled';
import { BoardContext } from '../App';
import { useFeed, useAccountsActions } from '@plebbit/plebbit-react-hooks';
import ImageBanner from './ImageBanner';
import InfiniteScroll from 'react-infinite-scroller';
2023-03-08 11:51:57 +01:00
import { useCookies } from 'react-cookie';
2023-02-19 16:48:46 +01:00
2023-03-02 18:19:08 +01:00
2023-02-19 16:48:46 +01:00
const Catalog = ({ setBodyStyle }) => {
const [defaultSubplebbits, setDefaultSubplebbits] = useState([]);
2023-02-26 19:13:46 +01:00
const { selectedTitle, setSelectedTitle, selectedAddress, setSelectedAddress, setSelectedThread, selectedStyle, setSelectedStyle } = useContext(BoardContext);
2023-02-19 16:48:46 +01:00
const [showPostFormLink, setShowPostFormLink] = useState(true);
const [showPostForm, setShowPostForm] = useState(false);
const [name, setName] = useState('');
const [subject, setSubject] = useState('');
const [comment, setComment] = useState('');
const navigate = useNavigate();
2023-03-06 14:33:31 +01:00
const location = useLocation();
2023-02-24 20:57:51 +01:00
const [prevScrollPos, setPrevScrollPos] = useState(0);
const [visible, setVisible] = useState(true);
2023-03-02 18:19:08 +01:00
const { publishComment } = useAccountsActions();
2023-02-19 16:48:46 +01:00
const { feed, hasMore, loadMore } = useFeed([`${selectedAddress}`], 'new');
2023-03-02 18:19:08 +01:00
const { subplebbitAddress } = useParams();
2023-03-08 11:51:57 +01:00
const [cookies, setCookie] = useCookies(['selectedStyle']);
2023-03-02 18:19:08 +01:00
useEffect(() => {
setSelectedAddress(subplebbitAddress);
const selectedSubplebbit = defaultSubplebbits.find((subplebbit) => subplebbit.address === subplebbitAddress);
if (selectedSubplebbit) {
setSelectedTitle(selectedSubplebbit.title);
}
}, [subplebbitAddress, setSelectedAddress, setSelectedTitle, defaultSubplebbits]);
useEffect(() => {
let didCancel = false;
fetch(
"https://raw.githubusercontent.com/plebbit/temporary-default-subplebbits/master/subplebbits.json",
{ cache: "no-cache" }
)
.then((res) => res.json())
.then(res => {
if (!didCancel) {
setDefaultSubplebbits(res);
}
});
return () => {
didCancel = true;
};
}, []);
useEffect(() => {
const handleScroll = () => {
const currentScrollPos = window.pageYOffset;
setVisible(prevScrollPos > currentScrollPos || currentScrollPos < 10);
setPrevScrollPos(currentScrollPos);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, [prevScrollPos, visible]);
2023-03-06 14:33:31 +01:00
// post route handling
useEffect(() => {
const path = location.pathname;
if (path.endsWith('/post')) {
setShowPostFormLink(false);
setShowPostForm(true);
} else {
setShowPostFormLink(true);
setShowPostForm(false);
}
}, [location.pathname]);
2023-03-08 13:13:55 +01:00
// automatic dark mode without interefering with user's selected style
useEffect(() => {
const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const isDarkMode = darkModeMediaQuery.matches;
if (isDarkMode) {
setSelectedStyle('Tomorrow');
setBodyStyle({
background: '#1d1f21 none',
color: '#c5c8c6',
fontFamily: 'Arial, Helvetica, sans-serif'
});
setCookie('selectedStyle', 'Tomorrow', { path: '/', sameSite: 'none', secure: true });
}
const darkModeListener = (e) => {
if (e.matches) {
setSelectedStyle('Tomorrow');
setBodyStyle({
background: '#1d1f21 none',
color: '#c5c8c6',
fontFamily: 'Arial, Helvetica, sans-serif'
});
setCookie('selectedStyle', 'Tomorrow', { path: '/', sameSite: 'none', secure: true });
}
};
darkModeMediaQuery.addEventListener('change', darkModeListener);
return () => {
darkModeMediaQuery.removeEventListener('change', darkModeListener);
};
}, []);
2023-03-02 18:19:08 +01:00
2023-02-19 16:48:46 +01:00
const tryLoadMore = async () => {
try {loadMore()}
catch (e)
{await new Promise(resolve => setTimeout(resolve, 1000))}
}
const onChallengeVerification = (challengeVerification) => {
if (challengeVerification.challengeSuccess === true) {
console.log('challenge success', {publishedCid: challengeVerification.publication.cid})
}
else if (challengeVerification.challengeSuccess === false) {
console.error('challenge failed', {reason: challengeVerification.reason, errors: challengeVerification.errors});
alert("Error: You seem to have mistyped the CAPTCHA. Please try again.");
}
}
2023-03-02 18:19:08 +01:00
2023-02-19 16:48:46 +01:00
const onChallenge = async (challenges, comment) => {
let challengeAnswers = [];
try {
challengeAnswers = await getChallengeAnswersFromUser(challenges)
}
catch (error) {
console.log(error);
}
if (challengeAnswers) {
await comment.publishChallengeAnswers(challengeAnswers)
}
}
2023-03-02 18:19:08 +01:00
2023-02-19 16:48:46 +01:00
const onError = (error) => console.error(error)
2023-03-02 18:19:08 +01:00
2023-02-19 16:48:46 +01:00
const getChallengeAnswersFromUser = async (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 = () => {
const inputEl = document.getElementById('t-resp');
const cntEl = document.getElementById('t-cnt');
cntEl.appendChild(challengeImg);
inputEl.focus();
const handleKeyDown = (event) => {
if (event.key === 'Enter') {
const challengeResponse = inputEl.value;
inputEl.value = '';
if (cntEl.contains(challengeImg)) {
cntEl.removeChild(challengeImg);
}
document.removeEventListener('keydown', handleKeyDown);
resolve(challengeResponse);
}
};
document.addEventListener('keydown', handleKeyDown);
};
challengeImg.onerror = () => {
reject(new Error('Could not load challenge image'));
};
});
};
2023-02-24 20:57:51 +01:00
2023-02-19 16:48:46 +01:00
const handleVoidClick = () => {}
2023-03-02 18:19:08 +01:00
2023-02-27 15:32:16 +01:00
const handleClickTitle = (title, address) => {
2023-02-19 16:48:46 +01:00
setSelectedTitle(title);
setSelectedAddress(address);
};
2023-03-02 18:19:08 +01:00
2023-02-27 18:16:47 +01:00
const handleSelectChange = (event) => {
const selected = event.target.value;
const selectedTitle = defaultSubplebbits.find((subplebbit) => subplebbit.address === selected).title;
setSelectedTitle(selectedTitle);
setSelectedAddress(selected);
navigate(`/${selected}`);
}
2023-03-02 18:19:08 +01:00
2023-02-19 16:48:46 +01:00
const handleClickHelp = () => {
alert("- The CAPTCHA loads after you click \"Post\" \n- The CAPTCHA is case-sensitive. \n- Make sure to not block any cookies set by plebchan.");
};
2023-03-02 18:19:08 +01:00
2023-02-19 16:48:46 +01:00
const handleClickForm = () => {
setShowPostFormLink(false);
setShowPostForm(true);
2023-03-02 21:51:06 +01:00
navigate(`/${selectedAddress}/catalog/post`);
2023-02-19 16:48:46 +01:00
};
2023-03-02 18:19:08 +01:00
const handleClickThread = (thread) => {
setSelectedThread(thread);
}
2023-03-02 18:19:08 +01:00
2023-02-19 16:48:46 +01:00
const handlePublishComment = async () => {
// Event.preventDefault();
try {
const pendingComment = await publishComment({
content: comment,
title: subject,
subplebbitAddress: selectedAddress,
onChallengeVerification,
onChallenge,
onError,
});
console.log(`Comment pending with index: ${pendingComment.index}`);
setName('');
setSubject('');
setComment('');
} catch (error) {
console.error(error);
}
};
const handleStyleChange = (event) => {
switch (event.target.value) {
case "Yotsuba":
setBodyStyle({
background: "#ffe url(/assets/fade.png) top repeat-x",
color: "maroon",
fontFamily: "Arial, Helvetica, sans-serif"
});
setSelectedStyle("Yotsuba");
2023-03-08 11:51:57 +01:00
setCookie("selectedStyle", "Yotsuba", { path: "/" });
2023-02-19 16:48:46 +01:00
break;
2023-03-08 12:49:44 +01:00
case "Yotsuba-B":
2023-02-19 16:48:46 +01:00
setBodyStyle({
background: "#eef2ff url(/assets/fade-blue.png) top center repeat-x",
color: "#000",
fontFamily: "Arial, Helvetica, sans-serif"
});
2023-03-08 12:49:44 +01:00
setSelectedStyle("Yotsuba-B");
setCookie("selectedStyle", "Yotsuba-B", { path: "/", sameSite: 'none', secure: true });
2023-02-19 16:48:46 +01:00
break;
case "Futaba":
setBodyStyle({
background: "#ffe",
color: "maroon",
fontFamily: "times new roman, serif"
});
setSelectedStyle("Futaba");
2023-03-08 11:51:57 +01:00
setCookie("selectedStyle", "Futaba", { path: "/", sameSite: 'none', secure: true });
2023-02-19 16:48:46 +01:00
break;
case "Burichan":
setBodyStyle({
background: "#eef2ff",
color: "#000",
fontFamily: "times new roman, serif"
});
setSelectedStyle("Burichan");
2023-03-08 11:51:57 +01:00
setCookie("selectedStyle", "Burichan", { path: "/", sameSite: 'none', secure: true });
2023-02-19 16:48:46 +01:00
break;
case "Tomorrow":
setBodyStyle({
background: "#1d1f21 none",
color: "#c5c8c6",
fontFamily: "Arial, Helvetica, sans-serif"
});
setSelectedStyle("Tomorrow");
2023-03-08 11:51:57 +01:00
setCookie("selectedStyle", "Tomorrow", { path: "/", sameSite: 'none', secure: true });
2023-02-19 16:48:46 +01:00
break;
case "Photon":
setBodyStyle({
background: "#eee none",
color: "#333",
fontFamily: "Arial, Helvetica, sans-serif"
});
setSelectedStyle("Photon");
2023-03-08 11:51:57 +01:00
setCookie("selectedStyle", "Photon", { path: "/", sameSite: 'none', secure: true });
2023-02-19 16:48:46 +01:00
break;
default:
setBodyStyle({
background: "#ffe url(/assets/fade.png) top repeat-x",
color: "maroon",
fontFamily: "Arial, Helvetica, sans-serif"
});
setSelectedStyle("Yotsuba");
2023-03-08 11:51:57 +01:00
setCookie("selectedStyle", "Yotsuba", { path: "/", sameSite: 'none', secure: true });
2023-02-19 16:48:46 +01:00
}
}
2023-03-08 11:51:57 +01:00
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
2023-03-08 12:49:44 +01:00
if (parts.length === 2) return parts.pop().split(";").shift();
2023-03-08 11:51:57 +01:00
}
2023-03-08 12:49:44 +01:00
2023-03-08 11:51:57 +01:00
useEffect(() => {
const style = getCookie("selectedStyle");
if (style) {
2023-03-08 12:49:44 +01:00
handleStyleChange({ target: { value: style } });
2023-03-08 11:51:57 +01:00
}
2023-03-08 12:49:44 +01:00
}, []);
2023-03-08 11:51:57 +01:00
2023-03-02 18:19:08 +01:00
2023-02-19 16:48:46 +01:00
return (
<Container>
<NavBar selectedStyle={selectedStyle}>
<>
{defaultSubplebbits.map(subplebbit => (
2023-03-11 12:32:42 +01:00
<span className="boardList" key={`span-${subplebbit.address}`}>
2023-02-19 16:48:46 +01:00
[
2023-03-11 12:32:42 +01:00
<Link to={`/${subplebbit.address}`} key={`a-${subplebbit.address}`} onClick={() => handleClickTitle(subplebbit.title, subplebbit.address)}
2023-02-19 22:08:18 +01:00
>{subplebbit.title}</Link>
2023-02-19 16:48:46 +01:00
]&nbsp;
</span>
))}
2023-02-23 16:45:29 +01:00
<span className="nav">
[
2023-03-07 13:54:14 +01:00
<Link to="" onClick={handleVoidClick}>Settings</Link>
2023-02-23 16:45:29 +01:00
]
[
<Link to="/" onClick={() => handleStyleChange({target: {value: "Yotsuba"}}
)}>Home</Link>
]
2023-02-19 16:48:46 +01:00
</span>
2023-02-24 20:57:51 +01:00
<div id="board-nav-mobile" style={{ top: visible ? 0 : '-23px' }}>
2023-02-23 16:45:29 +01:00
<div className="board-select">
<strong>Board</strong>
&nbsp;
2023-02-27 18:16:47 +01:00
<select id="board-select-mobile" value={selectedAddress} onChange={handleSelectChange}>
2023-02-23 16:45:29 +01:00
{defaultSubplebbits.map(subplebbit => (
2023-03-11 12:32:42 +01:00
<option key={`option-${subplebbit.address}`} value={subplebbit.address}
2023-02-27 18:16:47 +01:00
>{subplebbit.title}</option>
2023-02-27 15:32:16 +01:00
))}
2023-02-23 16:45:29 +01:00
</select>
</div>
<div className="page-jump">
2023-03-07 13:54:14 +01:00
<Link to="" onClick={handleVoidClick}>Settings</Link>
2023-02-23 16:45:29 +01:00
&nbsp;
<Link to="/" onClick={() => handleStyleChange({target: {value: "Yotsuba"}}
)}>Home</Link>
</div>
</div>
<div id="separator-mobile">&nbsp;</div>
<div id="separator-mobile">&nbsp;</div>
2023-02-19 16:48:46 +01:00
</>
</NavBar>
<Header selectedStyle={selectedStyle}>
<>
<div className="banner">
<ImageBanner />
</div>
<>
<div className="board-title">{selectedTitle}</div>
<div className="board-address">p/{selectedAddress}</div>
</>
</>
</Header>
<Break selectedStyle={selectedStyle} />
<PostForm selectedStyle={selectedStyle}>
2023-02-24 18:13:02 +01:00
<PostFormLink id="post-form-link" showPostFormLink={showPostFormLink} selectedStyle={selectedStyle} >
<div id="post-form-link-desktop">
[
<a onClick={handleClickForm} onMouseOver={(event) => event.target.style.cursor='pointer'}>Start a New Thread</a>
]
</div>
<div id="post-form-link-mobile">
<span className="btn-wrap">
<a onClick={handleClickForm} onMouseOver={(event) => event.target.style.cursor='pointer'}>Start a New Thread</a>
</span>
</div>
2023-02-19 16:48:46 +01:00
</PostFormLink>
<PostFormTable id="post-form" showPostForm={showPostForm} selectedStyle={selectedStyle} className="post-form">
<tbody>
<tr data-type="Name">
<td id="td-name">Name</td>
<td>
<input name="name" type="text" tabIndex={1} placeholder="Anonymous" value={name} onChange={(event) => setName(event.target.value)} />
</td>
</tr>
<tr data-type="Subject">
<td>Subject</td>
<td>
<input name="sub" type="text" tabIndex={3} value={subject} onChange={(event) => setSubject(event.target.value)} />
<input id="post-button" type="submit" value="Post" tabIndex={6} onClick={handlePublishComment} />
</td>
</tr>
<tr data-type="Comment">
<td>Comment</td>
<td>
<textarea name="com" cols="48" rows="4" tabIndex={4} wrap="soft" value={comment} onChange={(event) => setComment(event.target.value)}></textarea>
</td>
</tr>
<tr id="captchaFormPart">
<td>Verification</td>
<td colSpan={2}>
<div id="t-root">
<input id="t-resp" name="t-response" placeholder="Type the CAPTCHA here and hit return" autoComplete='off' type="text" />
<button id="t-help" type="button" onClick={handleClickHelp} data-tip="Help" tabIndex={-1}>?</button>
<div id="t-cnt">
</div>
</div>
</td>
</tr>
<tr data-type="File">
<td>Embed File</td>
<td>
<input name="embed" type="text" tabIndex={7} placeholder="Paste link" />
</td>
</tr>
<tr></tr>
</tbody>
</PostFormTable>
</PostForm>
<TopBar selectedStyle={selectedStyle}>
<hr />
<span className="style-changer">
Style:
 
<select id="style-selector" onChange={handleStyleChange} value={selectedStyle}>
<option value="Yotsuba">Yotsuba</option>
2023-03-08 12:49:44 +01:00
<option value="Yotsuba-B">Yotsuba B</option>
2023-02-19 16:48:46 +01:00
<option value="Futaba">Futaba</option>
<option value="Burichan">Burichan</option>
<option value="Tomorrow">Tomorrow</option>
<option value="Photon">Photon</option>
</select>
</span>
2023-02-24 18:13:02 +01:00
<div className="return-button" id="return-button-desktop">
2023-02-19 16:48:46 +01:00
[
2023-03-02 21:51:06 +01:00
<Link to={`/${selectedAddress}`}>Return</Link>
2023-02-19 16:48:46 +01:00
]
2023-02-24 18:13:02 +01:00
</div>
<div id="return-button-mobile">
<span className="btn-wrap-catalog btn-wrap">
2023-03-02 21:51:06 +01:00
<Link to={`/${selectedAddress}`}>Return</Link>
2023-02-24 18:13:02 +01:00
</span>
</div>
2023-02-19 16:48:46 +01:00
<hr />
</TopBar>
<Threads selectedStyle={selectedStyle}>
<InfiniteScroll
pageStart={0}
loadMore={tryLoadMore}
hasMore={hasMore}
2023-03-11 12:32:42 +01:00
loader={<div key={`loader-${feed.length}`}>Loading...</div>}
2023-02-19 16:48:46 +01:00
>
{feed.map(thread => {
return (
2023-03-11 12:32:42 +01:00
<div key={`thread-${thread.cid}`} className="thread">
<Link key={`a-${thread.cid}`} to={`/${selectedAddress}/thread/${thread.cid}`} onClick={() => handleClickThread(thread.cid)}>
<img key={`img-${thread.cid}`} alt="" src="/assets/plebchan-psycho.png" />
</Link>
2023-03-11 12:32:42 +01:00
<div key={`ti-${thread.cid}`} className="thread-icons" >
<span key={`si-${thread.cid}`} className="thread-icon sticky-icon" title="Sticky"></span>
2023-02-19 16:48:46 +01:00
</div>
2023-03-11 12:32:42 +01:00
<div key={`meta-${thread.cid}`} className="meta" title="(R)eplies / (I)mage Replies" >
2023-02-19 16:48:46 +01:00
R:
2023-03-11 12:32:42 +01:00
<b key={`b-${thread.cid}`}>{thread.replyCount}</b>
2023-02-19 16:48:46 +01:00
</div>
2023-03-11 12:32:42 +01:00
<div key={`t-${thread.cid}`} className="teaser">
<b key={`b2-${thread.cid}`}>{thread.title ? `${thread.title}` : null}</b>
{thread.content ? `: ${thread.content}` : null}
2023-02-19 16:48:46 +01:00
</div>
</div>
)})}
</InfiniteScroll>
</Threads>
</Container>
);
}
export default Catalog;