BlockMenu.hooks.ts 867 B

123456789101112131415161718192021222324252627282930
  1. import { documentActions } from '@/appflowy_app/stores/reducers/document/slice';
  2. import { useAppDispatch } from '@/appflowy_app/stores/store';
  3. import { useRef, useState, useEffect } from 'react';
  4. export function useBlockMenu(nodeId: string, open: boolean) {
  5. const ref = useRef<HTMLDivElement | null>(null);
  6. const dispatch = useAppDispatch();
  7. const [style, setStyle] = useState({ top: '0px', left: '0px' });
  8. useEffect(() => {
  9. if (!open) {
  10. return;
  11. }
  12. // set selection when open
  13. dispatch(documentActions.setSelectionById(nodeId));
  14. // get node rect
  15. const rect = document.querySelector(`[data-block-id="${nodeId}"]`)?.getBoundingClientRect();
  16. if (!rect) return;
  17. // set menu position
  18. setStyle({
  19. top: rect.top + 'px',
  20. left: rect.left + 'px',
  21. });
  22. }, [open, nodeId]);
  23. return {
  24. ref,
  25. style,
  26. };
  27. }