-
Notifications
You must be signed in to change notification settings - Fork 0
[URH-42] useDetectInactivity 신규 #36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
2ee6d3e
✨ feat: useDetectInactivity기본 로직 작성
foresec 9c87c7c
✨ feat: 터치이벤트 수행여부를 감지, 동록 이벤트를 구분하는 로직 추가
foresec 6c47cd1
🔨 refactor: 매개변수 default값 삭제
foresec b15a968
💬 comment: useDetectInactivity jsdocs작성
foresec 093d0f1
✅ test: useDetectInactivity 테스트코드 작성
foresec 7936cfd
✅ test: 테스트코드 필요 없는 코드 정리
foresec 265c255
🔨 refactor: isInactive가 true일때만 상태 재설정
foresec 125dc2d
✨ feat: 이벤트리스너 주기에 throttle적용
foresec 90b1445
🔨 refactor: useCallback 정리
foresec 863e100
🔨 refactor: useMousePosition에서 throttle을 util로 분리
foresec bad8002
✨ feat: throttle시간보다 time이 작은 경우 검증
foresec 721453f
💬 comment: throttle에 대한 jsdocs 수정
foresec ed901bf
🔨 refactor: throttle함수 이벤트만 받는 형태에서 일반콜백함수로 확장
foresec e6ce675
🚚 rename: genericCallback을 GenericFn으로 변경, 타입 분리
foresec a68b5e5
✨ feat: time 재설정시 동적으로 반영되도록 의존성 배열 추가
foresec e64ec91
🩹 chore: throw error 문구 한국어로 전환
foresec 441daf9
🔨 refactor: isClient util함수로 분리
foresec fcdc103
🔨 refactor: isTouchDevice util함수로 분리
foresec File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
import { act, renderHook } from '@testing-library/react'; | ||
import useDetectInactivity, { isTouchDevice } from './useDetectInactivity'; | ||
import useTimer from './useTimer'; | ||
|
||
jest.mock('./useTimer'); | ||
|
||
describe('useDetectInactivity', () => { | ||
let startMock: jest.Mock; | ||
let onInactivityMock: jest.Mock; | ||
|
||
beforeEach(() => { | ||
jest.useFakeTimers(); | ||
startMock = jest.fn(); | ||
onInactivityMock = jest.fn(); | ||
(useTimer as jest.Mock).mockImplementation((callback, time) => ({ | ||
start: () => { | ||
startMock(); | ||
setTimeout(() => { | ||
callback(); | ||
}, time); | ||
}, | ||
})); | ||
}); | ||
|
||
afterEach(() => { | ||
jest.clearAllTimers(); | ||
jest.clearAllMocks(); | ||
}); | ||
|
||
afterAll(() => { | ||
jest.useRealTimers(); | ||
}); | ||
|
||
test('타이머에 설정된 시간 후에는 비활동 상태가 감지된다.', () => { | ||
const { result } = renderHook(() => | ||
useDetectInactivity(5000, onInactivityMock) | ||
); | ||
act(() => { | ||
jest.advanceTimersByTime(5000); | ||
}); | ||
|
||
expect(onInactivityMock).toHaveBeenCalled(); | ||
expect(result.current).toBe(true); | ||
}); | ||
|
||
test('비활동 상태일때 onInactivity콜백은 호출되지 않는다.', () => { | ||
renderHook(() => useDetectInactivity(5000, onInactivityMock)); | ||
|
||
act(() => { | ||
jest.advanceTimersByTime(4500); | ||
}); | ||
|
||
expect(onInactivityMock).not.toHaveBeenCalled(); | ||
}); | ||
|
||
test('활동(설정된 이벤트)이 감지되면 타이머는 리셋된 후 다시 실행된다.', () => { | ||
const { result } = renderHook(() => | ||
useDetectInactivity(5000, onInactivityMock) | ||
); | ||
|
||
act(() => { | ||
jest.advanceTimersByTime(3000); | ||
}); | ||
|
||
expect(startMock).toHaveBeenCalledTimes(1); | ||
expect(result.current).toBe(false); | ||
|
||
act(() => { | ||
window.dispatchEvent(new Event('keyup')); | ||
}); | ||
|
||
expect(startMock).toHaveBeenCalledTimes(1); | ||
expect(result.current).toBe(false); | ||
|
||
act(() => { | ||
window.dispatchEvent(new Event('mousemove')); | ||
}); | ||
|
||
expect(startMock).toHaveBeenCalledTimes(2); | ||
expect(result.current).toBe(false); | ||
|
||
act(() => { | ||
jest.advanceTimersByTime(5000); | ||
}); | ||
|
||
expect(onInactivityMock).toHaveBeenCalled(); | ||
expect(result.current).toBe(true); | ||
}); | ||
|
||
test('환경에 맞게 이벤트 리스너가 추가/제거된다.', () => { | ||
const addEventListenerSpy = jest.spyOn(window, 'addEventListener'); | ||
const removeEventListenerSpy = jest.spyOn(window, 'removeEventListener'); | ||
|
||
const { unmount } = renderHook(() => | ||
useDetectInactivity(5000, onInactivityMock) | ||
); | ||
|
||
const expectedClientEvents = isTouchDevice() | ||
? ['touchstart'] | ||
: ['mousemove', 'keydown', 'click', 'dblclick', 'scroll']; | ||
|
||
const addedEvents = addEventListenerSpy.mock.calls.map( | ||
([event, callback]) => ({ event, callback }) | ||
); | ||
|
||
expectedClientEvents.forEach((event) => { | ||
expect(addedEvents.some((e) => e.event === event)).toBe(true); | ||
}); | ||
|
||
act(() => { | ||
unmount(); | ||
}); | ||
|
||
const removedEvents = removeEventListenerSpy.mock.calls.map( | ||
([event, callback]) => ({ event, callback }) | ||
); | ||
|
||
expectedClientEvents.forEach((event) => { | ||
expect(removedEvents.some((e) => e.event === event)).toBe(true); | ||
}); | ||
|
||
addEventListenerSpy.mockRestore(); | ||
removeEventListenerSpy.mockRestore(); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
import { useCallback, useEffect, useState } from 'react'; | ||
import useTimer from './useTimer'; | ||
import { Fn } from '../types'; | ||
import { isTouchDevice, throttle } from '../utils'; | ||
|
||
/** | ||
* 일정 시간(ms) 동안 활동이 없을 때 지정된 콜백 함수를 실행하는 훅. | ||
* | ||
* @param {number} time - 비활성 상태로 간주되기까지의 시간(밀리초). 양의 정수로 지정. (최소값 5000ms) | ||
* @param {Fn} onInactivity - 비활성 상태가 감지되었을 때 호출되는 콜백 함수. | ||
* | ||
* @returns {boolean} - 현재 비활동 상태 여부를 나타내는 boolean 값. | ||
* | ||
* @description | ||
* 사용자가 정의한 시간(time) 동안 활동이 없으면 비활성 상태로 간주하고, 지정된 콜백 함수(onInactivity)를 호출합니다. | ||
* 해당 환경에 맞게 설정된 이벤트를 5초마다 리스닝하여, 활동이 감지될 시 타이머를 리셋합니다. | ||
*/ | ||
|
||
const useDetectInactivity = (time: number, onInactivity: Fn) => { | ||
const [isInactive, setIsInactive] = useState(false); | ||
const { start } = useTimer(() => setIsInactive(true), time); | ||
|
||
// 이벤트 리스너는 5초마다 감지 | ||
const MIN_THROTTLE_TIME = 5000; | ||
|
||
if (time < MIN_THROTTLE_TIME) { | ||
throw new Error( | ||
`'time'은 최소 ${MIN_THROTTLE_TIME}ms 이상으로 설정되어야 합니다.` | ||
); | ||
} | ||
|
||
const clientEvents = isTouchDevice() | ||
? ['touchstart'] | ||
: ['mousemove', 'keydown', 'click', 'dblclick', 'scroll']; | ||
|
||
const resetTimer = useCallback(() => { | ||
setIsInactive(false); | ||
start(); | ||
}, [start]); | ||
|
||
useEffect(() => { | ||
start(); | ||
|
||
const throttledResetTimer = throttle(resetTimer, MIN_THROTTLE_TIME); | ||
|
||
clientEvents.forEach((event) => { | ||
window.addEventListener(event, throttledResetTimer); | ||
}); | ||
|
||
return () => { | ||
clientEvents.forEach((event) => | ||
window.removeEventListener(event, throttledResetTimer) | ||
); | ||
}; | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, [resetTimer]); | ||
|
||
useEffect(() => { | ||
if (isInactive) { | ||
onInactivity(); | ||
} | ||
}, [isInactive, onInactivity]); | ||
|
||
return isInactive; | ||
}; | ||
|
||
export default useDetectInactivity; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,3 @@ | ||
export type Fn = () => void; | ||
|
||
export type GenericFn<T extends unknown[]> = (...args: T) => void; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,4 @@ | ||
export { delayExecution, type CancelToken } from './delayExecution'; | ||
export { throttle } from './throttle'; | ||
export { isClient } from './isClient'; | ||
export { isTouchDevice } from './isTouchDevice'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export const isClient = typeof window !== 'undefined'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
import { isClient } from './isClient'; | ||
|
||
export const isTouchDevice = () => { | ||
if (!isClient) { | ||
return false; | ||
} | ||
return 'ontouchstart' in window || navigator.maxTouchPoints > 0; | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import { GenericFn } from '../types'; | ||
|
||
export const throttle = <T extends unknown[]>( | ||
callbackFn: GenericFn<T>, | ||
delayTime: number | ||
) => { | ||
let lastTime = 0; | ||
|
||
const throttledFunction = (...args: T) => { | ||
const now = Date.now(); | ||
if (now - lastTime >= delayTime) { | ||
lastTime = now; | ||
callbackFn(...args); | ||
} | ||
}; | ||
|
||
return throttledFunction; | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.