Skip to content

Commit d84fcf5

Browse files
authored
Merge pull request #50 from frontend-opensource-project/URH-67/use-prevent-copy
[URH-67] usePreventCopy 신규
2 parents dc21375 + 61fcd33 commit d84fcf5

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

src/hooks/usePreventCopy.test.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { act, renderHook } from '@testing-library/react';
2+
import usePreventCopy from './usePreventCopy';
3+
4+
describe('usePreventCopy', () => {
5+
it("'copy' 이벤트가 발생하면 기본 동작을 차단하고, 콜백 함수가 호출된다.", () => {
6+
const callback = jest.fn();
7+
8+
renderHook(() => usePreventCopy(callback));
9+
10+
const copyEvent = new Event('copy', {
11+
bubbles: true,
12+
cancelable: true,
13+
}) as ClipboardEvent;
14+
15+
act(() => {
16+
window.dispatchEvent(copyEvent);
17+
});
18+
19+
expect(copyEvent.defaultPrevented).toBe(true);
20+
expect(callback).toHaveBeenCalledTimes(1);
21+
});
22+
23+
it("'cut' 이벤트가 발생하면 기본 동작을 차단하고, 콜백 함수가 호출된다.", () => {
24+
const callback = jest.fn();
25+
26+
renderHook(() => usePreventCopy(callback));
27+
28+
const cutEvent = new Event('cut', {
29+
bubbles: true,
30+
cancelable: true,
31+
}) as ClipboardEvent;
32+
33+
act(() => {
34+
window.dispatchEvent(cutEvent);
35+
});
36+
37+
expect(cutEvent.defaultPrevented).toBe(true);
38+
expect(callback).toHaveBeenCalledTimes(1);
39+
});
40+
});

src/hooks/usePreventCopy.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { useEffect } from 'react';
2+
3+
/**
4+
* 브라우저에서 복사 이벤트를 차단하는 훅
5+
*
6+
* @param {VoidFunction} callback - 복사 이벤트가 발생할 때 실행될 콜백 함수
7+
*
8+
* @description 복사 이벤트를 차단하고 콜백 함수를 실행합니다.
9+
*/
10+
const usePreventCopy = (callback?: () => void) => {
11+
const preventCopy = (e: ClipboardEvent) => {
12+
e.preventDefault();
13+
callback?.();
14+
};
15+
16+
useEffect(() => {
17+
// TODO: useEventListener 적용하기
18+
window.addEventListener('copy', preventCopy);
19+
window.addEventListener('cut', preventCopy);
20+
return () => {
21+
window.removeEventListener('copy', preventCopy);
22+
window.removeEventListener('cut', preventCopy);
23+
};
24+
// eslint-disable-next-line react-hooks/exhaustive-deps
25+
}, []);
26+
};
27+
28+
export default usePreventCopy;

0 commit comments

Comments
 (0)