Skip to content

Commit 6155fc6

Browse files
authored
merge: useFocus 구현 (#28)
* feat: useFocus 기능 구현 * test: useFocus 기능 테스트 추가 * docs: Storybook, README업데이트 * chore: parameter에서 기본값 정의하도록 변경 (#27)
1 parent 8bebdb2 commit 6155fc6

File tree

8 files changed

+185
-0
lines changed

8 files changed

+185
-0
lines changed

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,20 @@ You can determine the initial on/off state of the toggle through `defaultValue`.
204204

205205
`toggle` : Reverses the current state of the switch.
206206

207+
### useFocus
208+
209+
Executes the provided callback function when a DOM element becomes visible on the screen.
210+
211+
#### Parameters
212+
213+
`onFocusCallback`: A function to execute when the element comes into focus.
214+
`threshold`: Determines the visibility threshold for the element. A value of 1 means the element must be fully visible within the viewport.
215+
`rootMargin`: Adjusts the viewport’s dimensions using the format "top right bottom left", with units explicitly specified.
216+
217+
#### Return Value
218+
219+
`ref`: A ref object to assign to the DOM element that should trigger the focus callback.
220+
207221
## Animation
208222

209223
The animation of this package is based on ClassName by default.

src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import useDebounce from './useDebounce/useDebounce';
1111
import useLocalStorage from './useLocalStorage/useLocalStorage';
1212
import useDisclosure from './useDisclosure/useDisclosure';
1313
import useModal from './useModal/useModal';
14+
import useFocus from './useFocus/useFocus';
1415

1516
export {
1617
useInput,
@@ -26,4 +27,5 @@ export {
2627
useLocalStorage,
2728
useDisclosure,
2829
useModal,
30+
useFocus,
2931
};

src/stories/useFocus/Docs.mdx

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { Canvas, Meta, Description } from '@storybook/blocks';
2+
import * as Focus from './Focus.stories';
3+
4+
<Meta of={Focus} />
5+
6+
# useFocus
7+
8+
DOM Element가 화면에 노출되었을때, callback으로 전달된 함수를 실행합니다.
9+
10+
## 함수인자
11+
12+
`onFocusCallback` : 요소가 focus되었을때, 수행할 함수입니다.
13+
14+
`threshold` : 요소가 화면에 보일때의 기준을 결정합니다. 1이면 전체요소가 모두 화면에 들어왔을때 입니다.
15+
16+
`rootMargin` : 화면의 너비, 높이를 조정할 수 있습니다. "top right bottom left" 형태로 기재하며 반드시 단위를 명시해야합니다.
17+
18+
## 반환값
19+
20+
`ref`: focus될 DOM요소에 할당해줄 ref 객체입니다.
21+
22+
<Canvas of={Focus.defaultStory} />

src/stories/useFocus/Focus.css.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { style } from '@vanilla-extract/css';
2+
3+
export const backgroundDiv = style({
4+
height: 100,
5+
});
6+
7+
export const scrollDiv = style({
8+
position: 'absolute',
9+
backgroundColor: 'black',
10+
color: 'white',
11+
borderRadius: 10,
12+
alignItems: 'center',
13+
justifyContent: 'center',
14+
display: 'flex',
15+
padding: 16,
16+
top: 200,
17+
});
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { Meta, StoryObj } from '@storybook/react';
2+
import Focus from './Focus';
3+
4+
const meta = {
5+
title: 'hooks/useFocus',
6+
component: Focus,
7+
parameters: {
8+
layout: 'centered',
9+
docs: {
10+
canvas: {},
11+
},
12+
},
13+
} satisfies Meta<typeof Focus>;
14+
15+
export default meta;
16+
17+
type Story = StoryObj<typeof meta>;
18+
19+
export const defaultStory: Story = {
20+
args: {},
21+
};

src/stories/useFocus/Focus.tsx

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import React, { useState } from 'react';
2+
import useFocus from '@/useFocus/useFocus';
3+
import { backgroundDiv, scrollDiv } from './Focus.css';
4+
5+
export default function Focus() {
6+
const [message, setMessage] = useState('NOT FOCUS');
7+
const ref = useFocus<HTMLDivElement>(() => setMessage('FOCUS!'), 1, '-10px');
8+
9+
return (
10+
<div className={backgroundDiv}>
11+
<div ref={ref} className={scrollDiv}>
12+
{message}
13+
</div>
14+
</div>
15+
);
16+
}

src/useFocus/useFocus.test.tsx

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { fireEvent, render } from '@testing-library/react';
2+
import useFocus from './useFocus';
3+
import React from 'react';
4+
5+
interface Entrie {
6+
target: Element;
7+
isIntersecting: boolean;
8+
}
9+
10+
const mockIntersectionObserver = class {
11+
entries: Entrie[];
12+
constructor(callback) {
13+
this.entries = [];
14+
window.addEventListener('scroll', () => {
15+
if (window.scrollY > 50) {
16+
this.entries.map((entry) => {
17+
entry.isIntersecting = this.isInViewPort();
18+
});
19+
}
20+
callback(this.entries, this);
21+
});
22+
}
23+
24+
isInViewPort() {
25+
return true;
26+
}
27+
28+
observe(target: Element) {
29+
this.entries.push({ isIntersecting: false, target });
30+
}
31+
32+
unobserve(target) {
33+
this.entries = this.entries.filter((ob) => ob.target !== target);
34+
}
35+
36+
disconnect() {
37+
this.entries = [];
38+
}
39+
};
40+
41+
describe('useFocus 기능 테스트', () => {
42+
beforeEach(() => {
43+
// eslint-disable-next-line
44+
global.IntersectionObserver = mockIntersectionObserver as any;
45+
});
46+
47+
it('focus되었을때 onFocusCallback을 실행시킬 수 있다.', async () => {
48+
const mock = jest.fn();
49+
const Test = () => {
50+
const ref = useFocus<HTMLDivElement>(mock);
51+
return <div ref={ref}>Test</div>;
52+
};
53+
render(<Test />);
54+
fireEvent.scroll(window, { target: { scrollY: 100 } });
55+
expect(mock).toHaveBeenCalled();
56+
});
57+
});

src/useFocus/useFocus.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { useCallback, useEffect, useRef } from 'react';
2+
3+
export default function useFocus<T extends HTMLElement>(
4+
onFocusCallback: (() => void) | (() => Promise<void>),
5+
threshold = 0.1,
6+
rootMargin?: string,
7+
) {
8+
const elementRef = useRef<T>(null);
9+
10+
const handleScroll: IntersectionObserverCallback = useCallback(([entry]) => {
11+
const { current } = elementRef;
12+
if (current) {
13+
if (entry.isIntersecting) {
14+
onFocusCallback();
15+
}
16+
}
17+
}, []);
18+
19+
useEffect(() => {
20+
let observer: IntersectionObserver;
21+
const { current } = elementRef;
22+
23+
if (current) {
24+
observer = new IntersectionObserver(handleScroll, {
25+
threshold,
26+
rootMargin: rootMargin || '0px 0px 0px 0px',
27+
});
28+
29+
observer.observe(current);
30+
31+
return () => observer && observer.disconnect();
32+
}
33+
}, [handleScroll]);
34+
35+
return elementRef;
36+
}

0 commit comments

Comments
 (0)