All files / src/plugins useCopied.tsx

28.57% Statements 6/21
0% Branches 0/10
42.85% Functions 3/7
31.57% Lines 6/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36                                4x                   4x 3x 3x 3x 2x          
import copyTextToClipboard from '@uiw/copy-to-clipboard';
import { useEffect } from 'react';
 
function getParentElement(target: EventTarget | null): null | HTMLElement {
  if (!target) return null;
  const dom = target as HTMLElement;
  if (dom.dataset.code && dom.classList.contains('copied')) {
    return dom;
  }
  if (dom.parentElement) {
    return getParentElement(dom.parentElement);
  }
  return null;
}
 
export function useCopied(container: React.RefObject<HTMLDivElement>) {
  const handle = (event: Event) => {
    const target = getParentElement(event.target);
    if (!target) return;
    target.classList.add('active');
    copyTextToClipboard(target.dataset.code as string, function () {
      setTimeout(() => {
        target.classList.remove('active');
      }, 2000);
    });
  };
  useEffect(() => {
    container.current?.removeEventListener('click', handle, false);
    container.current?.addEventListener('click', handle, false);
    return () => {
      container.current?.removeEventListener('click', handle, false);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [container]);
}