Files
5chan/src/hooks/use-publish-reply.ts
T

76 lines
2.6 KiB
TypeScript
Raw Normal View History

import { useCallback } from 'react';
2024-11-05 12:02:01 +01:00
import { Comment, useAccount, usePublishComment } from '@plebbit/plebbit-react-hooks';
2024-08-07 16:25:53 +02:00
import useAnonMode from './use-anon-mode';
2024-11-05 12:02:01 +01:00
import usePublishReplyStore from '../stores/use-publish-reply-store';
const usePublishReply = ({ cid, subplebbitAddress, postCid }: { cid: string; subplebbitAddress: string; postCid?: string }) => {
const parentCid = cid;
2024-09-19 21:07:45 +02:00
const account = useAccount();
const { anonMode } = useAnonMode(postCid);
2024-09-19 21:07:45 +02:00
const { author, signer, content, link, spoiler, publishCommentOptions } = usePublishReplyStore((state) => ({
author: state.author[parentCid],
signer: state.signer[parentCid] || undefined,
content: state.content[parentCid] || undefined,
link: state.link[parentCid] || undefined,
2024-09-19 21:07:45 +02:00
spoiler: state.spoiler[parentCid] || false,
publishCommentOptions: state.publishCommentOptions[parentCid],
}));
2025-01-30 17:27:58 +01:00
const setPublishReplyStore = usePublishReplyStore((state) => state.setPublishReplyStore);
const resetPublishReplyStore = usePublishReplyStore((state) => state.resetPublishReplyStore);
const createBaseOptions = useCallback(() => {
const baseOptions: Comment = {
subplebbitAddress,
parentCid,
postCid: postCid ?? parentCid,
content,
link,
spoiler,
};
if (anonMode) {
baseOptions.author = {
address: signer?.address,
displayName: author?.displayName,
};
baseOptions.signer = signer;
} else {
baseOptions.author = {
...account?.author,
displayName: author?.displayName || account?.author?.displayName,
};
}
return baseOptions;
}, [anonMode, author, content, link, parentCid, postCid, signer, spoiler, subplebbitAddress, account]);
const setPublishReplyOptions = useCallback(
(options: Partial<Comment>) => {
const baseOptions = createBaseOptions();
const sanitizedOptions = Object.entries(options).reduce((acc, [key, value]) => {
acc[key] = value === '' ? undefined : value;
return acc;
}, {} as Partial<Comment>);
2024-08-30 12:08:53 +02:00
const newOptions = { ...baseOptions, ...sanitizedOptions };
2025-01-30 17:27:58 +01:00
setPublishReplyStore(newOptions);
},
2025-01-30 17:27:58 +01:00
[createBaseOptions, setPublishReplyStore],
);
2025-01-30 17:27:58 +01:00
const resetPublishReplyOptions = useCallback(() => resetPublishReplyStore(parentCid), [parentCid, resetPublishReplyStore]);
const { index, publishComment } = usePublishComment(publishCommentOptions);
return {
setPublishReplyOptions,
resetPublishReplyOptions,
replyIndex: index,
publishReply: publishComment,
};
};
export default usePublishReply;