This commit is contained in:
plebeius.eth
2023-09-16 21:40:23 +02:00
parent d963c90d26
commit 020e509b71
39 changed files with 1970 additions and 2035 deletions
+4 -11
View File
@@ -1,9 +1,8 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from 'react';
import { useSubplebbit } from "@plebbit/plebbit-react-hooks"; import { useSubplebbit } from '@plebbit/plebbit-react-hooks';
const BoardAvatar = ({ address }) => { const BoardAvatar = ({ address }) => {
const [avatarUrl, setAvatarUrl] = useState("assets/plebchan.png"); const [avatarUrl, setAvatarUrl] = useState('assets/plebchan.png');
const subplebbit = useSubplebbit({ subplebbitAddress: address }); const subplebbit = useSubplebbit({ subplebbitAddress: address });
useEffect(() => { useEffect(() => {
@@ -12,13 +11,7 @@ const BoardAvatar = ({ address }) => {
} }
}, [subplebbit.suggested?.avatarUrl, subplebbit]); }, [subplebbit.suggested?.avatarUrl, subplebbit]);
return ( return <img className='board-avatar' alt='board avatar' src={avatarUrl} />;
<img
className="board-avatar"
alt="board avatar"
src={avatarUrl}
/>
);
}; };
export default BoardAvatar; export default BoardAvatar;
+47 -64
View File
@@ -1,20 +1,13 @@
import React, { useEffect, useRef, useState } from "react"; import React, { useEffect, useRef, useState } from 'react';
import { Link } from "react-router-dom"; import { Link } from 'react-router-dom';
import { usePublishSubplebbitEdit } from "@plebbit/plebbit-react-hooks"; import { usePublishSubplebbitEdit } from '@plebbit/plebbit-react-hooks';
import { StyledModal } from './styled/modals/ModerationModal.styled'; import { StyledModal } from './styled/modals/ModerationModal.styled';
import useError from "../hooks/useError"; import useError from '../hooks/useError';
import useSuccess from "../hooks/useSuccess"; import useSuccess from '../hooks/useSuccess';
import useGeneralStore from '../hooks/stores/useGeneralStore'; import useGeneralStore from '../hooks/stores/useGeneralStore';
const BoardSettings = ({ subplebbit }) => { const BoardSettings = ({ subplebbit }) => {
const { const { setCaptchaResponse, setChallengesArray, setIsCaptchaOpen, setResolveCaptchaPromise, selectedAddress, selectedStyle } = useGeneralStore((state) => state);
setCaptchaResponse,
setChallengesArray,
setIsCaptchaOpen,
setResolveCaptchaPromise,
selectedAddress,
selectedStyle,
} = useGeneralStore(state => state);
const allowedSettings = { const allowedSettings = {
address: subplebbit.address, address: subplebbit.address,
@@ -68,7 +61,6 @@ const BoardSettings = ({ subplebbit }) => {
const [, setNewErrorMessage] = useError(); const [, setNewErrorMessage] = useError();
const [, setNewSuccessMessage] = useSuccess(); const [, setNewSuccessMessage] = useSuccess();
const getDifferences = (oldObj, newObj) => { const getDifferences = (oldObj, newObj) => {
let differences = {}; let differences = {};
@@ -92,7 +84,6 @@ const BoardSettings = ({ subplebbit }) => {
return differences; return differences;
}; };
const isInitialMount = useRef(true); const isInitialMount = useRef(true);
useEffect(() => { useEffect(() => {
@@ -102,17 +93,14 @@ const BoardSettings = ({ subplebbit }) => {
} }
}, [subplebbit]); }, [subplebbit]);
function validateSettings(updatedSettings, allowedSettings) { function validateSettings(updatedSettings, allowedSettings) {
for (let key in updatedSettings) { for (let key in updatedSettings) {
if (!allowedSettings.hasOwnProperty(key) && !initialSettings.hasOwnProperty(key)) { if (!allowedSettings.hasOwnProperty(key) && !initialSettings.hasOwnProperty(key)) {
throw new Error(`Unexpected setting: ${key}`); throw new Error(`Unexpected setting: ${key}`);
} }
if (typeof updatedSettings[key] === 'object' && updatedSettings[key] !== null if (typeof updatedSettings[key] === 'object' && updatedSettings[key] !== null && !Array.isArray(updatedSettings[key])) {
&& !Array.isArray(updatedSettings[key])) { if (typeof allowedSettings[key] !== 'object' || allowedSettings[key] === null || Array.isArray(allowedSettings[key])) {
if (typeof allowedSettings[key] !== 'object' || allowedSettings[key] === null
|| Array.isArray(allowedSettings[key])) {
throw new Error(`Expected ${key} to be an object in allowedSettings`); throw new Error(`Expected ${key} to be an object in allowedSettings`);
} }
validateSettings(updatedSettings[key], allowedSettings[key]); validateSettings(updatedSettings[key], allowedSettings[key]);
@@ -120,32 +108,30 @@ const BoardSettings = ({ subplebbit }) => {
} }
} }
const onChallenge = async (challenges, subplebbitEdit) => { const onChallenge = async (challenges, subplebbitEdit) => {
let challengeAnswers = []; let challengeAnswers = [];
try { try {
challengeAnswers = await getChallengeAnswersFromUser(challenges) challengeAnswers = await getChallengeAnswersFromUser(challenges);
} } catch (error) {
catch (error) { setNewErrorMessage(error.message);
setNewErrorMessage(error.message); console.log(error); console.log(error);
} }
if (challengeAnswers) { if (challengeAnswers) {
await subplebbitEdit.publishChallengeAnswers(challengeAnswers) await subplebbitEdit.publishChallengeAnswers(challengeAnswers);
} }
}; };
const onChallengeVerification = (challengeVerification) => { const onChallengeVerification = (challengeVerification) => {
if (challengeVerification.challengeSuccess === true) { if (challengeVerification.challengeSuccess === true) {
setNewSuccessMessage('Challenge Success'); console.log('challenge success', challengeVerification); setNewSuccessMessage('Challenge Success');
console.log('challenge success', challengeVerification);
} else if (challengeVerification.challengeSuccess === false) { } else if (challengeVerification.challengeSuccess === false) {
setNewErrorMessage(`Challenge Failed, reason: ${challengeVerification.reason}. Errors: ${challengeVerification.errors}`); setNewErrorMessage(`Challenge Failed, reason: ${challengeVerification.reason}. Errors: ${challengeVerification.errors}`);
console.log('challenge failed', challengeVerification); console.log('challenge failed', challengeVerification);
} }
}; };
const getChallengeAnswersFromUser = async (challenges) => { const getChallengeAnswersFromUser = async (challenges) => {
setChallengesArray(challenges); setChallengesArray(challenges);
@@ -180,20 +166,18 @@ const BoardSettings = ({ subplebbit }) => {
}); });
}; };
const [editSubplebbitOptions, setEditSubplebbitOptions] = useState({ const [editSubplebbitOptions, setEditSubplebbitOptions] = useState({
subplebbitAddress: selectedAddress, subplebbitAddress: selectedAddress,
onChallenge, onChallenge,
onChallengeVerification, onChallengeVerification,
onError: (error) => { onError: (error) => {
setNewErrorMessage(error.message); console.log(error); setNewErrorMessage(error.message);
} console.log(error);
},
}); });
const { publishSubplebbitEdit } = usePublishSubplebbitEdit(editSubplebbitOptions); const { publishSubplebbitEdit } = usePublishSubplebbitEdit(editSubplebbitOptions);
useEffect(() => { useEffect(() => {
let isActive = true; let isActive = true;
if (editSubplebbitOptions && triggerPublilshSubplebbitEdit) { if (editSubplebbitOptions && triggerPublilshSubplebbitEdit) {
@@ -210,20 +194,19 @@ const BoardSettings = ({ subplebbit }) => {
}; };
}, [editSubplebbitOptions, publishSubplebbitEdit, triggerPublilshSubplebbitEdit]); }, [editSubplebbitOptions, publishSubplebbitEdit, triggerPublilshSubplebbitEdit]);
const handleSaveChanges = async () => { const handleSaveChanges = async () => {
try { try {
const updatedSettings = JSON.parse(boardSettingsJson); const updatedSettings = JSON.parse(boardSettingsJson);
validateSettings(updatedSettings, allowedSettings); validateSettings(updatedSettings, allowedSettings);
const changes = getDifferences(initialSettings, updatedSettings); const changes = getDifferences(initialSettings, updatedSettings);
if (Object.keys(changes).length > 0) { if (Object.keys(changes).length > 0) {
setEditSubplebbitOptions(prevOptions => ({ setEditSubplebbitOptions((prevOptions) => ({
...prevOptions, ...prevOptions,
...changes ...changes,
})); }));
setTriggerPublishCommentEdit(true); setTriggerPublishCommentEdit(true);
} else { } else {
setNewErrorMessage("No changes detected"); setNewErrorMessage('No changes detected');
} }
} catch (error) { } catch (error) {
setNewErrorMessage(`Error saving changes: ${error}`); setNewErrorMessage(`Error saving changes: ${error}`);
@@ -231,12 +214,10 @@ const BoardSettings = ({ subplebbit }) => {
} }
}; };
const handleResetChanges = () => { const handleResetChanges = () => {
setBoardSettingsJson(JSON.stringify(initialSettings, null, 2)); setBoardSettingsJson(JSON.stringify(initialSettings, null, 2));
}; };
function generateSettingsList(settingsObj, parentKey = '') { function generateSettingsList(settingsObj, parentKey = '') {
let result = []; let result = [];
@@ -256,10 +237,8 @@ const BoardSettings = ({ subplebbit }) => {
return result; return result;
} }
const possibleSettingsList = generateSettingsList(initialSettings); const possibleSettingsList = generateSettingsList(initialSettings);
const handleCloseModal = () => { const handleCloseModal = () => {
setIsModalOpen(false); setIsModalOpen(false);
setBoardSettingsJson(JSON.stringify(initialSettings, null, 2)); setBoardSettingsJson(JSON.stringify(initialSettings, null, 2));
@@ -270,54 +249,58 @@ const BoardSettings = ({ subplebbit }) => {
setBoardSettingsJson(JSON.stringify(generateSettingsFromSubplebbit(subplebbit), null, 2)); setBoardSettingsJson(JSON.stringify(generateSettingsFromSubplebbit(subplebbit), null, 2));
}; };
return ( return (
<> <>
<StyledModal <StyledModal
isOpen={isModalOpen} isOpen={isModalOpen}
onRequestClose={handleCloseModal} onRequestClose={handleCloseModal}
contentLabel="Board Settings" contentLabel='Board Settings'
style={{ overlay: { backgroundColor: "rgba(0,0,0,.25)" }}} style={{ overlay: { backgroundColor: 'rgba(0,0,0,.25)' } }}
selectedStyle={selectedStyle} selectedStyle={selectedStyle}
> >
<div className="panel-board"> <div className='panel-board'>
<div className="panel-header"> <div className='panel-header'>
Board Settings Board Settings
<Link to="" onClick={handleCloseModal}> <Link to='' onClick={handleCloseModal}>
<span className="icon" title="close" /> <span className='icon' title='close' />
</Link> </Link>
</div> </div>
<div className="settings-info"> <div className='settings-info'>
<div> <div>
<strong>Allowed settings: </strong> <strong>Allowed settings: </strong>
<span> <span>{`{ ${possibleSettingsList.join(', ')} }`}</span>
{`{ ${possibleSettingsList.join(', ')} }`}
</span>
</div> </div>
<strong style={{marginTop: '10px', display: 'inline-block'}}>API docs: </strong><a style={{color: 'inherit'}} href="https://github.com/plebbit/plebbit-js#readme" target="_blank" rel="noreferrer">https://github.com/plebbit/plebbit-js#readme</a> <strong style={{ marginTop: '10px', display: 'inline-block' }}>API docs: </strong>
<a style={{ color: 'inherit' }} href='https://github.com/plebbit/plebbit-js#readme' target='_blank' rel='noreferrer'>
https://github.com/plebbit/plebbit-js#readme
</a>
</div> </div>
<textarea <textarea
value={boardSettingsJson} value={boardSettingsJson}
onChange={e => setBoardSettingsJson(e.target.value)} onChange={(e) => setBoardSettingsJson(e.target.value)}
className="board-settings" className='board-settings'
autoComplete="off" autoComplete='off'
autoCorrect="off" autoCorrect='off'
spellCheck="false" spellCheck='false'
/> />
<div className="button-group"> <div className='button-group'>
<button id="reset-board-settings" onClick={handleResetChanges}>Reset</button> <button id='reset-board-settings' onClick={handleResetChanges}>
<button id="save-board-settings" onClick={handleSaveChanges}>Save Changes</button> Reset
</button>
<button id='save-board-settings' onClick={handleSaveChanges}>
Save Changes
</button>
</div> </div>
</div> </div>
</StyledModal> </StyledModal>
 [  [
<span id="subscribe" style={{ cursor: 'pointer' }}> <span id='subscribe' style={{ cursor: 'pointer' }}>
<span <span
onClick={() => { onClick={() => {
window.electron && window.electron.isElectron window.electron && window.electron.isElectron
? openModal() ? openModal()
: alert( : alert(
'To edit this board you must be using the plebchan desktop app, which is a plebbit full node that seeds the board automatically.\n\nDownload plebchan here:\n\nhttps://github.com/plebbit/plebchan/releases/latest' 'To edit this board you must be using the plebchan desktop app, which is a plebbit full node that seeds the board automatically.\n\nDownload plebchan here:\n\nhttps://github.com/plebbit/plebchan/releases/latest',
); );
}} }}
> >
+26 -14
View File
@@ -1,13 +1,11 @@
import React, { useState } from "react"; import React, { useState } from 'react';
import { useSubplebbit, useSubplebbitStats } from "@plebbit/plebbit-react-hooks/dist"; import { useSubplebbit, useSubplebbitStats } from '@plebbit/plebbit-react-hooks/dist';
import { BoardStatsContainer } from "./styled/BoardStats.styled"; import { BoardStatsContainer } from './styled/BoardStats.styled';
import { Break } from "./styled/views/Board.styled"; import { Break } from './styled/views/Board.styled';
import useGeneralStore from '../hooks/stores/useGeneralStore'; import useGeneralStore from '../hooks/stores/useGeneralStore';
const BoardStats = ({ subplebbitAddress }) => { const BoardStats = ({ subplebbitAddress }) => {
const { selectedStyle } = useGeneralStore(state => state); const { selectedStyle } = useGeneralStore((state) => state);
const stats = useSubplebbitStats({ subplebbitAddress }); const stats = useSubplebbitStats({ subplebbitAddress });
const [showStats, setShowStats] = useState(true); const [showStats, setShowStats] = useState(true);
const subplebbit = useSubplebbit({ subplebbitAddress }); const subplebbit = useSubplebbit({ subplebbitAddress });
@@ -24,22 +22,36 @@ const BoardStats = ({ subplebbitAddress }) => {
return month + '/' + day + '/' + year; return month + '/' + day + '/' + year;
}; };
const pluralize = (count, singular, plural) => count === 1 ? singular : plural; const pluralize = (count, singular, plural) => (count === 1 ? singular : plural);
return ( return (
<BoardStatsContainer selectedStyle={selectedStyle}> <BoardStatsContainer selectedStyle={selectedStyle}>
<Break selectedStyle={selectedStyle} style={{ width: '468px' }} /> <Break selectedStyle={selectedStyle} style={{ width: '468px' }} />
<table id="blotter"> <table id='blotter'>
{showStats && ( {showStats && (
<tbody id="blotter-msgs"> <tbody id='blotter-msgs'>
<tr> <tr>
<td>In the past hour, <span id="stat-number">{stats.hourActiveUserCount}</span> {pluralize(stats.hourActiveUserCount, 'user', 'users')} made <span id="stat-number">{stats.hourPostCount}</span> {pluralize(stats.hourPostCount, 'post', 'posts')} / in the past day, <span id="stat-number">{stats.dayActiveUserCount}</span> {pluralize(stats.dayActiveUserCount, 'user', 'users')} made <span id="stat-number">{stats.dayPostCount}</span> {pluralize(stats.dayPostCount, 'post', 'posts')}</td> <td>
In the past hour, <span id='stat-number'>{stats.hourActiveUserCount}</span> {pluralize(stats.hourActiveUserCount, 'user', 'users')} made{' '}
<span id='stat-number'>{stats.hourPostCount}</span> {pluralize(stats.hourPostCount, 'post', 'posts')} / in the past day,{' '}
<span id='stat-number'>{stats.dayActiveUserCount}</span> {pluralize(stats.dayActiveUserCount, 'user', 'users')} made{' '}
<span id='stat-number'>{stats.dayPostCount}</span> {pluralize(stats.dayPostCount, 'post', 'posts')}
</td>
</tr> </tr>
<tr> <tr>
<td>In the past week, <span id="stat-number">{stats.weekActiveUserCount}</span> {pluralize(stats.weekActiveUserCount, 'user', 'users')} made <span id="stat-number">{stats.weekPostCount}</span> {pluralize(stats.weekPostCount, 'post', 'posts')} / in the past month, <span id="stat-number">{stats.monthActiveUserCount}</span> {pluralize(stats.monthActiveUserCount, 'user', 'users')} made <span id="stat-number">{stats.monthPostCount}</span> {pluralize(stats.monthPostCount, 'post', 'posts')}</td> <td>
In the past week, <span id='stat-number'>{stats.weekActiveUserCount}</span> {pluralize(stats.weekActiveUserCount, 'user', 'users')} made{' '}
<span id='stat-number'>{stats.weekPostCount}</span> {pluralize(stats.weekPostCount, 'post', 'posts')} / in the past month,{' '}
<span id='stat-number'>{stats.monthActiveUserCount}</span> {pluralize(stats.monthActiveUserCount, 'user', 'users')} made{' '}
<span id='stat-number'>{stats.monthPostCount}</span> {pluralize(stats.monthPostCount, 'post', 'posts')}
</td>
</tr> </tr>
<tr> <tr>
<td>{unixToMMDDYYYY(subplebbit.createdAt)} board created / since then, <span id="stat-number">{stats.allActiveUserCount}</span> {pluralize(stats.allActiveUserCount, 'user', 'users')} have made <span id="stat-number">{stats.allPostCount}</span> {pluralize(stats.allPostCount, 'post', 'posts')}</td> <td>
{unixToMMDDYYYY(subplebbit.createdAt)} board created / since then, <span id='stat-number'>{stats.allActiveUserCount}</span>{' '}
{pluralize(stats.allActiveUserCount, 'user', 'users')} have made <span id='stat-number'>{stats.allPostCount}</span>{' '}
{pluralize(stats.allPostCount, 'post', 'posts')}
</td>
</tr> </tr>
</tbody> </tbody>
)} )}
@@ -47,7 +59,7 @@ const BoardStats = ({ subplebbitAddress }) => {
<tr> <tr>
<td colSpan={2}> <td colSpan={2}>
[ [
<span id="stat-number" className="hide-button" onClick={handleToggleStats}> <span id='stat-number' className='hide-button' onClick={handleToggleStats}>
{showStats ? 'Hide' : 'Show Stats'} {showStats ? 'Hide' : 'Show Stats'}
</span> </span>
] ]
+4 -6
View File
@@ -2,7 +2,6 @@ import React from 'react';
import ContentLoader from 'react-content-loader'; import ContentLoader from 'react-content-loader';
import useGeneralStore from '../hooks/stores/useGeneralStore'; import useGeneralStore from '../hooks/stores/useGeneralStore';
const SingleRectLoader = () => { const SingleRectLoader = () => {
const selectedStyle = useGeneralStore((state) => state.selectedStyle); const selectedStyle = useGeneralStore((state) => state.selectedStyle);
const backgroundColor = selectedStyle === 'Tomorrow' ? '#333' : '#f3f3f3'; const backgroundColor = selectedStyle === 'Tomorrow' ? '#333' : '#f3f3f3';
@@ -13,7 +12,7 @@ const SingleRectLoader = () => {
speed={2} speed={2}
width={150} width={150}
height={215} height={215}
viewBox="0 0 150 215" viewBox='0 0 150 215'
backgroundColor={backgroundColor} backgroundColor={backgroundColor}
foregroundColor={foregroundColor} foregroundColor={foregroundColor}
style={{ style={{
@@ -23,14 +22,13 @@ const SingleRectLoader = () => {
marginBottom: '30px', marginBottom: '30px',
}} }}
> >
<rect x={0} y={0} width="150" height="150" /> <rect x={0} y={0} width='150' height='150' />
<rect x={0} y={170} width="150" height="18" /> <rect x={0} y={170} width='150' height='18' />
<rect x={0} y={195} width="80" height="20" /> <rect x={0} y={195} width='80' height='20' />
</ContentLoader> </ContentLoader>
); );
}; };
const CatalogLoader = () => { const CatalogLoader = () => {
return ( return (
<div <div
+19 -23
View File
@@ -1,62 +1,58 @@
import React, { useState } from "react"; import React, { useState } from 'react';
import { useComment, useEditedComment } from "@plebbit/plebbit-react-hooks"; import { useComment, useEditedComment } from '@plebbit/plebbit-react-hooks';
import { Link } from "react-router-dom"; import { Link } from 'react-router-dom';
import OriginalCommentModal from "./modals/OriginalCommentModal"; import OriginalCommentModal from './modals/OriginalCommentModal';
import getDate from "../utils/getDate"; import getDate from '../utils/getDate';
import useGeneralStore from "../hooks/stores/useGeneralStore"; import useGeneralStore from '../hooks/stores/useGeneralStore';
const EditLabel = ({ commentCid, className }) => { const EditLabel = ({ commentCid, className }) => {
const { editedComments, setEditedComments } = useGeneralStore(state => state); const { editedComments, setEditedComments } = useGeneralStore((state) => state);
const [isOriginalCommentModalOpen, setIsOriginalCommentModalOpen] = useState(false); const [isOriginalCommentModalOpen, setIsOriginalCommentModalOpen] = useState(false);
const comment = useComment({ commentCid }); const comment = useComment({ commentCid });
const timestamp = getDate(comment.edit?.timestamp); const timestamp = getDate(comment.edit?.timestamp);
const { state: editedCommentState, editedComment } = useEditedComment({ comment }); const { state: editedCommentState, editedComment } = useEditedComment({ comment });
if (editedCommentState === 'pending' && !(commentCid in editedComments)) { if (editedCommentState === 'pending' && !(commentCid in editedComments)) {
setEditedComments({...editedComments, [commentCid]: editedComment}) setEditedComments({ ...editedComments, [commentCid]: editedComment });
} }
const conditionsCheck = () => { const conditionsCheck = () => {
let conditions = []; let conditions = [];
if (editedComment?.removed && !comment.removed) { if (editedComment?.removed && !comment.removed) {
conditions.push("removal"); conditions.push('removal');
} }
if (editedComment?.edit && !comment.edit) { if (editedComment?.edit && !comment.edit) {
conditions.push("edit"); conditions.push('edit');
} }
if (editedComment?.locked && !comment.locked) { if (editedComment?.locked && !comment.locked) {
conditions.push("lock"); conditions.push('lock');
} }
if (editedComment?.pinned && !comment.pinned) { if (editedComment?.pinned && !comment.pinned) {
conditions.push("sticky"); conditions.push('sticky');
} }
return conditions.length > 0 ? conditions.join(', ') : null; return conditions.length > 0 ? conditions.join(', ') : null;
}; };
const conditionsString = conditionsCheck(); const conditionsString = conditionsCheck();
return ( return (
<> <>
<OriginalCommentModal <OriginalCommentModal isOpen={isOriginalCommentModalOpen} closeModal={() => setIsOriginalCommentModalOpen(false)} comment={comment} />
isOpen={isOriginalCommentModalOpen}
closeModal={() => setIsOriginalCommentModalOpen(false)}
comment={comment}/>
{comment.edit && ( {comment.edit && (
<> <>
<br /> <br />
<span className={className}> <span className={className}>
(Edited at {timestamp}, <Link className="ttl-link" onClick={ (Edited at {timestamp},{' '}
() => setIsOriginalCommentModalOpen(true) <Link className='ttl-link' onClick={() => setIsOriginalCommentModalOpen(true)}>
}>show original</Link>) show original
</Link>
)
</span> </span>
</> </>
)} )}
{((editedCommentState === 'pending' || editedCommentState === 'failed') && conditionsString) ? ( {(editedCommentState === 'pending' || editedCommentState === 'failed') && conditionsString ? (
<> <>
<br /> <br />
<span className={className}> <span className={className}>
+93 -68
View File
@@ -39,35 +39,37 @@ const YoutubeEmbed = ({parsedUrl}) => {
let youtubeId; let youtubeId;
if (parsedUrl.host.endsWith('youtu.be')) { if (parsedUrl.host.endsWith('youtu.be')) {
youtubeId = parsedUrl.pathname.replaceAll('/', ''); youtubeId = parsedUrl.pathname.replaceAll('/', '');
} } else {
else {
youtubeId = parsedUrl.searchParams.get('v'); youtubeId = parsedUrl.searchParams.get('v');
} }
return <iframe return (
<iframe
className='enlarged youtube-embed' className='enlarged youtube-embed'
height="100%" height='100%'
width="100%" width='100%'
frameborder="0" frameborder='0'
credentialless credentialless
referrerpolicy='no-referrer' referrerpolicy='no-referrer'
allow="accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share" allow='accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share'
allowfullscreen allowfullscreen
title={parsedUrl.href} title={parsedUrl.href}
src={`https://www.youtube-nocookie.com/embed/${youtubeId}`} src={`https://www.youtube-nocookie.com/embed/${youtubeId}`}
/>; />
);
}; };
const twitterHosts = new Set(['twitter.com', 'www.twitter.com', 'x.com', 'www.x.com']); const twitterHosts = new Set(['twitter.com', 'www.twitter.com', 'x.com', 'www.x.com']);
const TwitterEmbed = ({ parsedUrl }) => { const TwitterEmbed = ({ parsedUrl }) => {
return <iframe return (
<iframe
className='enlarged twitter-embed' className='enlarged twitter-embed'
height="100%" height='100%'
width="100%" width='100%'
frameborder="0" frameborder='0'
credentialless credentialless
referrerpolicy='no-referrer' referrerpolicy='no-referrer'
allow="accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share" allow='accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share'
title={parsedUrl.href} title={parsedUrl.href}
srcdoc={` srcdoc={`
<blockquote class="twitter-tweet" data-theme="dark"> <blockquote class="twitter-tweet" data-theme="dark">
@@ -75,20 +77,22 @@ const TwitterEmbed = ({parsedUrl}) => {
</blockquote> </blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
`} `}
/>; />
);
}; };
const redditHosts = new Set(['reddit.com', 'www.reddit.com', 'old.reddit.com']); const redditHosts = new Set(['reddit.com', 'www.reddit.com', 'old.reddit.com']);
const RedditEmbed = ({ parsedUrl }) => { const RedditEmbed = ({ parsedUrl }) => {
return <iframe return (
<iframe
className='enlarged reddit-embed' className='enlarged reddit-embed'
height="100%" height='100%'
width="100%" width='100%'
frameborder="0" frameborder='0'
credentialless credentialless
referrerpolicy='no-referrer' referrerpolicy='no-referrer'
allow="accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share" allow='accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share'
title={parsedUrl.href} title={parsedUrl.href}
srcdoc={` srcdoc={`
<style> <style>
@@ -102,7 +106,8 @@ const RedditEmbed = ({parsedUrl}) => {
</blockquote> </blockquote>
<script async src="https://embed.reddit.com/widgets.js" charset="UTF-8"></script> <script async src="https://embed.reddit.com/widgets.js" charset="UTF-8"></script>
`} `}
/>; />
);
}; };
const twitchHosts = new Set(['twitch.tv', 'www.twitch.tv']); const twitchHosts = new Set(['twitch.tv', 'www.twitch.tv']);
@@ -112,37 +117,39 @@ const TwitchEmbed = ({parsedUrl}) => {
if (parsedUrl.pathname.startsWith('/videos/')) { if (parsedUrl.pathname.startsWith('/videos/')) {
const videoId = parsedUrl.pathname.replace('/videos/', ''); const videoId = parsedUrl.pathname.replace('/videos/', '');
iframeUrl = `https://player.twitch.tv/?video=${videoId}&parent=${window.location.hostname}`; iframeUrl = `https://player.twitch.tv/?video=${videoId}&parent=${window.location.hostname}`;
} } else {
else {
const channel = parsedUrl.pathname.replaceAll('/', ''); const channel = parsedUrl.pathname.replaceAll('/', '');
iframeUrl = `https://player.twitch.tv/?channel=${channel}&parent=${window.location.hostname}`; iframeUrl = `https://player.twitch.tv/?channel=${channel}&parent=${window.location.hostname}`;
} }
return <iframe return (
<iframe
className='enlarged twitch-embed' className='enlarged twitch-embed'
height="100%" height='100%'
width="100%" width='100%'
frameborder="0" frameborder='0'
credentialless credentialless
referrerpolicy='no-referrer' referrerpolicy='no-referrer'
allow="accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share" allow='accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share'
allowfullscreen allowfullscreen
title={parsedUrl.href} title={parsedUrl.href}
src={iframeUrl} src={iframeUrl}
/>; />
);
}; };
const tiktokHosts = new Set(['tiktok.com', 'www.tiktok.com']); const tiktokHosts = new Set(['tiktok.com', 'www.tiktok.com']);
const TiktokEmbed = ({ parsedUrl }) => { const TiktokEmbed = ({ parsedUrl }) => {
const videoId = parsedUrl.pathname.replace(/.+\/video\//, '').replaceAll('/', ''); const videoId = parsedUrl.pathname.replace(/.+\/video\//, '').replaceAll('/', '');
return <iframe return (
<iframe
className='enlarged tiktok-embed' className='enlarged tiktok-embed'
height="100%" height='100%'
width="100%" width='100%'
frameborder="0" frameborder='0'
credentialless credentialless
referrerpolicy='no-referrer' referrerpolicy='no-referrer'
allow="accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share" allow='accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share'
title={parsedUrl.href} title={parsedUrl.href}
srcdoc={` srcdoc={`
<blockquote class="tiktok-embed" data-video-id="${videoId}"> <blockquote class="tiktok-embed" data-video-id="${videoId}">
@@ -150,7 +157,8 @@ const TiktokEmbed = ({parsedUrl}) => {
</blockquote> </blockquote>
<script async src="https://www.tiktok.com/embed.js"></script> <script async src="https://www.tiktok.com/embed.js"></script>
`} `}
/>; />
);
}; };
const instagramHosts = new Set(['instagram.com', 'www.instagram.com']); const instagramHosts = new Set(['instagram.com', 'www.instagram.com']);
@@ -158,14 +166,15 @@ const instagramHosts = new Set(['instagram.com', 'www.instagram.com']);
const InstagramEmbed = ({ parsedUrl }) => { const InstagramEmbed = ({ parsedUrl }) => {
const pathNames = parsedUrl.pathname.replace(/\/+$/, '').split('/'); const pathNames = parsedUrl.pathname.replace(/\/+$/, '').split('/');
const id = pathNames[pathNames.length - 1]; const id = pathNames[pathNames.length - 1];
return <iframe return (
<iframe
className='enlarged instagram-embed' className='enlarged instagram-embed'
height="100%" height='100%'
width="100%" width='100%'
frameborder="0" frameborder='0'
credentialless credentialless
referrerpolicy='no-referrer' referrerpolicy='no-referrer'
allow="accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share" allow='accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share'
title={parsedUrl.href} title={parsedUrl.href}
srcdoc={` srcdoc={`
<blockquote class="instagram-media"> <blockquote class="instagram-media">
@@ -173,85 +182,101 @@ const InstagramEmbed = ({parsedUrl}) => {
</blockquote> </blockquote>
<script async src="//www.instagram.com/embed.js"></script> <script async src="//www.instagram.com/embed.js"></script>
`} `}
/>; />
);
}; };
const odyseeHosts = new Set(['odysee.com', 'www.odysee.com']); const odyseeHosts = new Set(['odysee.com', 'www.odysee.com']);
const OdyseeEmbed = ({ parsedUrl }) => { const OdyseeEmbed = ({ parsedUrl }) => {
const iframeUrl = `https://odysee.com/$/embed${parsedUrl.pathname}`; const iframeUrl = `https://odysee.com/$/embed${parsedUrl.pathname}`;
return <iframe return (
<iframe
className='enlarged odysee-embed' className='enlarged odysee-embed'
height="100%" height='100%'
width="100%" width='100%'
frameborder="0" frameborder='0'
credentialless credentialless
referrerpolicy='no-referrer' referrerpolicy='no-referrer'
allow="accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share" allow='accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share'
allowfullscreen allowfullscreen
title={parsedUrl.href} title={parsedUrl.href}
src={iframeUrl} src={iframeUrl}
/>; />
);
}; };
const bitchuteHosts = new Set(['bitchute.com', 'www.bitchute.com']); const bitchuteHosts = new Set(['bitchute.com', 'www.bitchute.com']);
const BitchuteEmbed = ({ parsedUrl }) => { const BitchuteEmbed = ({ parsedUrl }) => {
const videoId = parsedUrl.pathname.replace(/\/video\//, '').replaceAll('/', ''); const videoId = parsedUrl.pathname.replace(/\/video\//, '').replaceAll('/', '');
return <iframe return (
<iframe
className='enlarged bitchute-embed' className='enlarged bitchute-embed'
height="100%" height='100%'
width="100%" width='100%'
frameborder="0" frameborder='0'
credentialless credentialless
referrerpolicy='no-referrer' referrerpolicy='no-referrer'
allow="accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share" allow='accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share'
allowfullscreen allowfullscreen
title={parsedUrl.href} title={parsedUrl.href}
src={`https://www.bitchute.com/embed/${videoId}/`} src={`https://www.bitchute.com/embed/${videoId}/`}
/>; />
);
}; };
const streamableHosts = new Set(['streamable.com', 'www.streamable.com']); const streamableHosts = new Set(['streamable.com', 'www.streamable.com']);
const StreamableEmbed = ({ parsedUrl }) => { const StreamableEmbed = ({ parsedUrl }) => {
const videoId = parsedUrl.pathname.replaceAll('/', ''); const videoId = parsedUrl.pathname.replaceAll('/', '');
return <iframe return (
<iframe
className='enlarged streamable-embed' className='enlarged streamable-embed'
height="100%" height='100%'
width="100%" width='100%'
frameborder="0" frameborder='0'
credentialless credentialless
referrerpolicy='no-referrer' referrerpolicy='no-referrer'
allow="accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share" allow='accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share'
allowfullscreen allowfullscreen
title={parsedUrl.href} title={parsedUrl.href}
src={`https://streamable.com/e/${videoId}`} src={`https://streamable.com/e/${videoId}`}
/>; />
);
}; };
const spotifyHosts = new Set(['spotify.com', 'www.spotify.com', 'open.spotify.com']); const spotifyHosts = new Set(['spotify.com', 'www.spotify.com', 'open.spotify.com']);
const SpotifyEmbed = ({ parsedUrl }) => { const SpotifyEmbed = ({ parsedUrl }) => {
const iframeUrl = `https://open.spotify.com/embed${parsedUrl.pathname}?theme=0` const iframeUrl = `https://open.spotify.com/embed${parsedUrl.pathname}?theme=0`;
return <iframe return (
<iframe
className='enlarged spotify-embed' className='enlarged spotify-embed'
height="100%" height='100%'
width="100%" width='100%'
frameborder="0" frameborder='0'
credentialless credentialless
referrerpolicy='no-referrer' referrerpolicy='no-referrer'
allow="accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share" allow='accelerometer; encrypted-media; gyroscope; picture-in-picture; web-share'
allowfullscreen allowfullscreen
title={parsedUrl.href} title={parsedUrl.href}
src={iframeUrl} src={iframeUrl}
/>; />
);
}; };
const canEmbedHosts = new Set([ const canEmbedHosts = new Set([
...youtubeHosts, ...twitterHosts, ...redditHosts, ...twitchHosts, ...youtubeHosts,
...tiktokHosts, ...instagramHosts, ...odyseeHosts, ...bitchuteHosts, ...twitterHosts,
...streamableHosts, ...spotifyHosts ...redditHosts,
...twitchHosts,
...tiktokHosts,
...instagramHosts,
...odyseeHosts,
...bitchuteHosts,
...streamableHosts,
...spotifyHosts,
]); ]);
export const canEmbed = (parsedUrl) => canEmbedHosts.has(parsedUrl.host); export const canEmbed = (parsedUrl) => canEmbedHosts.has(parsedUrl.host);
+4 -10
View File
@@ -1,11 +1,11 @@
import React, { useEffect } from "react"; import React, { useEffect } from 'react';
import { Link } from "react-router-dom"; import { Link } from 'react-router-dom';
const ForwardRefLink = React.forwardRef((props, ref) => { const ForwardRefLink = React.forwardRef((props, ref) => {
const { children, setRefAndCid, onMouseOver, onMouseLeave, onClick, ...otherProps } = props; const { children, setRefAndCid, onMouseOver, onMouseLeave, onClick, ...otherProps } = props;
const handleClick = (event) => { const handleClick = (event) => {
if (otherProps.to === "#void") { if (otherProps.to === '#void') {
event.preventDefault(); event.preventDefault();
} }
if (onClick) { if (onClick) {
@@ -20,13 +20,7 @@ const ForwardRefLink = React.forwardRef((props, ref) => {
}, [ref, setRefAndCid]); }, [ref, setRefAndCid]);
return ( return (
<Link <Link ref={ref} {...otherProps} onMouseOver={onMouseOver} onMouseLeave={onMouseLeave} onClick={handleClick}>
ref={ref}
{...otherProps}
onMouseOver={onMouseOver}
onMouseLeave={onMouseLeave}
onClick={handleClick}
>
{children} {children}
</Link> </Link>
); );
+1 -5
View File
@@ -31,11 +31,7 @@ const ImageBanner = () => {
}; };
}, [parentRoute]); }, [parentRoute]);
return ( return <>{currentImage && <img id='banner-img' src={`${process.env.PUBLIC_URL}/assets/banners/banner-${currentImage}.jpg`} alt='banner' />}</>;
<>
{currentImage && <img id="banner-img" src={`${process.env.PUBLIC_URL}/assets/banners/banner-${currentImage}.jpg`} alt="banner" />}
</>
);
}; };
export function importAll(r) { export function importAll(r) {
+7 -7
View File
@@ -1,5 +1,5 @@
import React from "react"; import React from 'react';
import { useSubplebbit } from "@plebbit/plebbit-react-hooks"; import { useSubplebbit } from '@plebbit/plebbit-react-hooks';
const OfflineIndicator = ({ address, className, tooltipPlace }) => { const OfflineIndicator = ({ address, className, tooltipPlace }) => {
const subplebbit = useSubplebbit({ subplebbitAddress: address }); const subplebbit = useSubplebbit({ subplebbitAddress: address });
@@ -9,13 +9,13 @@ const OfflineIndicator = ({ address, className, tooltipPlace }) => {
<> <>
{!isOnline && ( {!isOnline && (
<> <>
{" "} {' '}
<img <img
className={className} className={className}
alt="offline" alt='offline'
src="assets/offline.png" src='assets/offline.png'
data-tooltip-id="tooltip" data-tooltip-id='tooltip'
data-tooltip-content="Offline" data-tooltip-content='Offline'
data-tooltip-place={tooltipPlace} data-tooltip-place={tooltipPlace}
style={{ imageRendering: 'pixelated' }} style={{ imageRendering: 'pixelated' }}
/> />
+8 -18
View File
@@ -1,28 +1,18 @@
import React from "react"; import React from 'react';
import { useAccountComment } from "@plebbit/plebbit-react-hooks"; import { useAccountComment } from '@plebbit/plebbit-react-hooks';
const PendingLabel = ({ commentIndex }) => { const PendingLabel = ({ commentIndex }) => {
const comment = useAccountComment({ commentIndex: commentIndex }); const comment = useAccountComment({ commentIndex: commentIndex });
if (commentIndex === undefined) return null; if (commentIndex === undefined) return null;
return ( return comment.cid ? (
comment.cid ? (
<span>{comment.cid.slice(2, 14)}</span> <span>{comment.cid.slice(2, 14)}</span>
) : ( ) : comment.state === 'pending' ? (
comment.state === "pending" ? ( <span style={{ color: 'red', fontWeight: '700' }}>Pending</span>
<span style={{color: 'red', fontWeight: '700'}}> ) : comment.state === 'failed' ? (
Pending <span style={{ color: 'red', fontWeight: '700' }}>Failed</span>
</span> ) : null;
) : (
comment.state === "failed" ? (
<span style={{color: 'red', fontWeight: '700'}}>
Failed
</span>
) : null
)
)
);
}; };
export default PendingLabel; export default PendingLabel;
+17 -19
View File
@@ -4,19 +4,20 @@ import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
import breaks from 'remark-breaks'; import breaks from 'remark-breaks';
import ForwardRefLink from './ForwardRefLink'; import ForwardRefLink from './ForwardRefLink';
const Post = ({ content, postQuoteOnClick, postQuoteOnOver, postQuoteOnLeave, postQuoteRef }) => { const Post = ({ content, postQuoteOnClick, postQuoteOnOver, postQuoteOnLeave, postQuoteRef }) => {
const doubleNewlineContent = content?.replace(/\n/g, '&nbsp;\n\n'); const doubleNewlineContent = content?.replace(/\n/g, '&nbsp;\n\n');
const customSchema = useMemo(() => ({ const customSchema = useMemo(
() => ({
...defaultSchema, ...defaultSchema,
tagNames: [...defaultSchema.tagNames, 'div'], tagNames: [...defaultSchema.tagNames, 'div'],
attributes: { attributes: {
...defaultSchema.attributes, ...defaultSchema.attributes,
div: ['className'], div: ['className'],
}, },
}), []); }),
[],
);
const blockquoteToGreentext = () => (tree) => { const blockquoteToGreentext = () => (tree) => {
tree.children.forEach((node) => { tree.children.forEach((node) => {
@@ -41,12 +42,11 @@ const Post = ({ content, postQuoteOnClick, postQuoteOnOver, postQuoteOnLeave, po
}); });
}; };
const createQuotelink = (children, postQuoteOnClick, postQuoteOnOver, postQuoteOnLeave, postQuoteRef) => { const createQuotelink = (children, postQuoteOnClick, postQuoteOnOver, postQuoteOnLeave, postQuoteRef) => {
const patternC = "(c/[A-Za-z0-9]{46}|c/[A-Za-z0-9]{12})"; const patternC = '(c/[A-Za-z0-9]{46}|c/[A-Za-z0-9]{12})';
const patternP = "(p/([A-Za-z0-9]{52}|[A-Za-z0-9-.]*\\.eth))"; const patternP = '(p/([A-Za-z0-9]{52}|[A-Za-z0-9-.]*\\.eth))';
const patternU = "(u/([A-Za-z0-9]{52}|[A-Za-z0-9-.]*\\.eth))"; const patternU = '(u/([A-Za-z0-9]{52}|[A-Za-z0-9-.]*\\.eth))';
const patternPC = "(p/([A-Za-z0-9]{52}|[A-Za-z0-9-.]*\\.eth)/c/[A-Za-z0-9]{46})"; const patternPC = '(p/([A-Za-z0-9]{52}|[A-Za-z0-9-.]*\\.eth)/c/[A-Za-z0-9]{46})';
const regex = new RegExp(`${patternC}|${patternPC}|${patternU}|${patternP}`, 'g'); const regex = new RegExp(`${patternC}|${patternPC}|${patternU}|${patternP}`, 'g');
@@ -71,10 +71,10 @@ const Post = ({ content, postQuoteOnClick, postQuoteOnOver, postQuoteOnLeave, po
const linkRef = React.createRef(); const linkRef = React.createRef();
let linkTo = () => {}; let linkTo = () => {};
const linkTarget = matchedText.startsWith('u/') ? "_blank" : "_self"; const linkTarget = matchedText.startsWith('u/') ? '_blank' : '_self';
if (matchedText.startsWith('u/')) { if (matchedText.startsWith('u/')) {
linkTo = "#void"; linkTo = '#void';
} else if (matchedText.startsWith('p/') || matchedText.startsWith('p/')) { } else if (matchedText.startsWith('p/') || matchedText.startsWith('p/')) {
linkTo = `/${matchedText}`; linkTo = `/${matchedText}`;
} }
@@ -82,7 +82,7 @@ const Post = ({ content, postQuoteOnClick, postQuoteOnOver, postQuoteOnLeave, po
parts.push( parts.push(
<ForwardRefLink <ForwardRefLink
key={`link-${i}-${matchedText}`} key={`link-${i}-${matchedText}`}
className="quotelink" className='quotelink'
to={linkTo} to={linkTo}
target={linkTarget} target={linkTarget}
ref={linkRef} ref={linkRef}
@@ -91,7 +91,9 @@ const Post = ({ content, postQuoteOnClick, postQuoteOnOver, postQuoteOnLeave, po
postQuoteRef(cid, ref); postQuoteRef(cid, ref);
} }
}} }}
onClick={() => {postQuoteOnClick(cid)}} onClick={() => {
postQuoteOnClick(cid);
}}
onMouseOver={() => { onMouseOver={() => {
postQuoteOnOver(cid); postQuoteOnOver(cid);
}} }}
@@ -100,7 +102,7 @@ const Post = ({ content, postQuoteOnClick, postQuoteOnOver, postQuoteOnLeave, po
}} }}
> >
{matchedText} {matchedText}
</ForwardRefLink> </ForwardRefLink>,
); );
lastIndex = index + matchedText.length; lastIndex = index + matchedText.length;
@@ -114,8 +116,6 @@ const Post = ({ content, postQuoteOnClick, postQuoteOnOver, postQuoteOnLeave, po
}); });
}; };
return ( return (
<ReactMarkdown <ReactMarkdown
children={doubleNewlineContent} children={doubleNewlineContent}
@@ -126,9 +126,7 @@ const Post = ({ content, postQuoteOnClick, postQuoteOnOver, postQuoteOnLeave, po
video: ({ src }) => <span>{src}</span>, video: ({ src }) => <span>{src}</span>,
source: ({ src }) => <span>{src}</span>, source: ({ src }) => <span>{src}</span>,
gif: ({ src }) => <span>{src}</span>, gif: ({ src }) => <span>{src}</span>,
p: ({ children }) => <div className='custom-paragraph'> p: ({ children }) => <div className='custom-paragraph'>{createQuotelink(children, postQuoteOnClick, postQuoteOnOver, postQuoteOnLeave, postQuoteRef)}</div>,
{createQuotelink(children, postQuoteOnClick, postQuoteOnOver, postQuoteOnLeave, postQuoteRef)}
</div>,
}} }}
/> />
); );
+4 -9
View File
@@ -9,15 +9,10 @@ const SinglePostLoader = () => {
return ( return (
<div style={{ paddingLeft: '30px', paddingRight: '30px', marginBottom: '50px', marginTop: '30px' }}> <div style={{ paddingLeft: '30px', paddingRight: '30px', marginBottom: '50px', marginTop: '30px' }}>
<ContentLoader <ContentLoader width='100%' height={15 * 3 + 30} backgroundColor={backgroundColor} foregroundColor={foregroundColor}>
width="100%" <rect x='0' y='8' width='100%' height='15' />
height={15 * 3 + 30} <rect x='0' y='30' width='100%' height='15' />
backgroundColor={backgroundColor} <rect x='0' y='52' width='100%' height='15' />
foregroundColor={foregroundColor}
>
<rect x="0" y="8" width="100%" height="15" />
<rect x="0" y="30" width="100%" height="15" />
<rect x="0" y="52" width="100%" height="15" />
</ContentLoader> </ContentLoader>
</div> </div>
); );
+168 -193
View File
@@ -1,28 +1,30 @@
import React, { Fragment } from "react"; import React, { Fragment } from 'react';
import { Link } from "react-router-dom"; import { Link } from 'react-router-dom';
import { useAccount, useComment } from "@plebbit/plebbit-react-hooks"; import { useAccount, useComment } from '@plebbit/plebbit-react-hooks';
import getDate from "../utils/getDate"; import getDate from '../utils/getDate';
import getCommentMediaInfo from "../utils/getCommentMediaInfo"; import getCommentMediaInfo from '../utils/getCommentMediaInfo';
import findShortParentCid from "../utils/findShortParentCid"; import findShortParentCid from '../utils/findShortParentCid';
import Post from "./Post"; import Post from './Post';
import EditLabel from "./EditLabel"; import EditLabel from './EditLabel';
import useStateString from "../hooks/useStateString"; import useStateString from '../hooks/useStateString';
import { BoardForm, Container } from "./styled/views/Board.styled"; import { BoardForm, Container } from './styled/views/Board.styled';
import useGeneralStore from "../hooks/stores/useGeneralStore"; import useGeneralStore from '../hooks/stores/useGeneralStore';
const PostOnHover = ({ cid, feed }) => { const PostOnHover = ({ cid, feed }) => {
const selectedStyle = useGeneralStore(state => state.selectedStyle); const selectedStyle = useGeneralStore((state) => state.selectedStyle);
const account = useAccount(); const account = useAccount();
const reply = useComment({ commentCid: cid }); const reply = useComment({ commentCid: cid });
const replyMediaInfo = getCommentMediaInfo(reply); const replyMediaInfo = getCommentMediaInfo(reply);
const fallbackImgUrl = "assets/filedeleted-res.gif"; const fallbackImgUrl = 'assets/filedeleted-res.gif';
const selectedFeed = feed; const selectedFeed = feed;
const thread = useComment({ commentCid: reply.parentCid }); const thread = useComment({ commentCid: reply.parentCid });
const shortParentCid = findShortParentCid(reply.parentCid, selectedFeed); const shortParentCid = findShortParentCid(reply.parentCid, selectedFeed);
const stateString = useStateString(reply); const stateString = useStateString(reply);
return ( return (
<Container selectedStyle={selectedStyle} style={{ <Container
selectedStyle={selectedStyle}
style={{
margin: '0', margin: '0',
padding: '0', padding: '0',
whiteSpace: 'normal', whiteSpace: 'normal',
@@ -31,284 +33,257 @@ const PostOnHover = ({ cid, feed }) => {
wordWrap: 'break-word', wordWrap: 'break-word',
wordBreak: 'break-all', wordBreak: 'break-all',
boxSizing: 'border-box', boxSizing: 'border-box',
}}> }}
>
<BoardForm selectedStyle={selectedStyle} style={{ margin: '0', padding: '0' }}> <BoardForm selectedStyle={selectedStyle} style={{ margin: '0', padding: '0' }}>
<div className="board" style={{margin: '0', padding: '0'}}> <div className='board' style={{ margin: '0', padding: '0' }}>
<div className="thread" style={{margin: '0', padding: '0'}}> <div className='thread' style={{ margin: '0', padding: '0' }}>
{reply.state === 'succeeded' ? ( {reply.state === 'succeeded' ? (
<div className="reply-container"> <div className='reply-container'>
<div className="post-reply post-reply-desktop"> <div className='post-reply post-reply-desktop'>
<div className="post-info"> <div className='post-info'>
<span className="nameblock"> <span className='nameblock'>
{reply.author?.displayName {reply.author?.displayName ? (
? reply.author?.displayName.length > 20 reply.author?.displayName.length > 20 ? (
? <Fragment > <Fragment>
<span className="name" <span className='name' data-tooltip-id='tooltip' data-tooltip-content={reply.author?.displayName} data-tooltip-place='top'>
data-tooltip-id="tooltip" {reply.author?.displayName.slice(0, 20) + ' (...)'}
data-tooltip-content={reply.author?.displayName}
data-tooltip-place="top">
{reply.author?.displayName.slice(0, 20) + " (...)"}
</span> </span>
</Fragment> </Fragment>
: <span className="name">
{reply.author?.displayName}</span>
: <span className="name">
Anonymous</span>}
&nbsp;
<span className="poster-address address-desktop"
id="reply-button" style={{cursor: "pointer"}}
>
(u/
{reply.author?.shortAddress ?
(
<span >
{reply.author?.shortAddress}
</span>
) : ( ) : (
<span > <span className='name'>{reply.author?.displayName}</span>
{account?.author?.shortAddress}
</span>
)
}
) )
) : (
<span className='name'>Anonymous</span>
)}
&nbsp;
<span className='poster-address address-desktop' id='reply-button' style={{ cursor: 'pointer' }}>
(u/
{reply.author?.shortAddress ? <span>{reply.author?.shortAddress}</span> : <span>{account?.author?.shortAddress}</span>})
</span> </span>
</span> </span>
&nbsp; &nbsp;
<span className="date-time" data-utc="data">{getDate(reply.timestamp)}</span> <span className='date-time' data-utc='data'>
{getDate(reply.timestamp)}
</span>
&nbsp; &nbsp;
<span className="post-number post-number-desktop"> <span className='post-number post-number-desktop'>
<span>c/</span> <span>c/</span>
<Link to={() => {}} id="reply-button" <Link to={() => {}} id='reply-button' title='Reply to this post'>
title="Reply to this post">{reply.shortCid}</Link> {reply.shortCid}
</span>&nbsp; </Link>
<div id="backlink-id" className="backlink"> </span>
&nbsp;
<div id='backlink-id' className='backlink'>
{reply.replies?.pages?.topAll.comments {reply.replies?.pages?.topAll.comments
.sort((a, b) => a.timestamp - b.timestamp) .sort((a, b) => a.timestamp - b.timestamp)
.map((reply, index) => ( .map((reply, index) => (
<div key={`div-${index}`} style={{ display: 'inline-block' }}> <div key={`div-${index}`} style={{ display: 'inline-block' }}>
<Link key={`link-${index}`} to={() => {}} <Link key={`link-${index}`} to={() => {}} className='quote-link'>
className="quote-link"> c/{reply.shortCid}
c/{reply.shortCid}</Link> </Link>
&nbsp; &nbsp;
</div> </div>
)) ))}
}
</div> </div>
</div> </div>
{replyMediaInfo?.url ? ( {replyMediaInfo?.url ? (
<div className="file" <div className='file' style={{ marginBottom: '5px' }}>
style={{marginBottom: "5px"}}> <div className='reply-file-text'>
<div className="reply-file-text">
Link:&nbsp; Link:&nbsp;
<a href={replyMediaInfo.url} target="_blank" <a href={replyMediaInfo.url} target='_blank' rel='noopener noreferrer'>
rel="noopener noreferrer">{ {replyMediaInfo?.url.length > 30 ? replyMediaInfo?.url.slice(0, 30) + '(...)' : replyMediaInfo?.url}
replyMediaInfo?.url.length > 30 ? </a>
replyMediaInfo?.url.slice(0, 30) + "(...)" : &nbsp;({replyMediaInfo?.type})
replyMediaInfo?.url
}</a>&nbsp;({replyMediaInfo?.type})
</div> </div>
{replyMediaInfo?.type === "webpage" ? ( {replyMediaInfo?.type === 'webpage' ? (
<div className="img-container"> <div className='img-container'>
<span className="file-thumb-reply"> <span className='file-thumb-reply'>
{reply.thumbnailUrl ? ( {reply.thumbnailUrl ? (
<img <img
src={replyMediaInfo.thumbnail} alt={replyMediaInfo.type} src={replyMediaInfo.thumbnail}
style={{cursor: "pointer"}} alt={replyMediaInfo.type}
onError={(e) => e.target.src = fallbackImgUrl} /> style={{ cursor: 'pointer' }}
onError={(e) => (e.target.src = fallbackImgUrl)}
/>
) : null} ) : null}
</span> </span>
</div> </div>
) : null} ) : null}
{replyMediaInfo?.type === "image" ? ( {replyMediaInfo?.type === 'image' ? (
<div className="img-container"> <div className='img-container'>
<span className="file-thumb-reply"> <span className='file-thumb-reply'>
<img <img src={replyMediaInfo.url} alt={replyMediaInfo.type} style={{ cursor: 'pointer' }} onError={(e) => (e.target.src = fallbackImgUrl)} />
src={replyMediaInfo.url} alt={replyMediaInfo.type}
style={{cursor: "pointer"}}
onError={(e) => e.target.src = fallbackImgUrl} />
</span> </span>
</div> </div>
) : null} ) : null}
{replyMediaInfo?.type === "video" ? ( {replyMediaInfo?.type === 'video' ? (
<span className="file-thumb-reply"> <span className='file-thumb-reply'>
<video controls <video controls src={replyMediaInfo.url} alt={replyMediaInfo.type} onError={(e) => (e.target.src = fallbackImgUrl)} />
src={replyMediaInfo.url} alt={replyMediaInfo.type}
onError={(e) => e.target.src = fallbackImgUrl} />
</span> </span>
) : null} ) : null}
{replyMediaInfo?.type === "audio" ? ( {replyMediaInfo?.type === 'audio' ? (
<span className="file-thumb-reply"> <span className='file-thumb-reply'>
<audio controls <audio controls src={replyMediaInfo.url} alt={replyMediaInfo.type} onError={(e) => (e.target.src = fallbackImgUrl)} />
src={replyMediaInfo.url} alt={replyMediaInfo.type}
onError={(e) => e.target.src = fallbackImgUrl} />
</span> </span>
) : null} ) : null}
</div> </div>
) : null} ) : null}
{reply.content ? ( {reply.content ? (
reply.content?.length > 500 ? reply.content?.length > 500 ? (
<Fragment> <Fragment>
<blockquote comment={reply} className="post-message"> <blockquote comment={reply} className='post-message'>
{shortParentCid ? ( {shortParentCid ? (
<Link to={() => {}} className="quotelink"> <Link to={() => {}} className='quotelink'>
{`c/${shortParentCid}`}{shortParentCid === thread.shortCid ? " (OP)" : null} {`c/${shortParentCid}`}
{shortParentCid === thread.shortCid ? ' (OP)' : null}
</Link> </Link>
) : null} ) : null}
<Post content={reply.content?.slice(0, 500)} /> <Post content={reply.content?.slice(0, 500)} />
<span className="ttl"> (...) <span className='ttl'>
<br /> <EditLabel {' '}
commentCid={reply.cid} (...)
className="ttl"/><br /> <br /> <EditLabel commentCid={reply.cid} className='ttl' />
Comment too long. Click the link to view.</span> <br />
Comment too long. Click the link to view.
</span>
</blockquote> </blockquote>
</Fragment> </Fragment>
: <blockquote className="post-message"> ) : (
<blockquote className='post-message'>
{shortParentCid ? ( {shortParentCid ? (
<Link to={() => {}} className="quotelink"> <Link to={() => {}} className='quotelink'>
{`c/${shortParentCid}`}{shortParentCid === thread.shortCid ? " (OP)" : null} {`c/${shortParentCid}`}
{shortParentCid === thread.shortCid ? ' (OP)' : null}
</Link> </Link>
) : null} ) : null}
<Post content={reply.content} comment={reply} /> <Post content={reply.content} comment={reply} />
<EditLabel <EditLabel commentCid={reply.cid} className='ttl' />
commentCid={reply.cid} </blockquote>
className="ttl"/> )
</blockquote>) ) : null}
: null}
</div> </div>
</div> </div>
) : ( ) : (
<div className="reply-container"> <div className='reply-container'>
<span className="ellipsis">{stateString}</span> <span className='ellipsis'>{stateString}</span>
</div> </div>
)} )}
</div> </div>
<div className="thread-mobile"> <div className='thread-mobile'>
{reply.state === 'succeeded' ? ( {reply.state === 'succeeded' ? (
<div className="reply-container"> <div className='reply-container'>
<div className="post-reply post-reply-mobile"> <div className='post-reply post-reply-mobile'>
<div className="post-info-mobile"> <div className='post-info-mobile'>
<span className="name-block-mobile"> <span className='name-block-mobile'>
{reply.author?.displayName {reply.author?.displayName ? (
? reply.author?.displayName.length > 20 reply.author?.displayName.length > 20 ? (
? <Fragment> <Fragment>
<span className="name-mobile"> <span className='name-mobile'>{reply.author?.displayName.slice(0, 20) + ' (...)'}</span>
{reply.author?.displayName.slice(0, 20) + " (...)"}
</span>
</Fragment> </Fragment>
: <span className="name-mobile">
{reply.author?.displayName}</span>
: <span className="name-mobile">
Anonymous</span>}
&nbsp;
<span className="poster-address-mobile address-mobile"
id="reply-button" style={{cursor: "pointer"}}
>
(u/
{reply.author?.shortAddress ?
(
<span className="highlight-address-mobile">
{reply.author?.shortAddress}
</span>
) : ( ) : (
<span> <span className='name-mobile'>{reply.author?.displayName}</span>
{account?.author?.shortAddress}
</span>
) )
} ) : (
<span className='name-mobile'>Anonymous</span>
)}
&nbsp;
<span className='poster-address-mobile address-mobile' id='reply-button' style={{ cursor: 'pointer' }}>
(u/
{reply.author?.shortAddress ? (
<span className='highlight-address-mobile'>{reply.author?.shortAddress}</span>
) : (
<span>{account?.author?.shortAddress}</span>
)}
)&nbsp; )&nbsp;
</span> </span>
<br /> <br />
</span> </span>
<span className="date-time-mobile post-number-mobile"> <span className='date-time-mobile post-number-mobile'>
{getDate(reply.timestamp)}&nbsp; {getDate(reply.timestamp)}&nbsp;
<span>c/</span> <span>c/</span>
<Link to={() => {}} id="reply-button" <Link to={() => {}} id='reply-button'>
>{reply.shortCid} {reply.shortCid}
</Link> </Link>
</span> </span>
</div> </div>
{reply.link ? ( {reply.link ? (
<div className="file-mobile"> <div className='file-mobile'>
{replyMediaInfo?.url ? ( {replyMediaInfo?.url ? (
replyMediaInfo.type === "webpage" ? ( replyMediaInfo.type === 'webpage' ? (
<div className="img-container"> <div className='img-container'>
<span className="file-thumb-mobile"> <span className='file-thumb-mobile'>
{reply.thumbnailUrl ? ( {reply.thumbnailUrl ? (
<img <img src={replyMediaInfo.thumbnail} alt='thumbnail' style={{ cursor: 'pointer' }} onError={(e) => (e.target.src = fallbackImgUrl)} />
src={replyMediaInfo.thumbnail} alt="thumbnail"
style={{cursor: "pointer"}}
onError={(e) => e.target.src = fallbackImgUrl} />
) : null} ) : null}
<div className="file-info-mobile">{replyMediaInfo.type}</div> <div className='file-info-mobile'>{replyMediaInfo.type}</div>
</span> </span>
</div> </div>
) : replyMediaInfo.type === "image" ? ( ) : replyMediaInfo.type === 'image' ? (
<div className="img-container"> <div className='img-container'>
<span className="file-thumb-mobile"> <span className='file-thumb-mobile'>
<img <img src={replyMediaInfo.url} alt={replyMediaInfo.type} style={{ cursor: 'pointer' }} onError={(e) => (e.target.src = fallbackImgUrl)} />
src={replyMediaInfo.url} alt={replyMediaInfo.type} <div className='file-info-mobile'>{replyMediaInfo.type}</div>
style={{cursor: "pointer"}}
onError={(e) => e.target.src = fallbackImgUrl} />
<div className="file-info-mobile">{replyMediaInfo.type}</div>
</span> </span>
</div> </div>
) : replyMediaInfo.type === "video" ? ( ) : replyMediaInfo.type === 'video' ? (
<span className="file-thumb-mobile"> <span className='file-thumb-mobile'>
<video <video
src={replyMediaInfo.url} alt={replyMediaInfo.type} src={replyMediaInfo.url}
style={{ pointerEvents: "none" }} alt={replyMediaInfo.type}
onError={(e) => e.target.src = fallbackImgUrl} /> style={{ pointerEvents: 'none' }}
<div className="file-info-mobile">{replyMediaInfo.type}</div> onError={(e) => (e.target.src = fallbackImgUrl)}
/>
<div className='file-info-mobile'>{replyMediaInfo.type}</div>
</span> </span>
) : replyMediaInfo.type === "audio" ? ( ) : replyMediaInfo.type === 'audio' ? (
<span className="file-thumb-mobile"> <span className='file-thumb-mobile'>
<audio <audio src={replyMediaInfo.url} alt={replyMediaInfo.type} onError={(e) => (e.target.src = fallbackImgUrl)} />
src={replyMediaInfo.url} alt={replyMediaInfo.type} <div className='file-info-mobile'>{replyMediaInfo.type}</div>
onError={(e) => e.target.src = fallbackImgUrl} />
<div className="file-info-mobile">{replyMediaInfo.type}</div>
</span> </span>
) : null ) : null
) : null} ) : null}
</div> </div>
) : null} ) : null}
{reply.content ? ( {reply.content ? (
reply.content?.length > 500 ? reply.content?.length > 500 ? (
<Fragment> <Fragment>
<blockquote className="post-message"> <blockquote className='post-message'>
{shortParentCid ? ( {shortParentCid ? (
<Link to={() => {}} className="quotelink"> <Link to={() => {}} className='quotelink'>
{`c/${shortParentCid}`}{shortParentCid === thread.shortCid ? " (OP)" : null} {`c/${shortParentCid}`}
{shortParentCid === thread.shortCid ? ' (OP)' : null}
</Link> </Link>
) : null} ) : null}
<Post content={reply.content?.slice(0, 500)} comment={reply} /> <Post content={reply.content?.slice(0, 500)} comment={reply} />
<span className="ttl"> (...) <span className='ttl'>
{' '}
(...)
<br /> <br />
<EditLabel <EditLabel commentCid={reply.cid} className='ttl' />
commentCid={reply.cid}
className="ttl"/>
<br /> <br />
Comment too long. Click the link to view. </span> Comment too long. Click the link to view.{' '}
</span>
</blockquote> </blockquote>
</Fragment> </Fragment>
: <blockquote className="post-message"> ) : (
<blockquote className='post-message'>
{shortParentCid ? ( {shortParentCid ? (
<Link to={() => {}} className="quotelink" > <Link to={() => {}} className='quotelink'>
{`c/${shortParentCid}`}{shortParentCid === thread.shortCid ? " (OP)" : null} {`c/${shortParentCid}`}
{shortParentCid === thread.shortCid ? ' (OP)' : null}
</Link> </Link>
) : null} ) : null}
<Post content={reply.content} comment={reply} /> <Post content={reply.content} comment={reply} />
<EditLabel <EditLabel commentCid={reply.cid} className='ttl' />
commentCid={reply.cid} </blockquote>
className="ttl"/> )
</blockquote>) ) : null}
: null}
</div> </div>
</div> </div>
) : ( ) : (
<div className="reply-container"> <div className='reply-container'>
<span className="ellipsis">{stateString}</span> <span className='ellipsis'>{stateString}</span>
</div> </div>
)} )}
</div> </div>
@@ -316,6 +291,6 @@ const PostOnHover = ({ cid, feed }) => {
</BoardForm> </BoardForm>
</Container> </Container>
); );
} };
export default PostOnHover; export default PostOnHover;
+6 -11
View File
@@ -1,6 +1,6 @@
import React from "react"; import React from 'react';
import { useAccountComment } from "@plebbit/plebbit-react-hooks"; import { useAccountComment } from '@plebbit/plebbit-react-hooks';
import useStateString from "../hooks/useStateString"; import useStateString from '../hooks/useStateString';
const StateLabel = ({ commentIndex, className }) => { const StateLabel = ({ commentIndex, className }) => {
const comment = useAccountComment({ commentIndex: commentIndex }); const comment = useAccountComment({ commentIndex: commentIndex });
@@ -10,7 +10,7 @@ const StateLabel = ({ commentIndex, className }) => {
return null; return null;
} }
if (comment.state === "failed" || comment.state === "succeeded") { if (comment.state === 'failed' || comment.state === 'succeeded') {
return null; return null;
} }
@@ -19,13 +19,8 @@ const StateLabel = ({ commentIndex, className }) => {
} }
return ( return (
<span className="ttl"> <span className='ttl'>
<br /> <br />(<span className={className}>{stateString}</span>)
(
<span className={className}>
{stateString}
</span>
)
</span> </span>
); );
}; };
+5 -6
View File
@@ -1,6 +1,6 @@
import { useEffect } from "react"; import { useEffect } from 'react';
import { useAccount } from "@plebbit/plebbit-react-hooks"; import { useAccount } from '@plebbit/plebbit-react-hooks';
import useAnonModeStore from "./stores/useAnonModeStore"; import useAnonModeStore from './stores/useAnonModeStore';
const useAnonMode = (threadCid, execute) => { const useAnonMode = (threadCid, execute) => {
const account = useAccount(); const account = useAccount();
@@ -18,13 +18,12 @@ useEffect(() => {
} }
} }
} }
} };
handleAnonMode(); handleAnonMode();
}, [threadCid, execute, account, anonymousMode]); }, [threadCid, execute, account, anonymousMode]);
return; return;
} };
export default useAnonMode; export default useAnonMode;
+5 -5
View File
@@ -1,6 +1,6 @@
import { useEffect } from "react"; import { useEffect } from 'react';
import { useAccount } from "@plebbit/plebbit-react-hooks"; import { useAccount } from '@plebbit/plebbit-react-hooks';
import useAnonModeStore from "./stores/useAnonModeStore"; import useAnonModeStore from './stores/useAnonModeStore';
const useAnonModeRef = (threadCidRef, execute) => { const useAnonModeRef = (threadCidRef, execute) => {
const account = useAccount(); const account = useAccount();
@@ -18,11 +18,11 @@ const useAnonModeRef = (threadCidRef, execute) => {
} }
} }
} }
} };
handleAnonMode(); handleAnonMode();
}, [threadCidRef, execute, account, anonymousMode]); }, [threadCidRef, execute, account, anonymousMode]);
return; return;
} };
export default useAnonModeRef; export default useAnonModeRef;
+1 -1
View File
@@ -1,4 +1,4 @@
import useGeneralStore from "./stores/useGeneralStore"; import useGeneralStore from './stores/useGeneralStore';
const useClickForm = () => { const useClickForm = () => {
const { setShowPostForm, setShowPostFormLink } = useGeneralStore.getState(); const { setShowPostForm, setShowPostFormLink } = useGeneralStore.getState();
+5 -6
View File
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from 'react';
import { toast } from "react-toastify"; import { toast } from 'react-toastify';
const useError = () => { const useError = () => {
const [errorMessage, setErrorMessage] = useState(''); const [errorMessage, setErrorMessage] = useState('');
@@ -9,14 +9,14 @@ const useError = () => {
if (errorMessage && errorMessage.length > 0) { if (errorMessage && errorMessage.length > 0) {
const showErrorToast = () => { const showErrorToast = () => {
const toastId = toast.error(errorMessage.toString(), { const toastId = toast.error(errorMessage.toString(), {
position: "top-right", position: 'top-right',
autoClose: false, autoClose: false,
hideProgressBar: true, hideProgressBar: true,
closeOnClick: false, closeOnClick: false,
pauseOnHover: false, pauseOnHover: false,
draggable: false, draggable: false,
progress: undefined, progress: undefined,
theme: "dark", theme: 'dark',
}); });
return () => { return () => {
@@ -43,10 +43,9 @@ const useError = () => {
} }
setErrorMessage(message); setErrorMessage(message);
setRenderCount(prevCount => prevCount + 1); setRenderCount((prevCount) => prevCount + 1);
}; };
return [errorMessage, setNewErrorMessage]; return [errorMessage, setNewErrorMessage];
}; };
+6 -7
View File
@@ -1,4 +1,4 @@
import { useMemo, useRef } from "react" import { useMemo, useRef } from 'react';
const useFeedRows = (feedWithDescriptionAndRules, columnCount) => { const useFeedRows = (feedWithDescriptionAndRules, columnCount) => {
const rowsRef = useRef([]); const rowsRef = useRef([]);
@@ -6,15 +6,14 @@ const useFeedRows = (feedWithDescriptionAndRules, columnCount) => {
const rows = []; const rows = [];
for (let i = 0; i < feedWithDescriptionAndRules.length; i += columnCount) { for (let i = 0; i < feedWithDescriptionAndRules.length; i += columnCount) {
if (rowsRef.current?.[rows.length] && rowsRef.current[rows.length].length === columnCount) { if (rowsRef.current?.[rows.length] && rowsRef.current[rows.length].length === columnCount) {
rows.push(rowsRef.current[rows.length]) rows.push(rowsRef.current[rows.length]);
} } else {
else { rows.push(feedWithDescriptionAndRules.slice(i, i + columnCount));
rows.push(feedWithDescriptionAndRules.slice(i, i + columnCount))
} }
} }
rowsRef.current = rows rowsRef.current = rows;
return rows; return rows;
}, [feedWithDescriptionAndRules, columnCount]); }, [feedWithDescriptionAndRules, columnCount]);
} };
export default useFeedRows; export default useFeedRows;
+34 -35
View File
@@ -1,27 +1,26 @@
import { useMemo } from "react" import { useMemo } from 'react';
const useFeedStateString = (subplebbits) => { const useFeedStateString = (subplebbits) => {
return useMemo(() => { return useMemo(() => {
const getClientHost = (clientUrl) => { const getClientHost = (clientUrl) => {
try { try {
clientUrl = new URL(clientUrl).hostname || clientUrl clientUrl = new URL(clientUrl).hostname || clientUrl;
} } catch (e) {}
catch (e) {} return clientUrl;
return clientUrl };
}
const getClientUrls = (regex) => { const getClientUrls = (regex) => {
const clientUrls = new Set() const clientUrls = new Set();
const addClientUrl = (client, clientUrl) => client?.state?.match?.(regex) && clientUrls.add(getClientHost(clientUrl)) const addClientUrl = (client, clientUrl) => client?.state?.match?.(regex) && clientUrls.add(getClientHost(clientUrl));
for (const subplebbit of subplebbits) { for (const subplebbit of subplebbits) {
for (const clientUrl in subplebbit?.clients?.ipfsGateways) { for (const clientUrl in subplebbit?.clients?.ipfsGateways) {
addClientUrl(subplebbit.clients.ipfsGateways[clientUrl], clientUrl) addClientUrl(subplebbit.clients.ipfsGateways[clientUrl], clientUrl);
} }
for (const clientUrl in subplebbit?.clients?.ipfsClients) { for (const clientUrl in subplebbit?.clients?.ipfsClients) {
addClientUrl(subplebbit.clients.ipfsClients[clientUrl], clientUrl) addClientUrl(subplebbit.clients.ipfsClients[clientUrl], clientUrl);
} }
for (const chainTicker in subplebbit?.clients?.chainProviders) { for (const chainTicker in subplebbit?.clients?.chainProviders) {
for (const clientUrl in subplebbit.clients.chainProviders[chainTicker]) { for (const clientUrl in subplebbit.clients.chainProviders[chainTicker]) {
addClientUrl(subplebbit.clients.chainProviders[chainTicker][clientUrl], clientUrl) addClientUrl(subplebbit.clients.chainProviders[chainTicker][clientUrl], clientUrl);
} }
} }
// find subplebbit pages states // find subplebbit pages states
@@ -29,68 +28,68 @@ const useFeedStateString = (subplebbits) => {
for (const clientType in subplebbit.posts.clients) { for (const clientType in subplebbit.posts.clients) {
for (const sortType in subplebbit.posts.clients[clientType]) { for (const sortType in subplebbit.posts.clients[clientType]) {
for (const clientUrl in subplebbit.posts.clients[clientType][sortType]) { for (const clientUrl in subplebbit.posts.clients[clientType][sortType]) {
addClientUrl(subplebbit.posts.clients[clientType][sortType][clientUrl], clientUrl) addClientUrl(subplebbit.posts.clients[clientType][sortType][clientUrl], clientUrl);
} }
} }
} }
} }
} }
return [...clientUrls] return [...clientUrls];
} };
if (!subplebbits) { if (!subplebbits) {
return return;
} }
const states = {} const states = {};
for (const subplebbit of subplebbits) { for (const subplebbit of subplebbits) {
states[subplebbit?.updatingState] = (states[subplebbit?.updatingState] || 0) + 1 states[subplebbit?.updatingState] = (states[subplebbit?.updatingState] || 0) + 1;
// find subplebbit pages states // find subplebbit pages states
for (const clientType in subplebbit?.posts?.clients) { for (const clientType in subplebbit?.posts?.clients) {
for (const sortType in subplebbit.posts.clients[clientType]) { for (const sortType in subplebbit.posts.clients[clientType]) {
for (const clientUrl in subplebbit.posts.clients[clientType][sortType]) { for (const clientUrl in subplebbit.posts.clients[clientType][sortType]) {
const state = subplebbit.posts.clients[clientType][sortType][clientUrl].state const state = subplebbit.posts.clients[clientType][sortType][clientUrl].state;
states[state] = (states[state] || 0) + 1 states[state] = (states[state] || 0) + 1;
} }
} }
} }
} }
// e.g. Resolving 2 addresses from infura.io, fetching 2 IPNS, 1 IPFS from cloudflare-ipfs.com, ipfs.io // e.g. Resolving 2 addresses from infura.io, fetching 2 IPNS, 1 IPFS from cloudflare-ipfs.com, ipfs.io
let stateString = '' let stateString = '';
if (states['resolving-address']) { if (states['resolving-address']) {
stateString += `resolving ${states['resolving-address']} addresses` stateString += `resolving ${states['resolving-address']} addresses`;
const clientUrls = getClientUrls(/address/) const clientUrls = getClientUrls(/address/);
if (clientUrls.length) { if (clientUrls.length) {
stateString += ` from ${clientUrls.join(', ')}` stateString += ` from ${clientUrls.join(', ')}`;
} }
} }
if (states['fetching-ipns'] || states['fetching-ipfs']) { if (states['fetching-ipns'] || states['fetching-ipfs']) {
if (stateString) { if (stateString) {
stateString += ', ' stateString += ', ';
} }
stateString += `fetching ` stateString += `fetching `;
if (states['fetching-ipns']) { if (states['fetching-ipns']) {
stateString += `${states['fetching-ipns']} IPNS` stateString += `${states['fetching-ipns']} IPNS`;
} }
if (states['fetching-ipfs']) { if (states['fetching-ipfs']) {
if (states['fetching-ipns']) { if (states['fetching-ipns']) {
stateString += ', ' stateString += ', ';
} }
stateString += `${states['fetching-ipfs']} IPFS` stateString += `${states['fetching-ipfs']} IPFS`;
} }
const clientUrls = getClientUrls(/ipfs|ipns/) const clientUrls = getClientUrls(/ipfs|ipns/);
if (clientUrls.length) { if (clientUrls.length) {
stateString += ` from ${clientUrls.join(', ')}` stateString += ` from ${clientUrls.join(', ')}`;
} }
} }
// capitalize first letter // capitalize first letter
stateString = stateString.charAt(0).toUpperCase() + stateString.slice(1) stateString = stateString.charAt(0).toUpperCase() + stateString.slice(1);
// if string is empty, return undefined instead // if string is empty, return undefined instead
return stateString || undefined return stateString || undefined;
}, [subplebbits]) }, [subplebbits]);
} };
export default useFeedStateString export default useFeedStateString;
+5 -5
View File
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from 'react';
import { toast } from "react-toastify"; import { toast } from 'react-toastify';
const useInfo = () => { const useInfo = () => {
const [infoMessage, setInfoMessage] = useState(''); const [infoMessage, setInfoMessage] = useState('');
@@ -9,14 +9,14 @@ const useInfo = () => {
if (infoMessage && infoMessage.length > 0) { if (infoMessage && infoMessage.length > 0) {
const showInfoToast = () => { const showInfoToast = () => {
const toastId = toast.info(infoMessage.toString(), { const toastId = toast.info(infoMessage.toString(), {
position: "top-right", position: 'top-right',
autoClose: false, autoClose: false,
hideProgressBar: false, hideProgressBar: false,
closeOnClick: false, closeOnClick: false,
pauseOnHover: false, pauseOnHover: false,
draggable: false, draggable: false,
progress: undefined, progress: undefined,
theme: "dark", theme: 'dark',
}); });
return () => { return () => {
@@ -34,7 +34,7 @@ const useInfo = () => {
const setNewInfoMessage = (message) => { const setNewInfoMessage = (message) => {
setInfoMessage(message); setInfoMessage(message);
setRenderCount(prevCount => prevCount + 1); setRenderCount((prevCount) => prevCount + 1);
}; };
return [infoMessage, setNewInfoMessage]; return [infoMessage, setNewInfoMessage];
+38 -40
View File
@@ -1,39 +1,39 @@
import { useMemo } from 'react' import { useMemo } from 'react';
const useStateString = (commentOrSubplebbit) => { const useStateString = (commentOrSubplebbit) => {
return useMemo(() => { return useMemo(() => {
// dont show state string if the data is already fetched // dont show state string if the data is already fetched
if (commentOrSubplebbit?.updatedAt || commentOrSubplebbit?.state === 'succeeded') { if (commentOrSubplebbit?.updatedAt || commentOrSubplebbit?.state === 'succeeded') {
return return;
} }
if (!commentOrSubplebbit?.clients) { if (!commentOrSubplebbit?.clients) {
return return;
} }
const clients = commentOrSubplebbit?.clients const clients = commentOrSubplebbit?.clients;
const states = {} const states = {};
const addState = (state, clientUrl) => { const addState = (state, clientUrl) => {
if (!state || state === 'stopped') { if (!state || state === 'stopped') {
return return;
} }
if (!states[state]) { if (!states[state]) {
states[state] = [] states[state] = [];
}
states[state].push(clientUrl)
} }
states[state].push(clientUrl);
};
for (const clientUrl in clients?.ipfsGateways) { for (const clientUrl in clients?.ipfsGateways) {
addState(clients.ipfsGateways[clientUrl]?.state, clientUrl) addState(clients.ipfsGateways[clientUrl]?.state, clientUrl);
} }
for (const clientUrl in clients?.ipfsClients) { for (const clientUrl in clients?.ipfsClients) {
addState(clients.ipfsClients[clientUrl]?.state, clientUrl) addState(clients.ipfsClients[clientUrl]?.state, clientUrl);
} }
for (const clientUrl in clients?.pubsubClients) { for (const clientUrl in clients?.pubsubClients) {
addState(clients.pubsubClients[clientUrl]?.state, clientUrl) addState(clients.pubsubClients[clientUrl]?.state, clientUrl);
} }
for (const chainTicker in clients?.chainProviders) { for (const chainTicker in clients?.chainProviders) {
for (const clientUrl in clients.chainProviders[chainTicker]) { for (const clientUrl in clients.chainProviders[chainTicker]) {
addState(clients.chainProviders[chainTicker][clientUrl]?.state, clientUrl) addState(clients.chainProviders[chainTicker][clientUrl]?.state, clientUrl);
} }
} }
@@ -42,15 +42,15 @@ const useStateString = (commentOrSubplebbit) => {
for (const clientType in commentOrSubplebbit.posts.clients) { for (const clientType in commentOrSubplebbit.posts.clients) {
for (const sortType in commentOrSubplebbit.posts.clients[clientType]) { for (const sortType in commentOrSubplebbit.posts.clients[clientType]) {
for (const clientUrl in commentOrSubplebbit.posts.clients[clientType][sortType]) { for (const clientUrl in commentOrSubplebbit.posts.clients[clientType][sortType]) {
let state = commentOrSubplebbit.posts.clients[clientType][sortType][clientUrl].state let state = commentOrSubplebbit.posts.clients[clientType][sortType][clientUrl].state;
if (state === 'stopped') { if (state === 'stopped') {
continue continue;
} }
state += `-page-${sortType}` state += `-page-${sortType}`;
if (!states[state]) { if (!states[state]) {
states[state] = [] states[state] = [];
} }
states[state].push(clientUrl) states[state].push(clientUrl);
} }
} }
} }
@@ -58,53 +58,51 @@ const useStateString = (commentOrSubplebbit) => {
const getClientHost = (clientUrl) => { const getClientHost = (clientUrl) => {
try { try {
clientUrl = new URL(clientUrl).hostname || clientUrl clientUrl = new URL(clientUrl).hostname || clientUrl;
} } catch (e) {}
catch (e) {} return clientUrl;
return clientUrl };
}
let stateString = '' let stateString = '';
for (const state in states) { for (const state in states) {
const clientUrls = states[state] const clientUrls = states[state];
const clientHosts = clientUrls.map(clientUrl => getClientHost(clientUrl)) const clientHosts = clientUrls.map((clientUrl) => getClientHost(clientUrl));
// if there are no valid hosts, skip this state // if there are no valid hosts, skip this state
if (clientHosts.length === 0) { if (clientHosts.length === 0) {
continue continue;
} }
// separate 2 different states using ', ' // separate 2 different states using ', '
if (stateString) { if (stateString) {
stateString += ', ' stateString += ', ';
} }
// e.g. 'fetching IPFS from cloudflare-ipfs.com, ipfs.io' // e.g. 'fetching IPFS from cloudflare-ipfs.com, ipfs.io'
const formattedState = state.replaceAll('-', ' ').replace('ipfs', 'IPFS').replace('ipns', 'IPNS') const formattedState = state.replaceAll('-', ' ').replace('ipfs', 'IPFS').replace('ipns', 'IPNS');
stateString += `${formattedState} from ${clientHosts.join(', ')}` stateString += `${formattedState} from ${clientHosts.join(', ')}`;
} }
// fallback to comment or subplebbit state when possible // fallback to comment or subplebbit state when possible
if (!stateString) { if (!stateString) {
if (commentOrSubplebbit?.publishingState && commentOrSubplebbit?.publishingState !== 'stopped' && commentOrSubplebbit?.publishingState !== 'succeeded') { if (commentOrSubplebbit?.publishingState && commentOrSubplebbit?.publishingState !== 'stopped' && commentOrSubplebbit?.publishingState !== 'succeeded') {
stateString = commentOrSubplebbit.publishingState stateString = commentOrSubplebbit.publishingState;
} } else if (commentOrSubplebbit?.updatingState !== 'stopped' && commentOrSubplebbit?.updatingState !== 'succeeded') {
else if (commentOrSubplebbit?.updatingState !== 'stopped' && commentOrSubplebbit?.updatingState !== 'succeeded') { stateString = commentOrSubplebbit.updatingState;
stateString = commentOrSubplebbit.updatingState
} }
if (stateString) { if (stateString) {
stateString = stateString.replaceAll('-', ' ').replace('ipfs', 'IPFS').replace('ipns', 'IPNS') stateString = stateString.replaceAll('-', ' ').replace('ipfs', 'IPFS').replace('ipns', 'IPNS');
} }
} }
// capitalize first letter // capitalize first letter
if (stateString) { if (stateString) {
stateString = stateString.charAt(0).toUpperCase() + stateString.slice(1) stateString = stateString.charAt(0).toUpperCase() + stateString.slice(1);
} }
// if string is empty, return undefined instead // if string is empty, return undefined instead
return stateString === '' ? undefined : stateString return stateString === '' ? undefined : stateString;
}, [commentOrSubplebbit]) }, [commentOrSubplebbit]);
} };
export default useStateString export default useStateString;
+5 -5
View File
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from 'react';
import { toast } from "react-toastify"; import { toast } from 'react-toastify';
const useSuccess = () => { const useSuccess = () => {
const [successMessage, setSuccessMessage] = useState(''); const [successMessage, setSuccessMessage] = useState('');
@@ -9,14 +9,14 @@ const useSuccess = () => {
if (successMessage && successMessage.length > 0) { if (successMessage && successMessage.length > 0) {
const showSuccessToast = () => { const showSuccessToast = () => {
const toastId = toast.success(successMessage.toString(), { const toastId = toast.success(successMessage.toString(), {
position: "top-right", position: 'top-right',
autoClose: 3000, autoClose: 3000,
hideProgressBar: false, hideProgressBar: false,
closeOnClick: false, closeOnClick: false,
pauseOnHover: false, pauseOnHover: false,
draggable: false, draggable: false,
progress: undefined, progress: undefined,
theme: "dark", theme: 'dark',
}); });
return () => { return () => {
@@ -34,7 +34,7 @@ const useSuccess = () => {
const setNewSuccessMessage = (message) => { const setNewSuccessMessage = (message) => {
setSuccessMessage(message); setSuccessMessage(message);
setRenderCount(prevCount => prevCount + 1); setRenderCount((prevCount) => prevCount + 1);
}; };
return [successMessage, setNewSuccessMessage]; return [successMessage, setNewSuccessMessage];
+7 -7
View File
@@ -1,16 +1,16 @@
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react';
export default function useWindowWidth() { export default function useWindowWidth() {
const [windowWidth, setWindowWidth] = useState(window.innerWidth) const [windowWidth, setWindowWidth] = useState(window.innerWidth);
useEffect(() => { useEffect(() => {
function handleResize() { function handleResize() {
setWindowWidth(window.innerWidth) setWindowWidth(window.innerWidth);
} }
window.addEventListener('resize', handleResize) window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize) return () => window.removeEventListener('resize', handleResize);
}, []) }, []);
return windowWidth return windowWidth;
} }
-1
View File
@@ -3,7 +3,6 @@ function countLinks(comment) {
if (comment.replyCount > 0) { if (comment.replyCount > 0) {
for (let reply of comment.replies.pages.topAll.comments) { for (let reply of comment.replies.pages.topAll.comments) {
if (reply.link) { if (reply.link) {
linkCount++; linkCount++;
} }
-2
View File
@@ -15,11 +15,9 @@ const getCommentMediaInfo = (comment) => {
if (['youtube.com', 'www.youtube.com', 'youtu.be'].includes(host)) { if (['youtube.com', 'www.youtube.com', 'youtu.be'].includes(host)) {
const videoId = host === 'youtu.be' ? url.pathname.slice(1) : url.searchParams.get('v'); const videoId = host === 'youtu.be' ? url.pathname.slice(1) : url.searchParams.get('v');
scrapedThumbnailUrl = `https://img.youtube.com/vi/${videoId}/sddefault.jpg`; scrapedThumbnailUrl = `https://img.youtube.com/vi/${videoId}/sddefault.jpg`;
} else if (host.includes('bitchute.com')) { } else if (host.includes('bitchute.com')) {
const videoId = url.pathname.split('/')[2]; const videoId = url.pathname.split('/')[2];
scrapedThumbnailUrl = `https://static-3.bitchute.com/live/cover_images/F61vWF4shy8s/${videoId}_640x360.jpg`; scrapedThumbnailUrl = `https://static-3.bitchute.com/live/cover_images/F61vWF4shy8s/${videoId}_640x360.jpg`;
} else if (host.includes('streamable.com')) { } else if (host.includes('streamable.com')) {
const videoId = url.pathname.split('/')[1]; const videoId = url.pathname.split('/')[1];
scrapedThumbnailUrl = `https://cdn-cf-east.streamable.com/image/${videoId}.jpg`; scrapedThumbnailUrl = `https://cdn-cf-east.streamable.com/image/${videoId}.jpg`;
+10 -13
View File
@@ -1,6 +1,6 @@
const getDate = (commentTimestamp) => { const getDate = (commentTimestamp) => {
if (commentTimestamp === undefined || isNaN(commentTimestamp)) { if (commentTimestamp === undefined || isNaN(commentTimestamp)) {
return ""; return '';
} }
const locale = Intl.DateTimeFormat().resolvedOptions().locale; const locale = Intl.DateTimeFormat().resolvedOptions().locale;
const string = new Intl.DateTimeFormat(locale, { const string = new Intl.DateTimeFormat(locale, {
@@ -11,28 +11,25 @@ const getDate = (commentTimestamp) => {
weekday: 'short', weekday: 'short',
hour: '2-digit', hour: '2-digit',
minute: '2-digit', minute: '2-digit',
second: '2-digit' second: '2-digit',
}).format(new Date(commentTimestamp * 1000)); }).format(new Date(commentTimestamp * 1000));
if (locale.startsWith('ar')) { if (locale.startsWith('ar')) {
return string return string;
} }
const items = string.split(/,* /) const items = string.split(/,* /);
if (items.length === 3) { if (items.length === 3) {
const itemIsNumber = [ const itemIsNumber = [items[0][0].match(/[0-9]/), items[1][0].match(/[0-9]/)];
items[0][0].match(/[0-9]/),
items[1][0].match(/[0-9]/)
]
if (itemIsNumber[0] && itemIsNumber[1]) { if (itemIsNumber[0] && itemIsNumber[1]) {
return `${items[0]}(${items[2]})${items[1]}` return `${items[0]}(${items[2]})${items[1]}`;
} }
if (itemIsNumber[0] && !itemIsNumber[1]) { if (itemIsNumber[0] && !itemIsNumber[1]) {
return `${items[0]}(${items[1]})${items[2]}` return `${items[0]}(${items[1]})${items[2]}`;
} }
if (!itemIsNumber[0] && itemIsNumber[1]) { if (!itemIsNumber[0] && itemIsNumber[1]) {
return `${items[1]}(${items[0]})${items[2]}` return `${items[1]}(${items[0]})${items[2]}`;
} }
} }
return string return string;
} };
export default getDate; export default getDate;
+5 -6
View File
@@ -5,7 +5,7 @@ const pluralize = (unit, value) => {
const getFormattedTime = (timestamp) => { const getFormattedTime = (timestamp) => {
try { try {
const currentTime = new Date().getTime(); const currentTime = new Date().getTime();
const differenceInMilliseconds = currentTime - (timestamp * 1000); const differenceInMilliseconds = currentTime - timestamp * 1000;
const years = Math.floor(differenceInMilliseconds / (1000 * 60 * 60 * 24 * 365.25)); const years = Math.floor(differenceInMilliseconds / (1000 * 60 * 60 * 24 * 365.25));
const months = Math.floor((differenceInMilliseconds % (1000 * 60 * 60 * 24 * 365.25)) / (1000 * 60 * 60 * 24 * 30)); const months = Math.floor((differenceInMilliseconds % (1000 * 60 * 60 * 24 * 365.25)) / (1000 * 60 * 60 * 24 * 30));
@@ -33,12 +33,11 @@ const getFormattedTime = (timestamp) => {
} else if (seconds > 30) { } else if (seconds > 30) {
return `${pluralize('second', seconds)} ago`; return `${pluralize('second', seconds)} ago`;
} else { } else {
return "just now"; return 'just now';
} }
} } catch (e) {
catch (e) { console.error('Error in getFormattedTime:', e);
console.error("Error in getFormattedTime:", e); return '[error]';
return "[error]";
} }
}; };
+4 -4
View File
@@ -4,7 +4,7 @@ function handleAddressClick(shortAddress) {
const postReplySelector = isMobile ? '.post-reply-mobile' : '.post-reply-desktop'; const postReplySelector = isMobile ? '.post-reply-mobile' : '.post-reply-desktop';
const opSelector = isMobile ? '.op-mobile' : '.op-desktop'; const opSelector = isMobile ? '.op-mobile' : '.op-desktop';
const matchingElements = [...document.querySelectorAll(postReplySelector + ',' + opSelector)].filter(el => { const matchingElements = [...document.querySelectorAll(postReplySelector + ',' + opSelector)].filter((el) => {
const addressElement = el.querySelector(addressSelector); const addressElement = el.querySelector(addressSelector);
return addressElement && addressElement.textContent.includes(shortAddress); return addressElement && addressElement.textContent.includes(shortAddress);
}); });
@@ -16,18 +16,18 @@ function handleAddressClick(shortAddress) {
const highlightedElements = document.querySelectorAll('.highlighted-address'); const highlightedElements = document.querySelectorAll('.highlighted-address');
let allHighlighted = true; let allHighlighted = true;
matchingElements.forEach(el => { matchingElements.forEach((el) => {
if (!el.classList.contains('highlighted-address')) { if (!el.classList.contains('highlighted-address')) {
allHighlighted = false; allHighlighted = false;
} }
}); });
highlightedElements.forEach(el => { highlightedElements.forEach((el) => {
el.classList.remove('highlighted-address'); el.classList.remove('highlighted-address');
}); });
if (!allHighlighted) { if (!allHighlighted) {
matchingElements.forEach(el => { matchingElements.forEach((el) => {
if (!el.classList.contains('op-mobile') && !el.classList.contains('op-desktop')) { if (!el.classList.contains('op-mobile') && !el.classList.contains('op-desktop')) {
el.classList.add('highlighted-address'); el.classList.add('highlighted-address');
} }
+7 -9
View File
@@ -6,20 +6,19 @@ function handleQuoteClick(reply, parentCid, threadCid) {
if (threadCid && cid === threadCid) { if (threadCid && cid === threadCid) {
const highlightedElements = document.querySelectorAll('.highlighted'); const highlightedElements = document.querySelectorAll('.highlighted');
highlightedElements.forEach(el => { highlightedElements.forEach((el) => {
el.classList.remove('highlighted'); el.classList.remove('highlighted');
}); });
const opElementSelector = isMobile ? '.op-mobile' : '.op-desktop'; const opElementSelector = isMobile ? '.op-mobile' : '.op-desktop';
const opElement = [...document.querySelectorAll(opElementSelector)] const opElement = [...document.querySelectorAll(opElementSelector)].find((el) => {
.find(el => {
const postNumberElement = el.querySelector(postNumberSelector); const postNumberElement = el.querySelector(postNumberSelector);
return postNumberElement && postNumberElement.innerHTML.includes(threadCid); return postNumberElement && postNumberElement.innerHTML.includes(threadCid);
}); });
if (opElement) { if (opElement) {
opElement.scrollIntoView({ behavior: "auto", block: "start" }); opElement.scrollIntoView({ behavior: 'auto', block: 'start' });
} else { } else {
return; return;
} }
@@ -29,8 +28,7 @@ function handleQuoteClick(reply, parentCid, threadCid) {
const targetElementSelector = isMobile ? '.post-reply-mobile, .op-mobile' : '.post-reply-desktop, .op-desktop'; const targetElementSelector = isMobile ? '.post-reply-mobile, .op-mobile' : '.post-reply-desktop, .op-desktop';
const targetElement = [...document.querySelectorAll(targetElementSelector)] const targetElement = [...document.querySelectorAll(targetElementSelector)].find((el) => {
.find(el => {
const postNumberElement = el.querySelector(postNumberSelector); const postNumberElement = el.querySelector(postNumberSelector);
return postNumberElement && postNumberElement.innerHTML.includes(cid); return postNumberElement && postNumberElement.innerHTML.includes(cid);
}); });
@@ -38,11 +36,11 @@ function handleQuoteClick(reply, parentCid, threadCid) {
if (targetElement) { if (targetElement) {
const highlightedElements = document.querySelectorAll('.highlighted-click'); const highlightedElements = document.querySelectorAll('.highlighted-click');
highlightedElements.forEach(el => { highlightedElements.forEach((el) => {
el.classList.remove('highlighted-click'); el.classList.remove('highlighted-click');
}); });
targetElement.scrollIntoView({ behavior: "auto", block: "start" }); targetElement.scrollIntoView({ behavior: 'auto', block: 'start' });
if (!targetElement.classList.contains('op-mobile') && !targetElement.classList.contains('op-desktop')) { if (!targetElement.classList.contains('op-mobile') && !targetElement.classList.contains('op-desktop')) {
targetElement.classList.add('highlighted-click'); targetElement.classList.add('highlighted-click');
@@ -50,6 +48,6 @@ function handleQuoteClick(reply, parentCid, threadCid) {
} else { } else {
return; return;
} }
}; }
export default handleQuoteClick; export default handleQuoteClick;
+3 -4
View File
@@ -5,8 +5,7 @@ function handleQuoteHover(reply, parentCid, onElementOutOfView) {
const targetElementSelector = isMobile ? '.post-reply-mobile, .op-mobile' : '.post-reply-desktop, .op-desktop'; const targetElementSelector = isMobile ? '.post-reply-mobile, .op-mobile' : '.post-reply-desktop, .op-desktop';
const targetElement = [...document.querySelectorAll(targetElementSelector)] const targetElement = [...document.querySelectorAll(targetElementSelector)].find((el) => {
.find(el => {
const postNumberElement = el.querySelector(postNumberSelector); const postNumberElement = el.querySelector(postNumberSelector);
return postNumberElement && postNumberElement.innerHTML.includes(cid); return postNumberElement && postNumberElement.innerHTML.includes(cid);
}); });
@@ -25,7 +24,7 @@ function handleQuoteHover(reply, parentCid, onElementOutOfView) {
if (isInViewport(targetElement)) { if (isInViewport(targetElement)) {
const highlightedElements = document.querySelectorAll('.highlighted'); const highlightedElements = document.querySelectorAll('.highlighted');
highlightedElements.forEach(el => { highlightedElements.forEach((el) => {
el.classList.remove('highlighted'); el.classList.remove('highlighted');
}); });
@@ -38,6 +37,6 @@ function handleQuoteHover(reply, parentCid, onElementOutOfView) {
} else { } else {
onElementOutOfView(); onElementOutOfView();
} }
}; }
export default handleQuoteHover; export default handleQuoteHover;
+9 -6
View File
@@ -1,13 +1,13 @@
function handleShareClick(selectedAddress, cid) { function handleShareClick(selectedAddress, cid) {
let shareLink; let shareLink;
if (cid === "rules" || cid === "description") { if (cid === 'rules' || cid === 'description') {
shareLink = `https://plebchan.eth.limo/#/p/${selectedAddress}`; shareLink = `https://plebchan.eth.limo/#/p/${selectedAddress}`;
} else { } else {
const plebBzBaseURL = "https://pleb.bz/p/"; const plebBzBaseURL = 'https://pleb.bz/p/';
shareLink = `${plebBzBaseURL}${selectedAddress}/`; shareLink = `${plebBzBaseURL}${selectedAddress}/`;
if (cid !== "rules" && cid !== "description") { if (cid !== 'rules' && cid !== 'description') {
shareLink += `c/${cid}`; shareLink += `c/${cid}`;
} }
@@ -15,9 +15,12 @@ function handleShareClick(selectedAddress, cid) {
} }
if (navigator.clipboard) { if (navigator.clipboard) {
navigator.clipboard.writeText(shareLink).then(() => { navigator.clipboard
console.log("Link copied to clipboard!"); .writeText(shareLink)
}).catch(err => { .then(() => {
console.log('Link copied to clipboard!');
})
.catch((err) => {
console.error('Could not copy text: ', err); console.error('Could not copy text: ', err);
}); });
} else { } else {
+51 -53
View File
@@ -1,94 +1,92 @@
import useGeneralStore from "../hooks/stores/useGeneralStore"; import useGeneralStore from '../hooks/stores/useGeneralStore';
const handleStyleChange = (event) => { const handleStyleChange = (event) => {
const { const { setBodyStyle, setSelectedStyle } = useGeneralStore.getState();
setBodyStyle, setSelectedStyle
} = useGeneralStore.getState();
switch (event.target.value) { switch (event.target.value) {
case "Yotsuba": case 'Yotsuba':
const yotsubaBodyStyle = { const yotsubaBodyStyle = {
background: "#ffe url(assets/fade.png) top repeat-x", background: '#ffe url(assets/fade.png) top repeat-x',
color: "maroon", color: 'maroon',
fontFamily: "Arial, Helvetica, sans-serif" fontFamily: 'Arial, Helvetica, sans-serif',
}; };
setBodyStyle(yotsubaBodyStyle); setBodyStyle(yotsubaBodyStyle);
setSelectedStyle("Yotsuba"); setSelectedStyle('Yotsuba');
localStorage.setItem("selectedStyle", "Yotsuba"); localStorage.setItem('selectedStyle', 'Yotsuba');
localStorage.setItem("bodyStyle", JSON.stringify(yotsubaBodyStyle)); localStorage.setItem('bodyStyle', JSON.stringify(yotsubaBodyStyle));
break; break;
case "Yotsuba-B": case 'Yotsuba-B':
const yotsubaBBodyStyle = { const yotsubaBBodyStyle = {
background: "#eef2ff url(assets/fade-blue.png) top center repeat-x", background: '#eef2ff url(assets/fade-blue.png) top center repeat-x',
color: "#000", color: '#000',
fontFamily: "Arial, Helvetica, sans-serif" fontFamily: 'Arial, Helvetica, sans-serif',
}; };
setBodyStyle(yotsubaBBodyStyle); setBodyStyle(yotsubaBBodyStyle);
setSelectedStyle("Yotsuba-B"); setSelectedStyle('Yotsuba-B');
localStorage.setItem("selectedStyle", "Yotsuba-B"); localStorage.setItem('selectedStyle', 'Yotsuba-B');
localStorage.setItem("bodyStyle", JSON.stringify(yotsubaBBodyStyle)); localStorage.setItem('bodyStyle', JSON.stringify(yotsubaBBodyStyle));
break; break;
case "Futaba": case 'Futaba':
const futabaBodyStyle = { const futabaBodyStyle = {
background: "#ffe", background: '#ffe',
color: "maroon", color: 'maroon',
fontFamily: "times new roman, serif" fontFamily: 'times new roman, serif',
}; };
setBodyStyle(futabaBodyStyle); setBodyStyle(futabaBodyStyle);
setSelectedStyle("Futaba"); setSelectedStyle('Futaba');
localStorage.setItem("selectedStyle", "Futaba"); localStorage.setItem('selectedStyle', 'Futaba');
localStorage.setItem("bodyStyle", JSON.stringify(futabaBodyStyle)); localStorage.setItem('bodyStyle', JSON.stringify(futabaBodyStyle));
break; break;
case "Burichan": case 'Burichan':
const burichanBodyStyle = { const burichanBodyStyle = {
background: "#eef2ff", background: '#eef2ff',
color: "#000", color: '#000',
fontFamily: "times new roman, serif" fontFamily: 'times new roman, serif',
}; };
setBodyStyle(burichanBodyStyle); setBodyStyle(burichanBodyStyle);
setSelectedStyle("Burichan"); setSelectedStyle('Burichan');
localStorage.setItem("selectedStyle", "Burichan"); localStorage.setItem('selectedStyle', 'Burichan');
localStorage.setItem("bodyStyle", JSON.stringify(burichanBodyStyle)); localStorage.setItem('bodyStyle', JSON.stringify(burichanBodyStyle));
break; break;
case "Tomorrow": case 'Tomorrow':
const tomorrowBodyStyle = { const tomorrowBodyStyle = {
background: "#1d1f21 none", background: '#1d1f21 none',
color: "#c5c8c6", color: '#c5c8c6',
fontFamily: "Arial, Helvetica, sans-serif" fontFamily: 'Arial, Helvetica, sans-serif',
}; };
setBodyStyle(tomorrowBodyStyle); setBodyStyle(tomorrowBodyStyle);
setSelectedStyle("Tomorrow"); setSelectedStyle('Tomorrow');
localStorage.setItem("selectedStyle", "Tomorrow"); localStorage.setItem('selectedStyle', 'Tomorrow');
localStorage.setItem("bodyStyle", JSON.stringify(tomorrowBodyStyle)); localStorage.setItem('bodyStyle', JSON.stringify(tomorrowBodyStyle));
break; break;
case "Photon": case 'Photon':
const photonBodyStyle = { const photonBodyStyle = {
background: "#eee none", background: '#eee none',
color: "#333", color: '#333',
fontFamily: "Arial, Helvetica, sans-serif" fontFamily: 'Arial, Helvetica, sans-serif',
}; };
setBodyStyle(photonBodyStyle); setBodyStyle(photonBodyStyle);
setSelectedStyle("Photon"); setSelectedStyle('Photon');
localStorage.setItem("selectedStyle", "Photon"); localStorage.setItem('selectedStyle', 'Photon');
localStorage.setItem("bodyStyle", JSON.stringify(photonBodyStyle)); localStorage.setItem('bodyStyle', JSON.stringify(photonBodyStyle));
break; break;
default: default:
const defaultBodyStyle = { const defaultBodyStyle = {
background: "#ffe url(assets/fade.png) top repeat-x", background: '#ffe url(assets/fade.png) top repeat-x',
color: "maroon", color: 'maroon',
fontFamily: "Arial, Helvetica, sans-serif" fontFamily: 'Arial, Helvetica, sans-serif',
}; };
setBodyStyle(defaultBodyStyle); setBodyStyle(defaultBodyStyle);
setSelectedStyle("Yotsuba"); setSelectedStyle('Yotsuba');
localStorage.setItem("selectedStyle", "Yotsuba"); localStorage.setItem('selectedStyle', 'Yotsuba');
localStorage.setItem("bodyStyle", JSON.stringify(defaultBodyStyle)); localStorage.setItem('bodyStyle', JSON.stringify(defaultBodyStyle));
}
} }
};
export default handleStyleChange; export default handleStyleChange;
+2 -2
View File
@@ -1,9 +1,9 @@
function removeHighlight() { function removeHighlight() {
const highlightedElements = document.querySelectorAll('.highlighted'); const highlightedElements = document.querySelectorAll('.highlighted');
highlightedElements.forEach(el => { highlightedElements.forEach((el) => {
el.classList.remove('highlighted'); el.classList.remove('highlighted');
}); });
}; }
export default removeHighlight; export default removeHighlight;