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

65 lines
2.1 KiB
TypeScript
Raw Normal View History

2025-01-30 17:09:21 +01:00
import { useCallback } from 'react';
import { Comment, useAccount, usePublishComment } from '@plebbit/plebbit-react-hooks';
import usePublishPostStore from '../stores/use-publish-post-store';
const usePublishPost = ({ subplebbitAddress }: { subplebbitAddress?: string }) => {
const account = useAccount();
2025-11-25 13:13:38 +01:00
const { author, title, content, link, spoiler, publishCommentOptions } = usePublishPostStore((state) => ({
2025-01-30 17:09:21 +01:00
author: state.author,
2025-01-30 17:27:58 +01:00
title: state.title || undefined,
content: state.content || undefined,
link: state.link || undefined,
2025-01-30 17:09:21 +01:00
spoiler: state.spoiler || false,
publishCommentOptions: state.publishCommentOptions,
}));
const setPublishPostStore = usePublishPostStore((state) => state.setPublishPostStore);
const resetPublishPostStore = usePublishPostStore((state) => state.resetPublishPostStore);
const createBaseOptions = useCallback(() => {
const baseOptions: Comment = {
subplebbitAddress,
title,
content,
link,
spoiler,
};
2025-11-25 13:13:38 +01:00
baseOptions.author = {
...account?.author,
displayName: author?.displayName || account?.author?.displayName,
};
2025-01-30 17:09:21 +01:00
return baseOptions;
2025-11-25 13:13:38 +01:00
}, [author, content, link, spoiler, subplebbitAddress, title, account]);
2025-01-30 17:09:21 +01:00
const setPublishPostOptions = 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>);
const newOptions = { ...baseOptions, ...sanitizedOptions };
setPublishPostStore(newOptions);
},
[createBaseOptions, setPublishPostStore],
);
const resetPublishPostOptions = useCallback(() => resetPublishPostStore(), [resetPublishPostStore]);
const { index, publishComment } = usePublishComment(publishCommentOptions);
return {
setPublishPostOptions,
resetPublishPostOptions,
postIndex: index,
publishPost: publishComment,
publishPostOptions: publishCommentOptions,
};
};
export default usePublishPost;