/ src / hooks / use-author-privileges.ts
use-author-privileges.ts
 1  import { useMemo } from 'react';
 2  import { useAccount, useSubplebbit } from '@plebbit/plebbit-react-hooks';
 3  import useAnonModeStore from '../stores/use-anon-mode-store';
 4  import useAnonMode from './use-anon-mode';
 5  
 6  interface AuthorPrivilegesProps {
 7    commentAuthorAddress: string;
 8    subplebbitAddress: string;
 9    postCid?: string;
10  }
11  
12  const useAuthorPrivileges = ({ commentAuthorAddress, subplebbitAddress, postCid }: AuthorPrivilegesProps) => {
13    const account = useAccount();
14    const accountAuthorAddress = account?.author?.address;
15    const { roles } = useSubplebbit({ subplebbitAddress }) || {};
16    const { getAddressSigner, getThreadSigner } = useAnonModeStore();
17    const { anonMode } = useAnonMode(postCid);
18  
19    const { isCommentAuthorMod, isAccountMod, isAccountCommentAuthor, commentAuthorRole, accountAuthorRole } = useMemo(() => {
20      const commentAuthorRole = roles?.[commentAuthorAddress]?.role;
21      const isCommentAuthorMod = commentAuthorRole === 'admin' || commentAuthorRole === 'owner' || commentAuthorRole === 'moderator';
22      const accountAuthorRole = roles?.[accountAuthorAddress]?.role;
23      const isAccountMod = accountAuthorRole === 'admin' || accountAuthorRole === 'owner' || accountAuthorRole === 'moderator';
24  
25      let isAccountCommentAuthor = accountAuthorAddress === commentAuthorAddress;
26  
27      if (!isAccountCommentAuthor && anonMode) {
28        const addressSigner = getAddressSigner(commentAuthorAddress);
29        const threadSigner = postCid ? getThreadSigner(postCid) : null;
30  
31        isAccountCommentAuthor = (addressSigner && addressSigner.address === commentAuthorAddress) || (threadSigner && threadSigner.address === commentAuthorAddress);
32      }
33  
34      return { isCommentAuthorMod, isAccountMod, isAccountCommentAuthor, commentAuthorRole, accountAuthorRole };
35    }, [roles, commentAuthorAddress, accountAuthorAddress, anonMode, getAddressSigner, getThreadSigner, postCid]);
36  
37    return { isCommentAuthorMod, isAccountMod, isAccountCommentAuthor, commentAuthorRole, accountAuthorRole };
38  };
39  
40  export default useAuthorPrivileges;