ForumSudo.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import React, { useContext, createContext } from 'react';
  2. import { JoyError } from '@polkadot/joy-utils/react/components';
  3. import { withMulti } from '@polkadot/react-api/hoc';
  4. import { Option } from '@polkadot/types/codec';
  5. import { useMyAccount } from '@polkadot/joy-utils/react/hooks';
  6. import { AccountId } from '@polkadot/types/interfaces';
  7. import AddressMini from '@polkadot/react-components/AddressMini';
  8. import { withForumCalls } from './calls';
  9. type LoadStructProps = {
  10. structOpt: Option<AccountId>;
  11. };
  12. const withLoadForumSudo = withForumCalls<LoadStructProps>(
  13. ['forumSudo', { propName: 'structOpt' }]
  14. );
  15. function innerWithOnlyForumSudo<P extends LoadStructProps> (Component: React.ComponentType<P>) {
  16. return function (props: P) {
  17. const { structOpt } = props;
  18. if (!structOpt) {
  19. return <em>Loading forum sudo...</em>;
  20. }
  21. const sudo = structOpt.isSome ? structOpt.unwrap().toString() : undefined;
  22. const { state: { address: myAddress } } = useMyAccount();
  23. const iAmForumSudo = sudo === myAddress;
  24. if (iAmForumSudo) {
  25. return <Component {...props} />;
  26. } else {
  27. return (
  28. <JoyError title={'Only forum sudo can access this functionality.'}>
  29. <div>Current forum sudo:</div>
  30. <div>{sudo ? <AddressMini value={sudo} /> : 'UNDEFINED'}</div>
  31. </JoyError>
  32. );
  33. }
  34. };
  35. }
  36. export function withOnlyForumSudo<P extends Record<string, unknown>> (Component: React.ComponentType<P>) {
  37. return withMulti(
  38. Component,
  39. withLoadForumSudo,
  40. innerWithOnlyForumSudo
  41. );
  42. }
  43. type ForumSudoContextProps = {
  44. forumSudo?: AccountId;
  45. };
  46. export const ForumSudoContext = createContext<ForumSudoContextProps>({});
  47. export function InnerForumSudoProvider (props: React.PropsWithChildren<LoadStructProps>) {
  48. const { structOpt } = props;
  49. const forumSudo = structOpt ? structOpt.unwrapOr(undefined) : undefined;
  50. return (
  51. <ForumSudoContext.Provider value={{ forumSudo }}>
  52. {props.children}
  53. </ForumSudoContext.Provider>
  54. );
  55. }
  56. export const ForumSudoProvider = withMulti(
  57. InnerForumSudoProvider,
  58. withLoadForumSudo
  59. );
  60. export function useForumSudo () {
  61. return useContext(ForumSudoContext);
  62. }
  63. export const IfIAmForumSudo = (props: React.PropsWithChildren<Record<any, unknown>>) => {
  64. const { forumSudo } = useForumSudo();
  65. const { state: { address: myAddress } } = useMyAccount();
  66. const iAmForumSudo: boolean = forumSudo !== undefined && forumSudo.eq(myAddress);
  67. return iAmForumSudo ? <>{props.children}</> : null;
  68. };