@jbpark/use-hooks 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,162 @@
1
+ # use-hooks
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@jbpark/use-hooks.svg)](https://www.npmjs.com/package/@jbpark/use-hooks)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@jbpark/use-hooks.svg)](https://www.npmjs.com/package/@jbpark/use-hooks)
5
+ [![GitHub issues](https://img.shields.io/github/issues/pjb0811/use-hooks)](https://github.com/pjb0811/use-hooks/issues)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ 일반적인 UI 및 상호작용 패턴을 위한 재사용 가능한 React 19 훅 모음입니다. TypeScript와 Vite로 빌드되었으며, 서버 사이드 렌더링과 클라이언트 사이드 애플리케이션 모두에 최적화되어 있습니다.
9
+
10
+ ## 기능
11
+
12
+ - 📦 **10개 프로덕션 레디 훅** - 스크롤, 뷰포트, 스토리지 등 다양한 유틸리티
13
+ - 🎯 **TypeScript 지원** - 완전한 타입 지원으로 더 나은 개발 경험
14
+ - ⚡ **트리 셰이킹 지원** - 필요한 것만 임포트하세요
15
+ - 🔒 **SSR 안전** - window/document 전역 변수에 대한 보호
16
+ - 📱 **iOS 최적화** - 모바일 뷰포트 특성에 대한 특별 처리
17
+ - 🧹 **완벽한 정리** - 모든 리스너와 옵저버가 정리됩니다
18
+
19
+ ## 설치
20
+
21
+ ```bash
22
+ npm install @jbpark/use-hooks
23
+ ```
24
+
25
+ ## 사용 방법
26
+
27
+ ```tsx
28
+ import {
29
+ useElementSize,
30
+ useLocalStorage,
31
+ useWindowScroll,
32
+ } from '@jbpark/use-hooks';
33
+
34
+ function MyComponent() {
35
+ // localStorage를 사용한 영속적 상태
36
+ const [count, setCount] = useLocalStorage('count', 0);
37
+
38
+ // 윈도우 스크롤 위치 추적
39
+ const { y, percent } = useWindowScroll();
40
+
41
+ // 브레이크포인트를 포함한 요소 크기 모니터링
42
+ const { size, breakpoint, ref } = useElementSize();
43
+
44
+ return (
45
+ <div ref={ref}>
46
+ <p>Count: {count}</p>
47
+ <p>Scroll: {percent.y}%</p>
48
+ <p>Breakpoint: {breakpoint.current}</p>
49
+ <button onClick={() => setCount(count + 1)}>+</button>
50
+ </div>
51
+ );
52
+ }
53
+ ```
54
+
55
+ ## 사용 가능한 훅
56
+
57
+ | 훅 | 설명 |
58
+ | --------------------- | --------------------------------------------------------------- |
59
+ | `useLocalStorage` | 에러 핸들링이 포함된 JSON 기반 영속 상태 (SSR 안전) |
60
+ | `useWindowScroll` | 윈도우 스크롤 위치 및 백분율 추적 (iOS visualViewport 대응) |
61
+ | `useScrollPosition` | ResizeObserver를 사용한 특정 요소의 스크롤 상태 추적 |
62
+ | `useElementRect` | 스크롤/리사이즈 시 요소의 바운딩 렉트 모니터링 (요소 참조 지원) |
63
+ | `useElementSize` | Tailwind 유사 브레이크포인트를 포함한 요소 크기 추적 (debounce) |
64
+ | `useBodyScrollLock` | 스타일 보존을 포함한 바디 스크롤 잠금/해제 (iOS 특별 처리) |
65
+ | `useScrollToElements` | 인덱스별로 특정 요소로 스크롤 (오프셋 조절 가능) |
66
+ | `useImageLoader` | 이미지 사전로드 및 로딩/에러 상태 노출 |
67
+ | `useRecursiveTimeout` | 비동기/동기 콜백을 재귀적으로 스케줄링 |
68
+ | `useViewport` | visualViewport 지원, 인앱 모드 옵션, debounce 포함 |
69
+
70
+ ## 개발
71
+
72
+ ```bash
73
+ # HMR이 포함된 개발 서버 시작
74
+ npm run dev
75
+
76
+ # 라이브러리 빌드 (tsc + vite)
77
+ npm run build
78
+
79
+ # 빌드된 라이브러리 미리보기
80
+ npm run preview
81
+
82
+ # 린트 및 타입 체크
83
+ npm run lint
84
+
85
+ # prettier로 포맷팅
86
+ npx prettier --write .
87
+ ```
88
+
89
+ ## 프로젝트 구조
90
+
91
+ ```
92
+ src/
93
+ ├── hooks/ # 개별 훅 구현
94
+ │ ├── useBodyScrollLock/
95
+ │ ├── useElementRect/
96
+ │ ├── useElementSize/
97
+ │ ├── useImageLoader/
98
+ │ ├── useLocalStorage/
99
+ │ ├── useRecursiveTimeout/
100
+ │ ├── useScrollPosition/
101
+ │ ├── useScrollToElements/
102
+ │ ├── useViewport/
103
+ │ ├── useWindowScroll/
104
+ │ └── index.ts # 배럴 익스포트
105
+ └── index.ts # 패키지 진입점
106
+
107
+ dist/ # 빌드된 라이브러리 (ES + CJS + types)
108
+ .changeset/ # 버저닝을 위한 Changesets
109
+ ```
110
+
111
+ ## 빌드 및 배포
112
+
113
+ 이 프로젝트는 버전 관리를 위해 Changesets를 사용합니다:
114
+
115
+ ```bash
116
+ # 변경사항 기록
117
+ npx changeset
118
+
119
+ # 버전 업데이트 및 CHANGELOG 생성
120
+ npx changeset version
121
+
122
+ # npm에 배포
123
+ npx changeset publish
124
+
125
+ # 태그 푸시
126
+ git push --follow-tags
127
+ ```
128
+
129
+ 라이브러리는 다음과 같이 빌드됩니다:
130
+
131
+ - **ES Module**: `dist/index.js`
132
+ - **CommonJS**: `dist/index.cjs`
133
+ - **타입 정의**: `dist/index.d.ts`
134
+
135
+ ## 주요 패턴
136
+
137
+ - **Window 보호**: `window`/`document`에 접근하는 훅은 SSR 안전성을 위해 `typeof window` 체크 (예: `useLocalStorage`)
138
+ - **이벤트 리스너**: 모든 스크롤/리사이즈 리스너는 가능한 한 passive 플래그 사용
139
+ - **ResizeObserver**: `useElementSize`와 `useScrollPosition`에서 사용하여 성능 최적화
140
+ - **requestAnimationFrame**: 스크롤/리사이즈 콜백에서 레이아웃 스래싱 방지
141
+ - **iOS 대응**: `useBodyScrollLock`, `useWindowScroll`, `useViewport`에서 iOS의 visualViewport 특성 처리
142
+ - **Debounce**: `useElementSize`와 `useViewport`에서 리사이즈 이벤트 디바운싱 지원
143
+
144
+ ## 브라우저 지원
145
+
146
+ - 최신 브라우저 (Chrome, Firefox, Safari, Edge)
147
+ - iOS 12+ (특수한 `visualViewport` 처리 포함)
148
+ - SSR 준비 완료 (적절한 보호 포함)
149
+
150
+ ## 기여하기
151
+
152
+ 버그 리포트, 기능 제안, 또는 코드 기여를 환영합니다!
153
+
154
+ - 🐛 **버그 리포트**: [Issues](https://github.com/pjb0811/use-hooks/issues)에서 버그를 리포트해주세요
155
+ - 💡 **기능 제안**: 새로운 기능 아이디어가 있으시면 [Issues](https://github.com/pjb0811/use-hooks/issues)에 제안해주세요
156
+ - 🔧 **코드 기여**: Pull Request를 보내주시면 검토 후 반영하겠습니다
157
+
158
+ 이슈를 생성하기 전에 기존 이슈를 확인해주시면 중복을 방지할 수 있습니다.
159
+
160
+ ## 라이선스
161
+
162
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react"),p=(e=!0)=>{i.useEffect(()=>{if(!e)return;const t=window.scrollY,l=/iPad|iPhone|iPod/.test(navigator.userAgent),o={documentElement:{overflow:document.documentElement.style.overflow,height:document.documentElement.style.height,position:document.documentElement.style.position,width:document.documentElement.style.width},body:{overflow:document.body.style.overflow,height:document.body.style.height,position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,right:document.body.style.right,width:document.body.style.width,webkitOverflowScrolling:document.body.style.getPropertyValue("-webkit-overflow-scrolling")}};if(document.documentElement.style.overflow="hidden",document.documentElement.style.height="100%",document.documentElement.style.position="fixed",document.documentElement.style.width="100%",document.body.style.overflow="hidden",document.body.style.height="100%",document.body.style.position="fixed",document.body.style.top=`-${t}px`,document.body.style.left="0",document.body.style.right="0",document.body.style.width="100%",l){document.body.style.setProperty("-webkit-overflow-scrolling","touch");const r=s=>{(s.target===document.body||s.target===document.documentElement||s.target===window)&&(s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation())},c=()=>{window.scrollTo(0,0),document.body.scrollTop=0,document.documentElement.scrollTop=0},n=["scroll","touchmove","touchstart","touchend"];n.forEach(s=>{window.addEventListener(s,r,{passive:!1,capture:!0}),document.addEventListener(s,r,{passive:!1,capture:!0}),document.body.addEventListener(s,r,{passive:!1,capture:!0})});const u=setInterval(c,16);return()=>{clearInterval(u),n.forEach(s=>{window.removeEventListener(s,r,{capture:!0}),document.removeEventListener(s,r,{capture:!0}),document.body.removeEventListener(s,r,{capture:!0})}),document.documentElement.style.overflow=o.documentElement.overflow,document.documentElement.style.height=o.documentElement.height,document.documentElement.style.position=o.documentElement.position,document.documentElement.style.width=o.documentElement.width,document.body.style.overflow=o.body.overflow,document.body.style.height=o.body.height,document.body.style.position=o.body.position,document.body.style.top=o.body.top,document.body.style.left=o.body.left,document.body.style.right=o.body.right,document.body.style.width=o.body.width,o.body.webkitOverflowScrolling?document.body.style.setProperty("-webkit-overflow-scrolling",o.body.webkitOverflowScrolling):document.body.style.removeProperty("-webkit-overflow-scrolling"),window.scrollTo(0,t)}}return()=>{document.documentElement.style.overflow=o.documentElement.overflow,document.documentElement.style.height=o.documentElement.height,document.documentElement.style.position=o.documentElement.position,document.documentElement.style.width=o.documentElement.width,document.body.style.overflow=o.body.overflow,document.body.style.height=o.body.height,document.body.style.position=o.body.position,document.body.style.top=o.body.top,document.body.style.left=o.body.left,document.body.style.right=o.body.right,document.body.style.width=o.body.width,window.scrollTo(0,t)}},[e])},b=e=>{const[t,l]=i.useState(null);return i.useEffect(()=>{const o=n=>typeof n=="string"?document.querySelector(n):n.current,r=()=>{const n=o(e);l(n?n.getBoundingClientRect():null)},c=()=>{requestAnimationFrame(r)};return r(),window.addEventListener("scroll",c,{passive:!0}),window.addEventListener("resize",c,{passive:!0}),()=>{window.removeEventListener("scroll",c),window.removeEventListener("resize",c)}},[e]),t};function E(e,t){t===void 0&&(t=0);var l=i.useRef(!1),o=i.useRef(),r=i.useRef(e),c=i.useCallback(function(){return l.current},[]),n=i.useCallback(function(){l.current=!1,o.current&&clearTimeout(o.current),o.current=setTimeout(function(){l.current=!0,r.current()},t)},[t]),u=i.useCallback(function(){l.current=null,o.current&&clearTimeout(o.current)},[]);return i.useEffect(function(){r.current=e},[e]),i.useEffect(function(){return n(),u},[t]),[c,u,n]}function S(e,t,l){t===void 0&&(t=0),l===void 0&&(l=[]);var o=E(e,t),r=o[0],c=o[1],n=o[2];return i.useEffect(n,l),[r,c]}const m={sm:640,md:768,lg:1024,xl:1280,"2xl":1536},L=e=>{let t="xs";return e>=m["2xl"]?t="2xl":e>=m.xl?t="xl":e>=m.lg?t="lg":e>=m.md?t="md":e>=m.sm?t="sm":t="xs",{current:t,xs:e<m.sm,sm:e>=m.sm&&e<m.md,md:e>=m.md&&e<m.lg,lg:e>=m.lg&&e<m.xl,xl:e>=m.xl&&e<m["2xl"],"2xl":e>=m["2xl"]}},T=(e=200)=>{const[t,l]=i.useState({width:0,height:0}),[o,r]=i.useState({current:"xs",xs:!0,sm:!1,md:!1,lg:!1,xl:!1,"2xl":!1}),[c,n]=i.useState({width:0,height:0}),u=i.useRef(null),s=i.useRef(null);return S(()=>{n(t)},e,[t]),i.useEffect(()=>{const d=()=>{const a=u.current??document.body;if(!a)return;const{offsetWidth:h,offsetHeight:v}=a;l(g=>g.width!==h||g.height!==v?{width:h,height:v}:g),r(g=>{const y=L(h);return g.current!==y.current?y:g})},w=()=>{const a=u.current??document.body;a&&(d(),s.current&&s.current.disconnect(),s.current=new ResizeObserver(()=>{requestAnimationFrame(()=>{d()})}),s.current.observe(a))},f=()=>{s.current&&(s.current.disconnect(),s.current=null)};return w(),()=>{f()}},[]),{size:c,breakpoint:o,ref:u}},x=e=>{const[t,l]=i.useState(!0),[o,r]=i.useState();return i.useEffect(()=>{if(!e){l(!1);return}const c=new Image;c.src=e,c.onload=()=>l(!1),c.onerror=n=>{l(!1),r(n)}},[e]),{loading:t,error:o}},V=(e,t)=>{const l=i.useRef(t),[o,r]=i.useState(()=>{if(typeof window>"u")return t;try{const n=window.localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}});i.useEffect(()=>{if(!(typeof window>"u"))try{const n=window.localStorage.getItem(e);n?r(JSON.parse(n)):window.localStorage.setItem(e,JSON.stringify(l.current))}catch(n){console.error(`Error reading localStorage key "${e}":`,n)}},[e]);const c=i.useCallback(n=>{try{r(u=>{const s=n instanceof Function?n(u):n;return localStorage.setItem(e,JSON.stringify(s)),s})}catch(u){console.error(`Error setting localStorage key "${e}":`,u)}},[e]);return[o,c]},R=(e,t)=>{const l=i.useRef(e);i.useEffect(()=>{l.current=e},[e]),i.useEffect(()=>{let o;function r(){const c=l.current();c instanceof Promise?c.then(()=>{t&&(o=setTimeout(r,t))}):t&&(o=setTimeout(r,t))}if(t)return o=setTimeout(r,t),()=>o&&clearTimeout(o)},[t])},z=()=>{const[e,t]=i.useState(null),[l,o]=i.useState({scrollY:0,scrollPercentage:0,isAtTop:!0,isAtBottom:!1,scrollableHeight:0,clientHeight:0,scrollHeight:0}),r=i.useCallback(c=>{t(c)},[]);return i.useEffect(()=>{if(!e)return;const c=()=>{const{scrollTop:s,scrollHeight:d,clientHeight:w}=e,f=d-w;if(f<=0){o({scrollY:0,scrollPercentage:0,isAtTop:!0,isAtBottom:!0,scrollableHeight:0,clientHeight:w,scrollHeight:d});return}const a=Math.min(100,Math.max(0,s/f*100));o({scrollY:s,scrollPercentage:a,isAtTop:s<=0,isAtBottom:s>=f-1,scrollableHeight:f,clientHeight:w,scrollHeight:d})};c();const n=()=>{c()};e.addEventListener("scroll",n,{passive:!0});const u=new ResizeObserver(()=>{c()});return u.observe(e),()=>{e.removeEventListener("scroll",n),u.unobserve(e)}},[e]),{...l,element:e,setRef:r}};function P(e){const t=i.useRef([]),l=i.useCallback(r=>{if(t.current[r]&&(t.current[r].scrollIntoView({behavior:"smooth",block:"start",inline:"start",...e}),e?.offset)){const c=t.current[r].getBoundingClientRect().top+window.scrollY-e.offset;window.scrollTo({top:c,behavior:e.behavior||"smooth"})}},[e]),o=i.useCallback((r,c)=>{t.current[c]=r},[]);return{elementRefs:t,setElementRef:o,scrollToElement:l}}const H=()=>{const[e,t]=i.useState({x:0,y:0,percent:{x:0,y:0}});return i.useEffect(()=>{const l=()=>{const n=window.scrollX||0,u=window.scrollY||0,s=/iPad|iPhone|iPod/.test(navigator.userAgent),d=window.visualViewport,w=s&&d?d.width:window.innerWidth,f=s&&d?d.height:window.innerHeight,a=Math.max(0,document.documentElement.scrollWidth-w),h=Math.max(0,document.documentElement.scrollHeight-f),v=a===0?0:Math.min(100,n/a*100),g=h===0?0:Math.min(100,u/h*100);t({x:n,y:u,percent:{x:Math.floor(Math.max(0,v)),y:Math.floor(Math.max(0,g))}})};l();const o=()=>{l()},r=()=>{setTimeout(l,100)},c=()=>{setTimeout(l,50)};return window.addEventListener("scroll",o,{passive:!0}),window.addEventListener("resize",r),window.addEventListener("orientationchange",r),window.visualViewport&&window.visualViewport.addEventListener("resize",c),()=>{window.removeEventListener("scroll",o),window.removeEventListener("resize",r),window.removeEventListener("orientationchange",r),window.visualViewport&&window.visualViewport.removeEventListener("resize",c)}},[]),e},I=(e={})=>{const{isInApp:t=!1,debounce:l=100}=e,[o,r]=i.useState({width:0,height:0,offsetLeft:0,offsetTop:0,pageLeft:0,pageTop:0,scale:1}),c=i.useCallback(()=>{const u=window.innerHeight,s=window.visualViewport?.height||u,d=document.documentElement.clientHeight,w=document.body.clientHeight;return window.visualViewport&&Math.abs(s-u)>100?s:Math.max(u,d,w)},[]),n=i.useCallback(()=>{if(window.visualViewport&&!t)return window.visualViewport;const u=window.visualViewport?.width||window.innerWidth,s=t?c():window.visualViewport?.height||window.innerHeight;return{width:u,height:s,offsetLeft:window.visualViewport?.offsetLeft||0,offsetTop:window.visualViewport?.offsetTop||0,pageLeft:window.scrollX??window.pageXOffset??0,pageTop:window.scrollY??window.pageYOffset??0,scale:window.visualViewport?.scale||1}},[t,c]);return i.useEffect(()=>{let u;const s=()=>{clearTimeout(u),u=setTimeout(()=>{r(n())},l)},d=()=>r(n());d();const w=["resize","orientationchange"];t&&w.push("focus","blur","touchstart","touchend"),w.forEach(a=>{a==="resize"||a==="orientationchange"?window.addEventListener(a,s):window.addEventListener(a,d,{passive:!0})}),window.visualViewport&&(window.visualViewport.addEventListener("resize",d),window.visualViewport.addEventListener("scroll",d));let f;if(t){let a=n().height;f=setInterval(()=>{const h=n().height;Math.abs(h-a)>50&&(a=h,d())},500)}return()=>{clearTimeout(u),f&&clearInterval(f),w.forEach(a=>{window.removeEventListener(a,a==="resize"||a==="orientationchange"?s:d)}),window.visualViewport&&(window.visualViewport.removeEventListener("resize",d),window.visualViewport.removeEventListener("scroll",d))}},[n,t,l]),o};exports.useBodyScrollLock=p;exports.useElementRect=b;exports.useElementSize=T;exports.useImageLoader=x;exports.useLocalStorage=V;exports.useRecursiveTimeout=R;exports.useScrollPosition=z;exports.useScrollToElements=P;exports.useViewport=I;exports.useWindowScroll=H;
@@ -0,0 +1,87 @@
1
+ import { RefObject } from 'react';
2
+
3
+ declare type Breakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';
4
+
5
+ declare interface BreakpointInfo {
6
+ current: Breakpoint;
7
+ xs: boolean;
8
+ sm: boolean;
9
+ md: boolean;
10
+ lg: boolean;
11
+ xl: boolean;
12
+ '2xl': boolean;
13
+ }
14
+
15
+ declare type ElementReference<T> = string | RefObject<T>;
16
+
17
+ declare interface Props extends ScrollIntoViewOptions {
18
+ offset?: number;
19
+ }
20
+
21
+ export declare const useBodyScrollLock: (enabled?: boolean) => void;
22
+
23
+ export declare const useElementRect: <T>(elementRef: ElementReference<T>) => DOMRect | null;
24
+
25
+ export declare const useElementSize: <T extends HTMLElement>(delay?: number) => {
26
+ size: {
27
+ width: number;
28
+ height: number;
29
+ };
30
+ breakpoint: BreakpointInfo;
31
+ ref: RefObject<T | null>;
32
+ };
33
+
34
+ export declare const useImageLoader: (src: string) => {
35
+ loading: boolean;
36
+ error: string | Event | undefined;
37
+ };
38
+
39
+ export declare const useLocalStorage: <T>(key: string, initialValue: T) => readonly [T, (value: T | ((val: T) => T)) => void];
40
+
41
+ export declare const useRecursiveTimeout: <T>(callback: () => Promise<T> | (() => void), delay: number | null) => void;
42
+
43
+ export declare const useScrollPosition: () => {
44
+ element: HTMLElement | null;
45
+ setRef: (el: HTMLElement | null) => void;
46
+ scrollY: number;
47
+ scrollPercentage: number;
48
+ isAtTop: boolean;
49
+ isAtBottom: boolean;
50
+ scrollableHeight: number;
51
+ clientHeight: number;
52
+ scrollHeight: number;
53
+ };
54
+
55
+ export declare function useScrollToElements(options?: Props): {
56
+ elementRefs: RefObject<HTMLElement[]>;
57
+ setElementRef: (element: HTMLElement, index: number) => void;
58
+ scrollToElement: (index: number) => void;
59
+ };
60
+
61
+ export declare const useViewport: (options?: UseViewportOptions) => ViewportInfo;
62
+
63
+ declare interface UseViewportOptions {
64
+ isInApp?: boolean;
65
+ debounce?: number;
66
+ }
67
+
68
+ export declare const useWindowScroll: () => {
69
+ x: number;
70
+ y: number;
71
+ percent: {
72
+ x: number;
73
+ y: number;
74
+ };
75
+ };
76
+
77
+ declare type ViewportInfo = VisualViewport | {
78
+ width: number;
79
+ height: number;
80
+ offsetLeft: number;
81
+ offsetTop: number;
82
+ pageLeft: number;
83
+ pageTop: number;
84
+ scale: number;
85
+ };
86
+
87
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1,415 @@
1
+ import { useEffect as w, useState as h, useRef as p, useCallback as v } from "react";
2
+ const V = (e = !0) => {
3
+ w(() => {
4
+ if (!e)
5
+ return;
6
+ const t = window.scrollY, c = /iPad|iPhone|iPod/.test(navigator.userAgent), o = {
7
+ documentElement: {
8
+ overflow: document.documentElement.style.overflow,
9
+ height: document.documentElement.style.height,
10
+ position: document.documentElement.style.position,
11
+ width: document.documentElement.style.width
12
+ },
13
+ body: {
14
+ overflow: document.body.style.overflow,
15
+ height: document.body.style.height,
16
+ position: document.body.style.position,
17
+ top: document.body.style.top,
18
+ left: document.body.style.left,
19
+ right: document.body.style.right,
20
+ width: document.body.style.width,
21
+ webkitOverflowScrolling: document.body.style.getPropertyValue(
22
+ "-webkit-overflow-scrolling"
23
+ )
24
+ }
25
+ };
26
+ if (document.documentElement.style.overflow = "hidden", document.documentElement.style.height = "100%", document.documentElement.style.position = "fixed", document.documentElement.style.width = "100%", document.body.style.overflow = "hidden", document.body.style.height = "100%", document.body.style.position = "fixed", document.body.style.top = `-${t}px`, document.body.style.left = "0", document.body.style.right = "0", document.body.style.width = "100%", c) {
27
+ document.body.style.setProperty("-webkit-overflow-scrolling", "touch");
28
+ const r = (i) => {
29
+ (i.target === document.body || i.target === document.documentElement || i.target === window) && (i.preventDefault(), i.stopPropagation(), i.stopImmediatePropagation());
30
+ }, s = () => {
31
+ window.scrollTo(0, 0), document.body.scrollTop = 0, document.documentElement.scrollTop = 0;
32
+ }, n = ["scroll", "touchmove", "touchstart", "touchend"];
33
+ n.forEach((i) => {
34
+ window.addEventListener(i, r, {
35
+ passive: !1,
36
+ capture: !0
37
+ }), document.addEventListener(i, r, {
38
+ passive: !1,
39
+ capture: !0
40
+ }), document.body.addEventListener(i, r, {
41
+ passive: !1,
42
+ capture: !0
43
+ });
44
+ });
45
+ const l = setInterval(s, 16);
46
+ return () => {
47
+ clearInterval(l), n.forEach((i) => {
48
+ window.removeEventListener(i, r, { capture: !0 }), document.removeEventListener(i, r, { capture: !0 }), document.body.removeEventListener(i, r, {
49
+ capture: !0
50
+ });
51
+ }), document.documentElement.style.overflow = o.documentElement.overflow, document.documentElement.style.height = o.documentElement.height, document.documentElement.style.position = o.documentElement.position, document.documentElement.style.width = o.documentElement.width, document.body.style.overflow = o.body.overflow, document.body.style.height = o.body.height, document.body.style.position = o.body.position, document.body.style.top = o.body.top, document.body.style.left = o.body.left, document.body.style.right = o.body.right, document.body.style.width = o.body.width, o.body.webkitOverflowScrolling ? document.body.style.setProperty(
52
+ "-webkit-overflow-scrolling",
53
+ o.body.webkitOverflowScrolling
54
+ ) : document.body.style.removeProperty("-webkit-overflow-scrolling"), window.scrollTo(0, t);
55
+ };
56
+ }
57
+ return () => {
58
+ document.documentElement.style.overflow = o.documentElement.overflow, document.documentElement.style.height = o.documentElement.height, document.documentElement.style.position = o.documentElement.position, document.documentElement.style.width = o.documentElement.width, document.body.style.overflow = o.body.overflow, document.body.style.height = o.body.height, document.body.style.position = o.body.position, document.body.style.top = o.body.top, document.body.style.left = o.body.left, document.body.style.right = o.body.right, document.body.style.width = o.body.width, window.scrollTo(0, t);
59
+ };
60
+ }, [e]);
61
+ }, z = (e) => {
62
+ const [t, c] = h(null);
63
+ return w(() => {
64
+ const o = (n) => typeof n == "string" ? document.querySelector(n) : n.current, r = () => {
65
+ const n = o(e);
66
+ c(n ? n.getBoundingClientRect() : null);
67
+ }, s = () => {
68
+ requestAnimationFrame(r);
69
+ };
70
+ return r(), window.addEventListener("scroll", s, { passive: !0 }), window.addEventListener("resize", s, { passive: !0 }), () => {
71
+ window.removeEventListener("scroll", s), window.removeEventListener("resize", s);
72
+ };
73
+ }, [e]), t;
74
+ };
75
+ function S(e, t) {
76
+ t === void 0 && (t = 0);
77
+ var c = p(!1), o = p(), r = p(e), s = v(function() {
78
+ return c.current;
79
+ }, []), n = v(function() {
80
+ c.current = !1, o.current && clearTimeout(o.current), o.current = setTimeout(function() {
81
+ c.current = !0, r.current();
82
+ }, t);
83
+ }, [t]), l = v(function() {
84
+ c.current = null, o.current && clearTimeout(o.current);
85
+ }, []);
86
+ return w(function() {
87
+ r.current = e;
88
+ }, [e]), w(function() {
89
+ return n(), l;
90
+ }, [t]), [s, l, n];
91
+ }
92
+ function L(e, t, c) {
93
+ t === void 0 && (t = 0), c === void 0 && (c = []);
94
+ var o = S(e, t), r = o[0], s = o[1], n = o[2];
95
+ return w(n, c), [r, s];
96
+ }
97
+ const a = {
98
+ // < 640px
99
+ sm: 640,
100
+ // >= 640px
101
+ md: 768,
102
+ // >= 768px
103
+ lg: 1024,
104
+ // >= 1024px
105
+ xl: 1280,
106
+ // >= 1280px
107
+ "2xl": 1536
108
+ // >= 1536px
109
+ }, x = (e) => {
110
+ let t = "xs";
111
+ return e >= a["2xl"] ? t = "2xl" : e >= a.xl ? t = "xl" : e >= a.lg ? t = "lg" : e >= a.md ? t = "md" : e >= a.sm ? t = "sm" : t = "xs", {
112
+ current: t,
113
+ xs: e < a.sm,
114
+ sm: e >= a.sm && e < a.md,
115
+ md: e >= a.md && e < a.lg,
116
+ lg: e >= a.lg && e < a.xl,
117
+ xl: e >= a.xl && e < a["2xl"],
118
+ "2xl": e >= a["2xl"]
119
+ };
120
+ }, H = (e = 200) => {
121
+ const [t, c] = h({ width: 0, height: 0 }), [o, r] = h({
122
+ current: "xs",
123
+ xs: !0,
124
+ sm: !1,
125
+ md: !1,
126
+ lg: !1,
127
+ xl: !1,
128
+ "2xl": !1
129
+ }), [s, n] = h({ width: 0, height: 0 }), l = p(null), i = p(null);
130
+ return L(
131
+ () => {
132
+ n(t);
133
+ },
134
+ e,
135
+ [t]
136
+ ), w(() => {
137
+ const d = () => {
138
+ const u = l.current ?? document.body;
139
+ if (!u)
140
+ return;
141
+ const { offsetWidth: g, offsetHeight: b } = u;
142
+ c((y) => y.width !== g || y.height !== b ? { width: g, height: b } : y), r((y) => {
143
+ const E = x(g);
144
+ return y.current !== E.current ? E : y;
145
+ });
146
+ }, m = () => {
147
+ const u = l.current ?? document.body;
148
+ u && (d(), i.current && i.current.disconnect(), i.current = new ResizeObserver(() => {
149
+ requestAnimationFrame(() => {
150
+ d();
151
+ });
152
+ }), i.current.observe(u));
153
+ }, f = () => {
154
+ i.current && (i.current.disconnect(), i.current = null);
155
+ };
156
+ return m(), () => {
157
+ f();
158
+ };
159
+ }, []), {
160
+ size: s,
161
+ breakpoint: o,
162
+ ref: l
163
+ };
164
+ }, P = (e) => {
165
+ const [t, c] = h(!0), [o, r] = h();
166
+ return w(() => {
167
+ if (!e) {
168
+ c(!1);
169
+ return;
170
+ }
171
+ const s = new Image();
172
+ s.src = e, s.onload = () => c(!1), s.onerror = (n) => {
173
+ c(!1), r(n);
174
+ };
175
+ }, [e]), {
176
+ loading: t,
177
+ error: o
178
+ };
179
+ }, I = (e, t) => {
180
+ const c = p(t), [o, r] = h(() => {
181
+ if (typeof window > "u")
182
+ return t;
183
+ try {
184
+ const n = window.localStorage.getItem(e);
185
+ return n ? JSON.parse(n) : t;
186
+ } catch {
187
+ return t;
188
+ }
189
+ });
190
+ w(() => {
191
+ if (!(typeof window > "u"))
192
+ try {
193
+ const n = window.localStorage.getItem(e);
194
+ n ? r(JSON.parse(n)) : window.localStorage.setItem(e, JSON.stringify(c.current));
195
+ } catch (n) {
196
+ console.error(`Error reading localStorage key "${e}":`, n);
197
+ }
198
+ }, [e]);
199
+ const s = v(
200
+ (n) => {
201
+ try {
202
+ r((l) => {
203
+ const i = n instanceof Function ? n(l) : n;
204
+ return localStorage.setItem(e, JSON.stringify(i)), i;
205
+ });
206
+ } catch (l) {
207
+ console.error(`Error setting localStorage key "${e}":`, l);
208
+ }
209
+ },
210
+ [e]
211
+ );
212
+ return [o, s];
213
+ }, R = (e, t) => {
214
+ const c = p(e);
215
+ w(() => {
216
+ c.current = e;
217
+ }, [e]), w(() => {
218
+ let o;
219
+ function r() {
220
+ const s = c.current();
221
+ s instanceof Promise ? s.then(() => {
222
+ t && (o = setTimeout(r, t));
223
+ }) : t && (o = setTimeout(r, t));
224
+ }
225
+ if (t)
226
+ return o = setTimeout(r, t), () => o && clearTimeout(o);
227
+ }, [t]);
228
+ }, O = () => {
229
+ const [e, t] = h(null), [c, o] = h({
230
+ scrollY: 0,
231
+ scrollPercentage: 0,
232
+ isAtTop: !0,
233
+ isAtBottom: !1,
234
+ scrollableHeight: 0,
235
+ clientHeight: 0,
236
+ scrollHeight: 0
237
+ }), r = v((s) => {
238
+ t(s);
239
+ }, []);
240
+ return w(() => {
241
+ if (!e)
242
+ return;
243
+ const s = () => {
244
+ const { scrollTop: i, scrollHeight: d, clientHeight: m } = e, f = d - m;
245
+ if (f <= 0) {
246
+ o({
247
+ scrollY: 0,
248
+ scrollPercentage: 0,
249
+ isAtTop: !0,
250
+ isAtBottom: !0,
251
+ scrollableHeight: 0,
252
+ clientHeight: m,
253
+ scrollHeight: d
254
+ });
255
+ return;
256
+ }
257
+ const u = Math.min(
258
+ 100,
259
+ Math.max(0, i / f * 100)
260
+ );
261
+ o({
262
+ scrollY: i,
263
+ scrollPercentage: u,
264
+ isAtTop: i <= 0,
265
+ isAtBottom: i >= f - 1,
266
+ scrollableHeight: f,
267
+ clientHeight: m,
268
+ scrollHeight: d
269
+ });
270
+ };
271
+ s();
272
+ const n = () => {
273
+ s();
274
+ };
275
+ e.addEventListener("scroll", n, { passive: !0 });
276
+ const l = new ResizeObserver(() => {
277
+ s();
278
+ });
279
+ return l.observe(e), () => {
280
+ e.removeEventListener("scroll", n), l.unobserve(e);
281
+ };
282
+ }, [e]), { ...c, element: e, setRef: r };
283
+ };
284
+ function A(e) {
285
+ const t = p([]), c = v(
286
+ (r) => {
287
+ if (t.current[r] && (t.current[r].scrollIntoView({
288
+ behavior: "smooth",
289
+ block: "start",
290
+ inline: "start",
291
+ ...e
292
+ }), e?.offset)) {
293
+ const s = t.current[r].getBoundingClientRect().top + window.scrollY - e.offset;
294
+ window.scrollTo({
295
+ top: s,
296
+ behavior: e.behavior || "smooth"
297
+ });
298
+ }
299
+ },
300
+ [e]
301
+ ), o = v((r, s) => {
302
+ t.current[s] = r;
303
+ }, []);
304
+ return { elementRefs: t, setElementRef: o, scrollToElement: c };
305
+ }
306
+ const M = () => {
307
+ const [e, t] = h({
308
+ x: 0,
309
+ y: 0,
310
+ percent: {
311
+ x: 0,
312
+ y: 0
313
+ }
314
+ });
315
+ return w(() => {
316
+ const c = () => {
317
+ const n = window.scrollX || 0, l = window.scrollY || 0, i = /iPad|iPhone|iPod/.test(navigator.userAgent), d = window.visualViewport, m = i && d ? d.width : window.innerWidth, f = i && d ? d.height : window.innerHeight, u = Math.max(
318
+ 0,
319
+ document.documentElement.scrollWidth - m
320
+ ), g = Math.max(
321
+ 0,
322
+ document.documentElement.scrollHeight - f
323
+ ), b = u === 0 ? 0 : Math.min(100, n / u * 100), y = g === 0 ? 0 : Math.min(100, l / g * 100);
324
+ t({
325
+ x: n,
326
+ y: l,
327
+ percent: {
328
+ x: Math.floor(Math.max(0, b)),
329
+ y: Math.floor(Math.max(0, y))
330
+ }
331
+ });
332
+ };
333
+ c();
334
+ const o = () => {
335
+ c();
336
+ }, r = () => {
337
+ setTimeout(c, 100);
338
+ }, s = () => {
339
+ setTimeout(c, 50);
340
+ };
341
+ return window.addEventListener("scroll", o, { passive: !0 }), window.addEventListener("resize", r), window.addEventListener("orientationchange", r), window.visualViewport && window.visualViewport.addEventListener("resize", s), () => {
342
+ window.removeEventListener("scroll", o), window.removeEventListener("resize", r), window.removeEventListener("orientationchange", r), window.visualViewport && window.visualViewport.removeEventListener(
343
+ "resize",
344
+ s
345
+ );
346
+ };
347
+ }, []), e;
348
+ }, Y = (e = {}) => {
349
+ const { isInApp: t = !1, debounce: c = 100 } = e, [o, r] = h({
350
+ width: 0,
351
+ height: 0,
352
+ offsetLeft: 0,
353
+ offsetTop: 0,
354
+ pageLeft: 0,
355
+ pageTop: 0,
356
+ scale: 1
357
+ }), s = v(() => {
358
+ const l = window.innerHeight, i = window.visualViewport?.height || l, d = document.documentElement.clientHeight, m = document.body.clientHeight;
359
+ return window.visualViewport && Math.abs(i - l) > 100 ? i : Math.max(l, d, m);
360
+ }, []), n = v(() => {
361
+ if (window.visualViewport && !t)
362
+ return window.visualViewport;
363
+ const l = window.visualViewport?.width || window.innerWidth, i = t ? s() : window.visualViewport?.height || window.innerHeight;
364
+ return {
365
+ width: l,
366
+ height: i,
367
+ offsetLeft: window.visualViewport?.offsetLeft || 0,
368
+ offsetTop: window.visualViewport?.offsetTop || 0,
369
+ pageLeft: window.scrollX ?? window.pageXOffset ?? 0,
370
+ pageTop: window.scrollY ?? window.pageYOffset ?? 0,
371
+ scale: window.visualViewport?.scale || 1
372
+ };
373
+ }, [t, s]);
374
+ return w(() => {
375
+ let l;
376
+ const i = () => {
377
+ clearTimeout(l), l = setTimeout(() => {
378
+ r(n());
379
+ }, c);
380
+ }, d = () => r(n());
381
+ d();
382
+ const m = ["resize", "orientationchange"];
383
+ t && m.push("focus", "blur", "touchstart", "touchend"), m.forEach((u) => {
384
+ u === "resize" || u === "orientationchange" ? window.addEventListener(u, i) : window.addEventListener(u, d, { passive: !0 });
385
+ }), window.visualViewport && (window.visualViewport.addEventListener("resize", d), window.visualViewport.addEventListener("scroll", d));
386
+ let f;
387
+ if (t) {
388
+ let u = n().height;
389
+ f = setInterval(() => {
390
+ const g = n().height;
391
+ Math.abs(g - u) > 50 && (u = g, d());
392
+ }, 500);
393
+ }
394
+ return () => {
395
+ clearTimeout(l), f && clearInterval(f), m.forEach((u) => {
396
+ window.removeEventListener(
397
+ u,
398
+ u === "resize" || u === "orientationchange" ? i : d
399
+ );
400
+ }), window.visualViewport && (window.visualViewport.removeEventListener("resize", d), window.visualViewport.removeEventListener("scroll", d));
401
+ };
402
+ }, [n, t, c]), o;
403
+ };
404
+ export {
405
+ V as useBodyScrollLock,
406
+ z as useElementRect,
407
+ H as useElementSize,
408
+ P as useImageLoader,
409
+ I as useLocalStorage,
410
+ R as useRecursiveTimeout,
411
+ O as useScrollPosition,
412
+ A as useScrollToElements,
413
+ Y as useViewport,
414
+ M as useWindowScroll
415
+ };
package/dist/vite.svg ADDED
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
package/package.json ADDED
@@ -0,0 +1,85 @@
1
+ {
2
+ "name": "@jbpark/use-hooks",
3
+ "version": "1.0.0",
4
+ "description": "일반적인 UI 및 상호작용 패턴을 위한 재사용 가능한 React 19 훅 모음",
5
+ "keywords": [
6
+ "react",
7
+ "hooks",
8
+ "typescript",
9
+ "react-hooks",
10
+ "utilities",
11
+ "custom-hooks"
12
+ ],
13
+ "author": "jbpark",
14
+ "license": "MIT",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/pjb0811/use-hooks.git"
18
+ },
19
+ "homepage": "https://github.com/pjb0811/use-hooks#readme",
20
+ "bugs": {
21
+ "url": "https://github.com/pjb0811/use-hooks/issues"
22
+ },
23
+ "private": false,
24
+ "type": "module",
25
+ "main": "./dist/index.cjs",
26
+ "module": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "source": "./src/index.ts",
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js",
33
+ "require": "./dist/index.cjs"
34
+ }
35
+ },
36
+ "files": [
37
+ "dist"
38
+ ],
39
+ "scripts": {
40
+ "dev": "vite",
41
+ "build": "tsc -b && vite build",
42
+ "lint": "eslint .",
43
+ "preview": "vite preview",
44
+ "prepublishOnly": "npm run build",
45
+ "prepare": "husky install"
46
+ },
47
+ "peerDependencies": {
48
+ "react": "^19.1.1",
49
+ "react-dom": "^19.1.1"
50
+ },
51
+ "dependencies": {
52
+ "react-use": "^17.6.0"
53
+ },
54
+ "devDependencies": {
55
+ "@changesets/cli": "^2.29.8",
56
+ "@eslint/js": "^9.33.0",
57
+ "@trivago/prettier-plugin-sort-imports": "^5.2.2",
58
+ "@types/node": "^24.5.2",
59
+ "@types/react": "^19.1.10",
60
+ "@types/react-dom": "^19.1.7",
61
+ "@vitejs/plugin-react": "^5.0.0",
62
+ "eslint": "^9.33.0",
63
+ "eslint-plugin-react-hooks": "^5.2.0",
64
+ "eslint-plugin-react-refresh": "^0.4.20",
65
+ "globals": "^16.3.0",
66
+ "husky": "^9.1.7",
67
+ "lint-staged": "^16.1.6",
68
+ "prettier-plugin-classnames": "^0.8.3",
69
+ "prettier-plugin-merge": "^0.8.0",
70
+ "prettier-plugin-tailwindcss": "^0.6.14",
71
+ "react": "^19.1.1",
72
+ "react-dom": "^19.1.1",
73
+ "typescript": "~5.8.3",
74
+ "typescript-eslint": "^8.39.1",
75
+ "vite": "^7.1.2",
76
+ "vite-plugin-dts": "^4.5.4"
77
+ },
78
+ "lint-staged": {
79
+ "**/*.{js,jsx,ts,tsx,css,scss,md}": "prettier --write",
80
+ "**/*.{js,jsx,ts,tsx}": [
81
+ "bash -c 'npm run lint'",
82
+ "bash -c 'tsc -b'"
83
+ ]
84
+ }
85
+ }