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
+259 -281
View File
@@ -8,330 +8,308 @@ 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 nodeRef = useRef(null);
const nameRef = useRef(); const nameRef = useRef();
const commentRef = useRef(); const commentRef = useRef();
const linkRef = useRef(); const linkRef = useRef();
const [triggerPublishComment, setTriggerPublishComment] = useState(false); const [triggerPublishComment, setTriggerPublishComment] = useState(false);
const [isMobile, setIsMobile] = useState(window.innerWidth <= 480); const [isMobile, setIsMobile] = useState(window.innerWidth <= 480);
const [executeAnonMode, setExecuteAnonMode] = useState(false); const [executeAnonMode, setExecuteAnonMode] = useState(false);
useAnonMode(selectedParentCid, anonymousMode && executeAnonMode); useAnonMode(selectedParentCid, anonymousMode && executeAnonMode);
useEffect(() => {
const handleResize = () => setIsMobile(window.innerWidth <= 480);
window.addEventListener('resize', handleResize);
useEffect(() => { // Cleanup function
const handleResize = () => setIsMobile(window.innerWidth <= 480); return () => {
window.addEventListener('resize', handleResize); window.removeEventListener('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 startPos = inputElement.selectionStart || inputElement.value.length;
const endPos = startPos + valueToInsert.length;
inputElement.setRangeText(valueToInsert, startPos, startPos, 'end');
inputElement.setSelectionRange(endPos, endPos);
};
const onModalOpen = () => { useEffect(() => {
if (commentRef.current) { if (replyQuoteCid && commentRef.current) {
if (selectedText) { const prefixedReplyQuoteCid = `c/${replyQuoteCid}\n`;
commentRef.current.value += '\n'; insertAtCursor(commentRef.current, prefixedReplyQuoteCid);
} }
commentRef.current.focus(); }, [triggerInsertion, replyQuoteCid]);
const len = commentRef.current.value.length;
commentRef.current.setSelectionRange(len, len);
}
};
const getSelectedText = useCallback(() => {
const text = document.getSelection().toString();
setSelectedText(text ? `>${text}\n` : '');
}, [setSelectedText]);
const insertAtCursor = (inputElement, valueToInsert) => { useEffect(() => {
const startPos = inputElement.selectionStart || inputElement.value.length; if (isOpen) {
const endPos = startPos + valueToInsert.length; setTimeout(getSelectedText, 0);
inputElement.setRangeText(valueToInsert, startPos, startPos, 'end'); } else {
inputElement.setSelectionRange(endPos, endPos); setSelectedText('');
} }
}, [isOpen, getSelectedText, setSelectedText]);
useEffect(() => { const onChallengeVerification = (challengeVerification) => {
if (replyQuoteCid && commentRef.current) { if (challengeVerification.challengeSuccess === true) {
const prefixedReplyQuoteCid = `c/${replyQuoteCid}\n`; return;
insertAtCursor(commentRef.current, prefixedReplyQuoteCid); } else if (challengeVerification.challengeSuccess === false) {
} setNewErrorMessage(`Challenge Failed, reason: ${challengeVerification.reason}. Errors: ${challengeVerification.errors}`);
}, [triggerInsertion, replyQuoteCid]); console.log('challenge failed', challengeVerification);
}
};
const onChallenge = async (challenges, comment) => {
setPendingComment(comment);
let challengeAnswers = [];
const getSelectedText = useCallback(() => { try {
const text = document.getSelection().toString(); challengeAnswers = await getChallengeAnswersFromUser(challenges);
setSelectedText(text ? `>${text}\n` : ''); } catch (error) {
}, [setSelectedText]); setNewErrorMessage(error.message);
console.log(error);
}
if (challengeAnswers) {
await comment.publishChallengeAnswers(challengeAnswers);
}
};
useEffect(() => {
setPublishCommentOptions((prevPublishCommentOptions) => ({
...prevPublishCommentOptions,
subplebbitAddress: selectedAddress,
}));
}, [selectedAddress]);
useEffect(() => { const [publishCommentOptions, setPublishCommentOptions] = useState({
if (isOpen) { subplebbitAddress: selectedAddress,
setTimeout(getSelectedText, 0); onChallenge,
} else { onChallengeVerification,
setSelectedText(''); onError: (error) => {
} setNewErrorMessage(error.message);
}, [isOpen, getSelectedText, setSelectedText]); console.log(error);
},
});
const { publishComment, index } = usePublishComment(publishCommentOptions);
const onChallengeVerification = (challengeVerification) => { useEffect(() => {
if (challengeVerification.challengeSuccess === true) { if (index !== undefined) {
return; setPendingCommentIndex(index);
} else if (challengeVerification.challengeSuccess === false) { }
setNewErrorMessage(`Challenge Failed, reason: ${challengeVerification.reason}. Errors: ${challengeVerification.errors}`); }, [index, setPendingCommentIndex]);
console.log('challenge failed', challengeVerification);
}
};
const resetFields = useCallback(() => {
if (nameRef.current) {
nameRef.current.value = '';
}
if (commentRef.current) {
commentRef.current.value = '';
}
if (linkRef.current) {
linkRef.current.value = '';
}
}, []);
const onChallenge = async (challenges, comment) => { const handleSubmit = async (event) => {
setPendingComment(comment); event.preventDefault();
let challengeAnswers = [];
try { if (commentRef.current.value === '' && linkRef.current.value === '') {
challengeAnswers = await getChallengeAnswersFromUser(challenges) setNewErrorMessage('Please enter a comment or link.');
} return;
catch (error) { }
setNewErrorMessage(error.message); console.log(error);
}
if (challengeAnswers) {
await comment.publishChallengeAnswers(challengeAnswers)
}
};
setPublishCommentOptions((prevPublishCommentOptions) => ({
...prevPublishCommentOptions,
author: {
displayName: nameRef.current.value || undefined,
...(anonymousMode ? {} : { address: account?.author.address }),
},
content: commentRef.current.value || undefined,
link: linkRef.current.value || undefined,
parentCid: selectedParentCid,
}));
useEffect(() => { setTriggerPublishComment(true);
setPublishCommentOptions((prevPublishCommentOptions) => ({ };
...prevPublishCommentOptions,
subplebbitAddress: selectedAddress,
}));
}, [selectedAddress]);
const updateSigner = useCallback(async () => {
if (anonymousMode) {
setExecuteAnonMode(true);
const [publishCommentOptions, setPublishCommentOptions] = useState({ let storedSigners = JSON.parse(localStorage.getItem('storedSigners')) || {};
subplebbitAddress: selectedAddress, let signer;
onChallenge,
onChallengeVerification,
onError: (error) => {
setNewErrorMessage(error.message); console.log(error);
},
});
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;
const { publishComment, index } = usePublishComment(publishCommentOptions); try {
signer = await account?.plebbit.createSigner({ type: 'ed25519', privateKey: signerPrivateKey });
} catch (error) {
console.log(error);
}
}
useEffect(() => { setPublishCommentOptions((prevPublishCommentOptions) => {
if (index !== undefined) { const newPublishCommentOptions = {
setPendingCommentIndex(index); ...prevPublishCommentOptions,
} signer,
}, [index, setPendingCommentIndex]); author: {
...prevPublishCommentOptions.author,
address: signer?.address,
},
};
if (JSON.stringify(prevPublishCommentOptions) !== JSON.stringify(newPublishCommentOptions)) {
return newPublishCommentOptions;
}
const resetFields = useCallback(() => { return prevPublishCommentOptions;
if (nameRef.current) { });
nameRef.current.value = ''; }
} }, [selectedParentCid, anonymousMode, account]);
if (commentRef.current) {
commentRef.current.value = '';
}
if (linkRef.current) {
linkRef.current.value = '';
}
}, []);
useEffect(() => {
if (anonymousMode) {
updateSigner();
}
}, [updateSigner, anonymousMode]);
const handleSubmit = async (event) => { useEffect(() => {
event.preventDefault(); if (publishCommentOptions && triggerPublishComment) {
(async () => {
await publishComment();
resetFields();
closeModal();
})();
setTriggerPublishComment(false);
setExecuteAnonMode(false);
}
}, [publishCommentOptions, triggerPublishComment, publishComment, resetFields, closeModal]);
if ( const getChallengeAnswersFromUser = async (challenges) => {
commentRef.current.value === "" && setChallengesArray(challenges);
linkRef.current.value === ""
) {
setNewErrorMessage("Please enter a comment or link.");
return;
}
setPublishCommentOptions((prevPublishCommentOptions) => ({ return new Promise((resolve, reject) => {
...prevPublishCommentOptions, const imageString = challenges?.challenges[0].challenge;
author: { const imageSource = `data:image/png;base64,${imageString}`;
displayName: nameRef.current.value || undefined, const challengeImg = new Image();
...(anonymousMode ? {} : {address: account?.author.address}), challengeImg.src = imageSource;
},
content: commentRef.current.value || undefined,
link: linkRef.current.value || undefined,
parentCid: selectedParentCid,
}));
setTriggerPublishComment(true); 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();
}
};
const updateSigner = useCallback(async () => { setCaptchaResponse('');
if (anonymousMode) { document.addEventListener('keydown', handleKeyDown);
setExecuteAnonMode(true);
let storedSigners = JSON.parse(localStorage.getItem('storedSigners')) || {}; setResolveCaptchaPromise(resolve);
let signer; };
if (!storedSigners[selectedParentCid]) { challengeImg.onerror = () => {
signer = await account?.plebbit.createSigner(); reject(setNewErrorMessage('Could not load challenges'));
storedSigners[selectedParentCid] = { privateKey: signer?.privateKey, address: signer?.address }; };
localStorage.setItem('storedSigners', JSON.stringify(storedSigners)); });
} else { };
const signerPrivateKey = storedSigners[selectedParentCid].privateKey;
try { return (
signer = await account?.plebbit.createSigner({type: 'ed25519', privateKey: signerPrivateKey}); <StyledModal
} catch (error) { isOpen={isOpen}
console.log(error); onAfterOpen={onModalOpen}
} onRequestClose={closeModal}
} contentLabel='Reply Modal'
shouldCloseOnEsc={true}
setPublishCommentOptions(prevPublishCommentOptions => { shouldCloseOnOverlayClick={isMobile}
const newPublishCommentOptions = { selectedStyle={selectedStyle}
...prevPublishCommentOptions, overlayClassName='overlay'
signer, style={isMobile ? { overlay: { backgroundColor: 'rgba(0,0,0,.25)' } } : { overlay: { backgroundColor: 'rgba(0,0,0,0)' } }}
author: { >
...prevPublishCommentOptions.author, <Draggable handle='.modal-header' nodeRef={nodeRef} disabled={isMobile}>
address: signer?.address, <div className='modal-content' ref={nodeRef}>
}, <div className='modal-header'>
}; Reply to c/{selectedShortCid}
<button className='icon' onClick={() => closeModal()} title='close' />
if (JSON.stringify(prevPublishCommentOptions) !== JSON.stringify(newPublishCommentOptions)) { </div>
return newPublishCommentOptions; <div id='form'>
} <div>
{account?.author.displayName ? (
return prevPublishCommentOptions; <input id='name' type='text' defaultValue={account?.author?.displayName} ref={nameRef} />
}); ) : (
} <input id='name' type='text' placeholder='Anonymous' ref={nameRef} />
}, [selectedParentCid, anonymousMode, account]); )}
</div>
useEffect(() => { <div>
if (anonymousMode) { <input id='name' type='text' placeholder='Embed link' ref={linkRef} />
updateSigner(); </div>
} <div className='textarea-wrapper'>
}, [updateSigner, anonymousMode]); <span className='fixed-text'>{`c/${selectedShortCid}`}</span>
<textarea className='textarea' rows='4' placeholder='Comment' defaultValue={selectedText} wrap='soft' ref={commentRef} />
</div>
useEffect(() => { <div>
if (publishCommentOptions && triggerPublishComment) { <button id='next' onClick={handleSubmit}>
(async () => { Post
await publishComment(); </button>
resetFields(); </div>
closeModal(); </div>
})(); </div>
setTriggerPublishComment(false); </Draggable>
setExecuteAnonMode(false); </StyledModal>
} );
}, [publishCommentOptions, triggerPublishComment, publishComment, resetFields, closeModal]);
const getChallengeAnswersFromUser = async (challenges) => {
setChallengesArray(challenges);
return new Promise((resolve, reject) => {
const imageString = challenges?.challenges[0].challenge;
const imageSource = `data:image/png;base64,${imageString}`;
const challengeImg = new Image();
challengeImg.src = imageSource;
challengeImg.onload = () => {
setIsCaptchaOpen(true);
const handleKeyDown = async (event) => {
if (event.key === 'Enter') {
const currentCaptchaResponse = captchaResponse;
resolve(currentCaptchaResponse);
setIsCaptchaOpen(false);
document.removeEventListener('keydown', handleKeyDown);
event.preventDefault();
}
};
setCaptchaResponse('');
document.addEventListener('keydown', handleKeyDown);
setResolveCaptchaPromise(resolve);
};
challengeImg.onerror = () => {
reject(setNewErrorMessage('Could not load challenges'));
};
});
};
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 && account?.author && account?.author.displayName ? (
<input id="name" type="text" value={account?.author?.displayName} ref={nameRef} disabled />
) : (
<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');
+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} />
)} )}