fix(Post Form): use defaultValue for Name when displayName is defined

This commit is contained in:
plebeius.eth
2023-09-22 21:43:10 +02:00
parent a7a845eada
commit c779c34243
4 changed files with 276 additions and 298 deletions
+270 -292
View File
@@ -8,332 +8,310 @@ import useError from '../../hooks/useError';
import useAnonModeStore from '../../hooks/stores/useAnonModeStore'; import useAnonModeStore from '../../hooks/stores/useAnonModeStore';
import useGeneralStore from '../../hooks/stores/useGeneralStore'; import useGeneralStore from '../../hooks/stores/useGeneralStore';
const ReplyModal = ({ isOpen, closeModal }) => { const ReplyModal = ({ isOpen, closeModal }) => {
const { const {
captchaResponse, setCaptchaResponse, captchaResponse,
setChallengesArray, setCaptchaResponse,
setIsCaptchaOpen, setChallengesArray,
setPendingComment, setIsCaptchaOpen,
setPendingCommentIndex, setPendingComment,
replyQuoteCid, setPendingCommentIndex,
setResolveCaptchaPromise, replyQuoteCid,
selectedAddress, setResolveCaptchaPromise,
selectedParentCid, selectedAddress,
selectedShortCid, selectedParentCid,
selectedStyle, selectedShortCid,
selectedText, setSelectedText, selectedStyle,
triggerInsertion, selectedText,
} = useGeneralStore(state => state); setSelectedText,
triggerInsertion,
} = useGeneralStore((state) => state);
const { anonymousMode } = useAnonModeStore(); const { anonymousMode } = useAnonModeStore();
const account = useAccount(); const account = useAccount();
const [, setNewErrorMessage] = useError(); const [, setNewErrorMessage] = useError();
const nodeRef = useRef(null);
const nameRef = useRef();
const commentRef = useRef();
const linkRef = useRef();
const [triggerPublishComment, setTriggerPublishComment] = useState(false); const nodeRef = useRef(null);
const [isMobile, setIsMobile] = useState(window.innerWidth <= 480); const nameRef = useRef();
const [executeAnonMode, setExecuteAnonMode] = useState(false); const commentRef = useRef();
const linkRef = useRef();
useAnonMode(selectedParentCid, anonymousMode && executeAnonMode);
const [triggerPublishComment, setTriggerPublishComment] = useState(false);
const [isMobile, setIsMobile] = useState(window.innerWidth <= 480);
const [executeAnonMode, setExecuteAnonMode] = useState(false);
useEffect(() => { useAnonMode(selectedParentCid, anonymousMode && executeAnonMode);
const handleResize = () => setIsMobile(window.innerWidth <= 480);
window.addEventListener('resize', handleResize);
// Cleanup function useEffect(() => {
return () => { const handleResize = () => setIsMobile(window.innerWidth <= 480);
window.removeEventListener('resize', handleResize); window.addEventListener('resize', handleResize);
};
}, [setIsMobile]);
// Cleanup function
const onModalOpen = () => { return () => {
if (commentRef.current) { window.removeEventListener('resize', handleResize);
if (selectedText) { };
commentRef.current.value += '\n'; }, [setIsMobile]);
}
commentRef.current.focus();
const len = commentRef.current.value.length;
commentRef.current.setSelectionRange(len, len);
}
};
const insertAtCursor = (inputElement, valueToInsert) => { const onModalOpen = () => {
const startPos = inputElement.selectionStart || inputElement.value.length; if (commentRef.current) {
const endPos = startPos + valueToInsert.length; if (selectedText) {
inputElement.setRangeText(valueToInsert, startPos, startPos, 'end'); commentRef.current.value += '\n';
inputElement.setSelectionRange(endPos, endPos); }
} commentRef.current.focus();
const len = commentRef.current.value.length;
commentRef.current.setSelectionRange(len, len);
}
};
useEffect(() => { const insertAtCursor = (inputElement, valueToInsert) => {
if (replyQuoteCid && commentRef.current) { const startPos = inputElement.selectionStart || inputElement.value.length;
const prefixedReplyQuoteCid = `c/${replyQuoteCid}\n`; const endPos = startPos + valueToInsert.length;
insertAtCursor(commentRef.current, prefixedReplyQuoteCid); inputElement.setRangeText(valueToInsert, startPos, startPos, 'end');
} inputElement.setSelectionRange(endPos, endPos);
}, [triggerInsertion, replyQuoteCid]); };
const getSelectedText = useCallback(() => { useEffect(() => {
const text = document.getSelection().toString(); if (replyQuoteCid && commentRef.current) {
setSelectedText(text ? `>${text}\n` : ''); const prefixedReplyQuoteCid = `c/${replyQuoteCid}\n`;
}, [setSelectedText]); insertAtCursor(commentRef.current, prefixedReplyQuoteCid);
}
}, [triggerInsertion, replyQuoteCid]);
const getSelectedText = useCallback(() => {
const text = document.getSelection().toString();
setSelectedText(text ? `>${text}\n` : '');
}, [setSelectedText]);
useEffect(() => { useEffect(() => {
if (isOpen) { if (isOpen) {
setTimeout(getSelectedText, 0); setTimeout(getSelectedText, 0);
} else { } else {
setSelectedText(''); setSelectedText('');
} }
}, [isOpen, getSelectedText, setSelectedText]); }, [isOpen, getSelectedText, setSelectedText]);
const onChallengeVerification = (challengeVerification) => { const onChallengeVerification = (challengeVerification) => {
if (challengeVerification.challengeSuccess === true) { if (challengeVerification.challengeSuccess === true) {
return; return;
} 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 onChallenge = async (challenges, comment) => {
setPendingComment(comment);
let challengeAnswers = [];
const onChallenge = async (challenges, comment) => { try {
setPendingComment(comment); challengeAnswers = await getChallengeAnswersFromUser(challenges);
let challengeAnswers = []; } catch (error) {
setNewErrorMessage(error.message);
try { console.log(error);
challengeAnswers = await getChallengeAnswersFromUser(challenges) }
} if (challengeAnswers) {
catch (error) { await comment.publishChallengeAnswers(challengeAnswers);
setNewErrorMessage(error.message); console.log(error); }
} };
if (challengeAnswers) {
await comment.publishChallengeAnswers(challengeAnswers)
}
};
useEffect(() => {
useEffect(() => { setPublishCommentOptions((prevPublishCommentOptions) => ({
setPublishCommentOptions((prevPublishCommentOptions) => ({ ...prevPublishCommentOptions,
...prevPublishCommentOptions, subplebbitAddress: selectedAddress,
subplebbitAddress: selectedAddress, }));
})); }, [selectedAddress]);
}, [selectedAddress]);
const [publishCommentOptions, setPublishCommentOptions] = useState({
subplebbitAddress: selectedAddress,
onChallenge,
onChallengeVerification,
onError: (error) => {
setNewErrorMessage(error.message); console.log(error);
},
});
const [publishCommentOptions, setPublishCommentOptions] = useState({
subplebbitAddress: selectedAddress,
onChallenge,
onChallengeVerification,
onError: (error) => {
setNewErrorMessage(error.message);
console.log(error);
},
});
const { publishComment, index } = usePublishComment(publishCommentOptions); const { publishComment, index } = usePublishComment(publishCommentOptions);
useEffect(() => { useEffect(() => {
if (index !== undefined) { if (index !== undefined) {
setPendingCommentIndex(index); setPendingCommentIndex(index);
} }
}, [index, setPendingCommentIndex]); }, [index, setPendingCommentIndex]);
const resetFields = useCallback(() => {
const resetFields = useCallback(() => { if (nameRef.current) {
if (nameRef.current) { nameRef.current.value = '';
nameRef.current.value = ''; }
} if (commentRef.current) {
if (commentRef.current) { commentRef.current.value = '';
commentRef.current.value = ''; }
} if (linkRef.current) {
if (linkRef.current) { linkRef.current.value = '';
linkRef.current.value = ''; }
} }, []);
}, []);
const handleSubmit = async (event) => {
event.preventDefault();
const handleSubmit = async (event) => { if (commentRef.current.value === '' && linkRef.current.value === '') {
event.preventDefault(); setNewErrorMessage('Please enter a comment or link.');
return;
}
if ( setPublishCommentOptions((prevPublishCommentOptions) => ({
commentRef.current.value === "" && ...prevPublishCommentOptions,
linkRef.current.value === "" author: {
) { displayName: nameRef.current.value || undefined,
setNewErrorMessage("Please enter a comment or link."); ...(anonymousMode ? {} : { address: account?.author.address }),
return; },
} content: commentRef.current.value || undefined,
link: linkRef.current.value || undefined,
parentCid: selectedParentCid,
}));
setPublishCommentOptions((prevPublishCommentOptions) => ({ setTriggerPublishComment(true);
...prevPublishCommentOptions, };
author: {
displayName: nameRef.current.value || undefined,
...(anonymousMode ? {} : {address: account?.author.address}),
},
content: commentRef.current.value || undefined,
link: linkRef.current.value || undefined,
parentCid: selectedParentCid,
}));
setTriggerPublishComment(true);
};
const updateSigner = useCallback(async () => {
const updateSigner = useCallback(async () => { if (anonymousMode) {
if (anonymousMode) { setExecuteAnonMode(true);
setExecuteAnonMode(true);
let storedSigners = JSON.parse(localStorage.getItem('storedSigners')) || {};
let signer;
if (!storedSigners[selectedParentCid]) {
signer = await account?.plebbit.createSigner();
storedSigners[selectedParentCid] = { privateKey: signer?.privateKey, address: signer?.address };
localStorage.setItem('storedSigners', JSON.stringify(storedSigners));
} else {
const signerPrivateKey = storedSigners[selectedParentCid].privateKey;
try {
signer = await account?.plebbit.createSigner({type: 'ed25519', privateKey: signerPrivateKey});
} catch (error) {
console.log(error);
}
}
setPublishCommentOptions(prevPublishCommentOptions => {
const newPublishCommentOptions = {
...prevPublishCommentOptions,
signer,
author: {
...prevPublishCommentOptions.author,
address: signer?.address,
},
};
if (JSON.stringify(prevPublishCommentOptions) !== JSON.stringify(newPublishCommentOptions)) {
return newPublishCommentOptions;
}
return prevPublishCommentOptions;
});
}
}, [selectedParentCid, anonymousMode, account]);
useEffect(() => {
if (anonymousMode) {
updateSigner();
}
}, [updateSigner, anonymousMode]);
useEffect(() => {
if (publishCommentOptions && triggerPublishComment) {
(async () => {
await publishComment();
resetFields();
closeModal();
})();
setTriggerPublishComment(false);
setExecuteAnonMode(false);
}
}, [publishCommentOptions, triggerPublishComment, publishComment, resetFields, closeModal]);
let storedSigners = JSON.parse(localStorage.getItem('storedSigners')) || {};
let signer;
const getChallengeAnswersFromUser = async (challenges) => { if (!storedSigners[selectedParentCid]) {
setChallengesArray(challenges); signer = await account?.plebbit.createSigner();
storedSigners[selectedParentCid] = { privateKey: signer?.privateKey, address: signer?.address };
return new Promise((resolve, reject) => { localStorage.setItem('storedSigners', JSON.stringify(storedSigners));
const imageString = challenges?.challenges[0].challenge; } else {
const imageSource = `data:image/png;base64,${imageString}`; const signerPrivateKey = storedSigners[selectedParentCid].privateKey;
const challengeImg = new Image();
challengeImg.src = imageSource;
challengeImg.onload = () => {
setIsCaptchaOpen(true);
const handleKeyDown = async (event) => {
if (event.key === 'Enter') {
const currentCaptchaResponse = captchaResponse;
resolve(currentCaptchaResponse);
setIsCaptchaOpen(false);
document.removeEventListener('keydown', handleKeyDown);
event.preventDefault();
}
};
setCaptchaResponse(''); try {
document.addEventListener('keydown', handleKeyDown); signer = await account?.plebbit.createSigner({ type: 'ed25519', privateKey: signerPrivateKey });
} catch (error) {
console.log(error);
}
}
setResolveCaptchaPromise(resolve); setPublishCommentOptions((prevPublishCommentOptions) => {
}; const newPublishCommentOptions = {
...prevPublishCommentOptions,
challengeImg.onerror = () => { signer,
reject(setNewErrorMessage('Could not load challenges')); author: {
}; ...prevPublishCommentOptions.author,
}); address: signer?.address,
}; },
};
if (JSON.stringify(prevPublishCommentOptions) !== JSON.stringify(newPublishCommentOptions)) {
return newPublishCommentOptions;
}
return ( return prevPublishCommentOptions;
<StyledModal });
isOpen={isOpen} }
onAfterOpen={onModalOpen} }, [selectedParentCid, anonymousMode, account]);
onRequestClose={closeModal}
contentLabel="Reply Modal" useEffect(() => {
shouldCloseOnEsc={true} if (anonymousMode) {
shouldCloseOnOverlayClick={isMobile} updateSigner();
selectedStyle={selectedStyle} }
overlayClassName="overlay" }, [updateSigner, anonymousMode]);
style={isMobile ? ({ overlay: { backgroundColor: "rgba(0,0,0,.25)" }}) : ({ overlay: { backgroundColor: "rgba(0,0,0,0)" }})
} useEffect(() => {
> if (publishCommentOptions && triggerPublishComment) {
<Draggable handle=".modal-header" nodeRef={nodeRef} disabled={isMobile}> (async () => {
<div className="modal-content" ref={nodeRef}> await publishComment();
<div className="modal-header"> resetFields();
Reply to c/{selectedShortCid} closeModal();
<button className="icon" onClick={() => closeModal()} title="close" /> })();
</div> setTriggerPublishComment(false);
<div id="form"> setExecuteAnonMode(false);
<div> }
{account && account?.author && account?.author.displayName ? ( }, [publishCommentOptions, triggerPublishComment, publishComment, resetFields, closeModal]);
<input id="name" type="text" value={account?.author?.displayName} ref={nameRef} disabled />
) : ( const getChallengeAnswersFromUser = async (challenges) => {
<input id="name" type="text" placeholder="Anonymous" ref={nameRef} /> setChallengesArray(challenges);
)}
</div> return new Promise((resolve, reject) => {
<div> const imageString = challenges?.challenges[0].challenge;
<input id="name" type="text" placeholder="Embed link" ref={linkRef} /> const imageSource = `data:image/png;base64,${imageString}`;
</div> const challengeImg = new Image();
<div className="textarea-wrapper"> challengeImg.src = imageSource;
<span className="fixed-text">{`c/${selectedShortCid}`}</span>
<textarea className="textarea" challengeImg.onload = () => {
rows="4" setIsCaptchaOpen(true);
placeholder="Comment"
defaultValue={selectedText} const handleKeyDown = async (event) => {
wrap="soft" if (event.key === 'Enter') {
ref={commentRef} const currentCaptchaResponse = captchaResponse;
/> resolve(currentCaptchaResponse);
</div> setIsCaptchaOpen(false);
<div> document.removeEventListener('keydown', handleKeyDown);
<button id="next" onClick={handleSubmit}>Post</button> event.preventDefault();
</div> }
</div> };
</div>
</Draggable> setCaptchaResponse('');
</StyledModal> document.addEventListener('keydown', handleKeyDown);
);
setResolveCaptchaPromise(resolve);
};
challengeImg.onerror = () => {
reject(setNewErrorMessage('Could not load challenges'));
};
});
};
return (
<StyledModal
isOpen={isOpen}
onAfterOpen={onModalOpen}
onRequestClose={closeModal}
contentLabel='Reply Modal'
shouldCloseOnEsc={true}
shouldCloseOnOverlayClick={isMobile}
selectedStyle={selectedStyle}
overlayClassName='overlay'
style={isMobile ? { overlay: { backgroundColor: 'rgba(0,0,0,.25)' } } : { overlay: { backgroundColor: 'rgba(0,0,0,0)' } }}
>
<Draggable handle='.modal-header' nodeRef={nodeRef} disabled={isMobile}>
<div className='modal-content' ref={nodeRef}>
<div className='modal-header'>
Reply to c/{selectedShortCid}
<button className='icon' onClick={() => closeModal()} title='close' />
</div>
<div id='form'>
<div>
{account?.author.displayName ? (
<input id='name' type='text' defaultValue={account?.author?.displayName} ref={nameRef} />
) : (
<input id='name' type='text' placeholder='Anonymous' ref={nameRef} />
)}
</div>
<div>
<input id='name' type='text' placeholder='Embed link' ref={linkRef} />
</div>
<div className='textarea-wrapper'>
<span className='fixed-text'>{`c/${selectedShortCid}`}</span>
<textarea className='textarea' rows='4' placeholder='Comment' defaultValue={selectedText} wrap='soft' ref={commentRef} />
</div>
<div>
<button id='next' onClick={handleSubmit}>
Post
</button>
</div>
</div>
</div>
</Draggable>
</StyledModal>
);
}; };
Modal.setAppElement('#root'); Modal.setAppElement('#root');
export default ReplyModal; export default ReplyModal;
+2 -2
View File
@@ -868,8 +868,8 @@ const Board = () => {
<tr data-type='Name'> <tr data-type='Name'>
<td id='td-name'>Name</td> <td id='td-name'>Name</td>
<td> <td>
{account && account?.author && account?.author.displayName ? ( {account?.author.displayName ? (
<input name='name' type='text' tabIndex={1} value={account?.author?.displayName} ref={nameRef} disabled /> <input name='name' type='text' tabIndex={1} defaultValue={account?.author?.displayName} ref={nameRef} />
) : ( ) : (
<input name='name' type='text' placeholder='Anonymous' tabIndex={1} ref={nameRef} /> <input name='name' type='text' placeholder='Anonymous' tabIndex={1} ref={nameRef} />
)} )}
+2 -2
View File
@@ -1637,8 +1637,8 @@ const Catalog = () => {
<tr data-type='Name'> <tr data-type='Name'>
<td id='td-name'>Name</td> <td id='td-name'>Name</td>
<td> <td>
{account && account?.author && account?.author.displayName ? ( {account?.author.displayName ? (
<input name='name' type='text' tabIndex={1} value={account?.author?.displayName} ref={nameRef} disabled /> <input name='name' type='text' tabIndex={1} defaultValue={account?.author?.displayName} ref={nameRef} />
) : ( ) : (
<input name='name' type='text' placeholder='Anonymous' tabIndex={1} ref={nameRef} /> <input name='name' type='text' placeholder='Anonymous' tabIndex={1} ref={nameRef} />
)} )}
+2 -2
View File
@@ -839,8 +839,8 @@ const Thread = () => {
<tr data-type='Name'> <tr data-type='Name'>
<td id='td-name'>Name</td> <td id='td-name'>Name</td>
<td> <td>
{account && account?.author && account?.author.displayName ? ( {account?.author.displayName ? (
<input name='name' type='text' tabIndex={1} value={account?.author?.displayName} ref={nameRef} disabled /> <input name='name' type='text' tabIndex={1} defaultValue={account?.author?.displayName} ref={nameRef} />
) : ( ) : (
<input name='name' type='text' placeholder='Anonymous' tabIndex={1} ref={nameRef} /> <input name='name' type='text' placeholder='Anonymous' tabIndex={1} ref={nameRef} />
)} )}