TableWithEditButton.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import React, { useCallback, type JSX } from 'react';
  2. import { globalEventTarget } from '@growi/core/dist/utils';
  3. import type { Element } from 'hast';
  4. import type { LaunchHandsonTableModalEventDetail } from '~/client/interfaces/handsontable-modal';
  5. import {
  6. useIsGuestUser, useIsReadOnlyUser, useIsSharedUser, useShareLinkId,
  7. } from '~/stores-universal/context';
  8. import { useIsRevisionOutdated } from '~/stores/page';
  9. import { useCurrentPageYjsData } from '~/stores/yjs';
  10. import styles from './TableWithEditButton.module.scss';
  11. type TableWithEditButtonProps = {
  12. children: React.ReactNode,
  13. node: Element,
  14. className?: string
  15. }
  16. const TableWithEditButtonNoMemorized = (props: TableWithEditButtonProps): JSX.Element => {
  17. const { children, node, className } = props;
  18. const { data: isGuestUser } = useIsGuestUser();
  19. const { data: isReadOnlyUser } = useIsReadOnlyUser();
  20. const { data: isSharedUser } = useIsSharedUser();
  21. const { data: shareLinkId } = useShareLinkId();
  22. const { data: isRevisionOutdated } = useIsRevisionOutdated();
  23. const { data: currentPageYjsData } = useCurrentPageYjsData();
  24. const bol = node.position?.start.line ?? 0;
  25. const eol = node.position?.end.line ?? 0;
  26. const editButtonClickHandler = useCallback(() => {
  27. globalEventTarget.dispatchEvent(new CustomEvent<LaunchHandsonTableModalEventDetail>('launchHandsonTableModal', {
  28. detail: {
  29. bol,
  30. eol,
  31. },
  32. }));
  33. }, [bol, eol]);
  34. const isNoEditingUsers = currentPageYjsData?.awarenessStateSize == null || currentPageYjsData?.awarenessStateSize === 0;
  35. const showEditButton = isNoEditingUsers
  36. && !isRevisionOutdated
  37. && !isGuestUser
  38. && !isReadOnlyUser
  39. && !isSharedUser
  40. && shareLinkId == null;
  41. return (
  42. <div className={`editable-with-handsontable ${styles['editable-with-handsontable']}`}>
  43. { showEditButton && (
  44. <button type="button" className="handsontable-modal-trigger" onClick={editButtonClickHandler}>
  45. <span className="material-symbols-outlined">edit_square</span>
  46. </button>
  47. )}
  48. <table className={className}>
  49. {children}
  50. </table>
  51. </div>
  52. );
  53. };
  54. TableWithEditButtonNoMemorized.displayName = 'TableWithEditButton';
  55. export const TableWithEditButton = React.memo(TableWithEditButtonNoMemorized) as typeof TableWithEditButtonNoMemorized;