@jbpark/use-hooks 4.0.1 → 4.0.2
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.ko.md
CHANGED
|
@@ -7,7 +7,9 @@
|
|
|
7
7
|
[](https://github.com/pjb0811/use-hooks/issues)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
📖 **문서 및 라이브 데모:** https://use-hooks-lab.vercel.app
|
|
11
|
+
|
|
12
|
+
일반적인 UI 및 상호작용 패턴을 위한 재사용 가능한 React 19 훅 모음입니다. TypeScript로 빌드되었으며, 서버 사이드 렌더링과 클라이언트 사이드 애플리케이션 모두에 최적화되어 있습니다.
|
|
11
13
|
|
|
12
14
|
## 기능
|
|
13
15
|
|
|
@@ -80,7 +82,7 @@ function MyComponent() {
|
|
|
80
82
|
| `useElementPosition` | 스크롤/리사이즈 시 요소의 바운딩 렉트 모니터링 (요소 참조 지원) |
|
|
81
83
|
| `useResponsiveSize` | Tailwind 유사 브레이크포인트를 포함한 요소 크기 추적 (debounce) |
|
|
82
84
|
| `useViewport` | visualViewport 지원, 인앱 모드 옵션, debounce 포함 |
|
|
83
|
-
| `useScrollToElements` | 키로 요소를 등록하고 키로 스크롤 (오프셋 조절,
|
|
85
|
+
| `useScrollToElements` | 키로 요소를 등록하고 키로 스크롤 (오프셋 조절, 가장 가까운 스크롤 조상을 스크롤) |
|
|
84
86
|
| `useBodyScrollLock` | 스타일 보존을 포함한 바디 스크롤 잠금/해제 (iOS 특별 처리) |
|
|
85
87
|
| `useIntersectionObserver` | 뷰포트 교차 추적, `[ref, { entry, isIntersecting }]` 반환, `freezeOnceVisible` 옵션 |
|
|
86
88
|
| `useResizeObserver` | 콜백 ref로 요소 자체의 너비/높이 추적 (content-box/border-box) |
|
|
@@ -108,22 +110,26 @@ v3.0.0은 breaking change가 여럿 포함된 메이저 릴리스입니다. 전
|
|
|
108
110
|
## 개발
|
|
109
111
|
|
|
110
112
|
```bash
|
|
111
|
-
#
|
|
112
|
-
pnpm dev
|
|
113
|
-
|
|
114
|
-
# 라이브러리 빌드 (tsc + vite)
|
|
113
|
+
# 라이브러리 빌드 (tsc + tsdown)
|
|
115
114
|
pnpm build
|
|
116
115
|
|
|
117
|
-
# 빌드된 라이브러리 미리보기
|
|
118
|
-
pnpm preview
|
|
119
|
-
|
|
120
116
|
# 린트 및 타입 체크
|
|
121
117
|
pnpm lint
|
|
122
118
|
|
|
123
119
|
# prettier로 포맷팅
|
|
124
120
|
pnpm exec prettier --write .
|
|
121
|
+
|
|
122
|
+
# 문서/데모 사이트 시작 (각 훅의 데모는 해당 훅의 문서 페이지에 있습니다)
|
|
123
|
+
pnpm --dir website start
|
|
124
|
+
|
|
125
|
+
# 문서 사이트 의존성 설치 (별도의 pnpm 프로젝트입니다)
|
|
126
|
+
pnpm --dir website install
|
|
125
127
|
```
|
|
126
128
|
|
|
129
|
+
두 `package.json` 모두 `packageManager`에 같은 pnpm 버전을 핀하고 있어,
|
|
130
|
+
`website/` 안에서 pnpm을 실행해도 `PATH`에 깔린 버전이 아니라 핀된 버전이
|
|
131
|
+
쓰입니다. 버전을 올릴 때는 두 곳을 함께 올립니다.
|
|
132
|
+
|
|
127
133
|
## 프로젝트 구조
|
|
128
134
|
|
|
129
135
|
```
|
|
@@ -149,6 +155,9 @@ src/
|
|
|
149
155
|
└── index.ts # 패키지 진입점
|
|
150
156
|
|
|
151
157
|
dist/ # 빌드된 라이브러리 (ESM + types)
|
|
158
|
+
website/ # Docusaurus 문서 및 데모 사이트
|
|
159
|
+
└── src/demo/ # 훅별 인터랙티브 데모 컴포넌트 1개씩
|
|
160
|
+
└── use-x-demo.tsx # 해당 훅의 문서 페이지에 그대로 렌더링됨
|
|
152
161
|
```
|
|
153
162
|
|
|
154
163
|
## 빌드 및 배포
|
|
@@ -164,10 +173,13 @@ dist/ # 빌드된 라이브러리 (ESM + types)
|
|
|
164
173
|
- **ES Module**: `dist/index.mjs`
|
|
165
174
|
- **타입 정의**: `dist/index.d.ts`
|
|
166
175
|
|
|
176
|
+
Docusaurus 문서 사이트는 `website/`에서 빌드되어 Vercel로 배포됩니다
|
|
177
|
+
(`vercel.json` 참고).
|
|
178
|
+
|
|
167
179
|
## 주요 패턴
|
|
168
180
|
|
|
169
181
|
- **훅 1개 = 파일 1개**: 각 훅은 `src/hooks/use-x.ts` 형태의 단일 파일로 존재하며 (폴더/`index.ts` 없음), `src/hooks/index.ts`에서 재수출됩니다
|
|
170
|
-
- **데모 파일 네이밍**: 각 훅의 데모 페이지 파일명은 훅 파일명에 `-demo`를 붙인 `src/demo/use-x-demo.tsx` 형태를 따릅니다 (컴포넌트명 자체는 기존처럼 PascalCase 유지, 예: `ClickOutsideDemo`)
|
|
182
|
+
- **데모 파일 네이밍**: 각 훅의 데모 페이지 파일명은 훅 파일명에 `-demo`를 붙인 `website/src/demo/use-x-demo.tsx` 형태를 따릅니다 (컴포넌트명 자체는 기존처럼 PascalCase 유지, 예: `ClickOutsideDemo`)
|
|
171
183
|
- **Window 보호**: `window`/`document`에 접근하는 훅은 SSR 안전성을 위해 `typeof window` 체크 (예: `useLocalStorage`)
|
|
172
184
|
- **이벤트 리스너**: 모든 스크롤/리사이즈 리스너는 가능한 한 passive 플래그 사용
|
|
173
185
|
- **ResizeObserver**: `useResponsiveSize`와 `useElementPosition`에서 사용하여 성능 최적화
|
package/README.md
CHANGED
|
@@ -7,7 +7,9 @@
|
|
|
7
7
|
[](https://github.com/pjb0811/use-hooks/issues)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
📖 **Documentation & live demos:** https://use-hooks-lab.vercel.app
|
|
11
|
+
|
|
12
|
+
A collection of reusable React 19 hooks for common UI and interaction patterns. Built with TypeScript, optimized for both server-side rendering and client-side applications.
|
|
11
13
|
|
|
12
14
|
## Features
|
|
13
15
|
|
|
@@ -80,7 +82,7 @@ function MyComponent() {
|
|
|
80
82
|
| `useElementPosition` | Monitor element bounding rect on scroll/resize (element ref support) |
|
|
81
83
|
| `useResponsiveSize` | Track element size with Tailwind-like breakpoints (debounced) |
|
|
82
84
|
| `useViewport` | visualViewport support with in-app mode option and debounce |
|
|
83
|
-
| `useScrollToElements` | Register elements by key and scroll to them by key (adjustable offset,
|
|
85
|
+
| `useScrollToElements` | Register elements by key and scroll to them by key (adjustable offset, scrolls the nearest scrollable ancestor) |
|
|
84
86
|
| `useBodyScrollLock` | Lock/unlock body scroll with style preservation (iOS-specific handling) |
|
|
85
87
|
| `useIntersectionObserver` | Track viewport intersection; returns `[ref, { entry, isIntersecting }]` with optional `freezeOnceVisible` |
|
|
86
88
|
| `useResizeObserver` | Track an element's own width/height via a callback ref (content-box or border-box) |
|
|
@@ -108,22 +110,26 @@ v3.0.0 is a major release with several breaking changes. See the
|
|
|
108
110
|
## Development
|
|
109
111
|
|
|
110
112
|
```bash
|
|
111
|
-
#
|
|
112
|
-
pnpm dev
|
|
113
|
-
|
|
114
|
-
# Build library (tsc + vite)
|
|
113
|
+
# Build library (tsc + tsdown)
|
|
115
114
|
pnpm build
|
|
116
115
|
|
|
117
|
-
# Preview built library
|
|
118
|
-
pnpm preview
|
|
119
|
-
|
|
120
116
|
# Run lint and type check
|
|
121
117
|
pnpm lint
|
|
122
118
|
|
|
123
119
|
# Format code with prettier
|
|
124
120
|
pnpm exec prettier --write .
|
|
121
|
+
|
|
122
|
+
# Start the docs/demo site (each hook's demo lives on its docs page)
|
|
123
|
+
pnpm --dir website start
|
|
124
|
+
|
|
125
|
+
# Install the docs site's own dependencies (separate pnpm project)
|
|
126
|
+
pnpm --dir website install
|
|
125
127
|
```
|
|
126
128
|
|
|
129
|
+
Both `package.json` files pin `packageManager` to the same pnpm version, so
|
|
130
|
+
running pnpm inside `website/` picks up that version rather than whatever is
|
|
131
|
+
on `PATH`. Bump the two together.
|
|
132
|
+
|
|
127
133
|
## Project Structure
|
|
128
134
|
|
|
129
135
|
```
|
|
@@ -131,7 +137,7 @@ src/
|
|
|
131
137
|
├── hooks/ # Individual hook implementations (one file per hook)
|
|
132
138
|
│ ├── use-body-scroll-lock.ts
|
|
133
139
|
│ ├── use-click-outside.ts
|
|
134
|
-
│ ├── use-
|
|
140
|
+
│ ├── use-debounced-value.ts
|
|
135
141
|
│ ├── use-element-position.ts
|
|
136
142
|
│ ├── use-element-scroll.ts
|
|
137
143
|
│ ├── use-history-state.ts
|
|
@@ -142,13 +148,16 @@ src/
|
|
|
142
148
|
│ ├── use-recursive-timeout.ts
|
|
143
149
|
│ ├── use-responsive-size.ts
|
|
144
150
|
│ ├── use-scroll-to-elements.ts
|
|
145
|
-
│ ├── use-
|
|
151
|
+
│ ├── use-throttled-value.ts
|
|
146
152
|
│ ├── use-viewport.ts
|
|
147
153
|
│ ├── use-window-scroll.ts
|
|
148
154
|
│ └── index.ts # Barrel export
|
|
149
155
|
└── index.ts # Package entry point
|
|
150
156
|
|
|
151
157
|
dist/ # Built library (ESM + types)
|
|
158
|
+
website/ # Docusaurus documentation & demo site
|
|
159
|
+
└── src/demo/ # One interactive demo component per hook
|
|
160
|
+
└── use-x-demo.tsx # Rendered directly on that hook's docs page
|
|
152
161
|
```
|
|
153
162
|
|
|
154
163
|
## Build & Deployment
|
|
@@ -164,10 +173,13 @@ The library is built as:
|
|
|
164
173
|
- **ES Module**: `dist/index.mjs`
|
|
165
174
|
- **Type Definitions**: `dist/index.d.ts`
|
|
166
175
|
|
|
176
|
+
The Docusaurus documentation site is built from `website/` and deployed via
|
|
177
|
+
Vercel (see `vercel.json`).
|
|
178
|
+
|
|
167
179
|
## Key Patterns
|
|
168
180
|
|
|
169
181
|
- **One File Per Hook**: Each hook lives in a single flat file at `src/hooks/use-x.ts` (no per-hook folder/`index.ts`) and is re-exported from `src/hooks/index.ts`
|
|
170
|
-
- **Demo File Naming**: Each hook's demo page file is named `src/demo/use-x-demo.tsx`, matching the hook's own filename with a `-demo` suffix (the component name itself stays PascalCase, e.g. `ClickOutsideDemo`)
|
|
182
|
+
- **Demo File Naming**: Each hook's demo page file is named `website/src/demo/use-x-demo.tsx`, matching the hook's own filename with a `-demo` suffix (the component name itself stays PascalCase, e.g. `ClickOutsideDemo`)
|
|
171
183
|
- **Window Protection**: Hooks accessing `window`/`document` check `typeof window` for SSR safety (e.g., `useLocalStorage`)
|
|
172
184
|
- **Event Listeners**: All scroll/resize listeners use passive flag when possible
|
|
173
185
|
- **ResizeObserver**: Used in `useResponsiveSize` and `useElementPosition` for performance
|
|
@@ -17,7 +17,6 @@ const lockScroll = (token) => {
|
|
|
17
17
|
width: document.documentElement.style.width
|
|
18
18
|
},
|
|
19
19
|
body: {
|
|
20
|
-
overflow: document.body.style.overflow,
|
|
21
20
|
height: document.body.style.height,
|
|
22
21
|
position: document.body.style.position,
|
|
23
22
|
top: document.body.style.top,
|
|
@@ -32,7 +31,6 @@ const lockScroll = (token) => {
|
|
|
32
31
|
document.documentElement.style.height = "100%";
|
|
33
32
|
document.documentElement.style.position = "fixed";
|
|
34
33
|
document.documentElement.style.width = "100%";
|
|
35
|
-
document.body.style.overflow = "hidden";
|
|
36
34
|
document.body.style.height = "100%";
|
|
37
35
|
document.body.style.position = "fixed";
|
|
38
36
|
document.body.style.top = `-${originalScrollY}px`;
|
|
@@ -51,7 +49,6 @@ const unlockScroll = (token) => {
|
|
|
51
49
|
document.documentElement.style.height = originalStyles.documentElement.height;
|
|
52
50
|
document.documentElement.style.position = originalStyles.documentElement.position;
|
|
53
51
|
document.documentElement.style.width = originalStyles.documentElement.width;
|
|
54
|
-
document.body.style.overflow = originalStyles.body.overflow;
|
|
55
52
|
document.body.style.height = originalStyles.body.height;
|
|
56
53
|
document.body.style.position = originalStyles.body.position;
|
|
57
54
|
document.body.style.top = originalStyles.body.top;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-body-scroll-lock.mjs","names":[],"sources":["../../src/hooks/use-body-scroll-lock.ts"],"sourcesContent":["import { useEffect } from 'react';\n\ninterface LockedStyles {\n documentElement: {\n overflow: string;\n height: string;\n position: string;\n width: string;\n };\n body: {\n
|
|
1
|
+
{"version":3,"file":"use-body-scroll-lock.mjs","names":[],"sources":["../../src/hooks/use-body-scroll-lock.ts"],"sourcesContent":["import { useEffect } from 'react';\n\ninterface LockedStyles {\n documentElement: {\n overflow: string;\n height: string;\n position: string;\n width: string;\n };\n body: {\n height: string;\n position: string;\n top: string;\n left: string;\n right: string;\n width: string;\n paddingRight: string;\n webkitOverflowScrolling: string;\n };\n}\n\n// A Set of per-instance tokens instead of a raw counter — deleting the same\n// token twice (or locking with a token that's already in the set) can't\n// drift the count the way increment/decrement pairs could.\nconst activeLocks = new Set<symbol>();\nlet originalStyles: LockedStyles | null = null;\nlet originalScrollY = 0;\n\nconst isIOS = () =>\n typeof navigator !== 'undefined' &&\n /iPad|iPhone|iPod/.test(navigator.userAgent);\n\nconst lockScroll = (token: symbol) => {\n if (activeLocks.size === 0) {\n originalScrollY = window.scrollY;\n const scrollbarWidth =\n window.innerWidth - document.documentElement.clientWidth;\n const currentPaddingRight =\n parseFloat(getComputedStyle(document.body).paddingRight) || 0;\n\n originalStyles = {\n documentElement: {\n overflow: document.documentElement.style.overflow,\n height: document.documentElement.style.height,\n position: document.documentElement.style.position,\n width: document.documentElement.style.width,\n },\n body: {\n height: document.body.style.height,\n position: document.body.style.position,\n top: document.body.style.top,\n left: document.body.style.left,\n right: document.body.style.right,\n width: document.body.style.width,\n paddingRight: document.body.style.paddingRight,\n webkitOverflowScrolling: document.body.style.getPropertyValue(\n '-webkit-overflow-scrolling',\n ),\n },\n };\n\n document.documentElement.style.overflow = 'hidden';\n document.documentElement.style.height = '100%';\n document.documentElement.style.position = 'fixed';\n document.documentElement.style.width = '100%';\n\n // `overflow: hidden` belongs on the root element only. Setting it on the\n // body as well clips the body's own box — and that box is shifted up by\n // `top: -scrollY`, so everything the user was looking at gets clipped out\n // of view and the page goes blank behind the modal. The overlay survives\n // because a `position: fixed` element isn't clipped by an ancestor's\n // overflow, which makes the failure look like an opaque backdrop rather\n // than a rendering bug.\n document.body.style.height = '100%';\n document.body.style.position = 'fixed';\n document.body.style.top = `-${originalScrollY}px`;\n document.body.style.left = '0';\n document.body.style.right = '0';\n document.body.style.width = '100%';\n\n if (scrollbarWidth > 0) {\n document.body.style.paddingRight = `${currentPaddingRight + scrollbarWidth}px`;\n }\n\n if (isIOS()) {\n document.body.style.setProperty('-webkit-overflow-scrolling', 'touch');\n }\n }\n\n activeLocks.add(token);\n};\n\nconst unlockScroll = (token: symbol) => {\n activeLocks.delete(token);\n\n if (activeLocks.size > 0 || !originalStyles) {\n return;\n }\n\n document.documentElement.style.overflow =\n originalStyles.documentElement.overflow;\n document.documentElement.style.height = originalStyles.documentElement.height;\n document.documentElement.style.position =\n originalStyles.documentElement.position;\n document.documentElement.style.width = originalStyles.documentElement.width;\n\n document.body.style.height = originalStyles.body.height;\n document.body.style.position = originalStyles.body.position;\n document.body.style.top = originalStyles.body.top;\n document.body.style.left = originalStyles.body.left;\n document.body.style.right = originalStyles.body.right;\n document.body.style.width = originalStyles.body.width;\n document.body.style.paddingRight = originalStyles.body.paddingRight;\n\n if (originalStyles.body.webkitOverflowScrolling) {\n document.body.style.setProperty(\n '-webkit-overflow-scrolling',\n originalStyles.body.webkitOverflowScrolling,\n );\n } else {\n document.body.style.removeProperty('-webkit-overflow-scrolling');\n }\n\n window.scrollTo(0, originalScrollY);\n originalStyles = null;\n};\n\nconst useBodyScrollLock = (enabled: boolean = true) => {\n useEffect(() => {\n if (typeof window === 'undefined' || !enabled) {\n return;\n }\n\n const token = Symbol('body-scroll-lock');\n lockScroll(token);\n\n // The position:fixed styles above are the real lock — this is only a\n // narrow safety net for iOS Safari, which can still rubber-band the\n // page on a touchmove that starts directly on the body/html background.\n // Only that one event is handled (no capture, no stopPropagation), so\n // a scrollable element inside the locked content (e.g. a modal body)\n // keeps scrolling normally — its touchmove target isn't body/html.\n let removeTouchListener: (() => void) | undefined;\n\n if (isIOS()) {\n const preventTouchMove = (event: TouchEvent) => {\n if (\n event.target === document.body ||\n event.target === document.documentElement\n ) {\n event.preventDefault();\n }\n };\n\n document.addEventListener('touchmove', preventTouchMove, {\n passive: false,\n });\n\n removeTouchListener = () => {\n document.removeEventListener('touchmove', preventTouchMove);\n };\n }\n\n return () => {\n removeTouchListener?.();\n unlockScroll(token);\n };\n }, [enabled]);\n};\n\nexport default useBodyScrollLock;\n"],"mappings":"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"}
|
|
@@ -4,6 +4,18 @@ const resolveContainer = (container) => {
|
|
|
4
4
|
if (!container) return null;
|
|
5
5
|
return "current" in container ? container.current : container;
|
|
6
6
|
};
|
|
7
|
+
const isScrollable = (element) => {
|
|
8
|
+
const { overflowY } = getComputedStyle(element);
|
|
9
|
+
return (overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay") && element.scrollHeight > element.clientHeight;
|
|
10
|
+
};
|
|
11
|
+
const findScrollableAncestor = (element) => {
|
|
12
|
+
let parent = element.parentElement;
|
|
13
|
+
while (parent && parent !== document.body && parent !== document.documentElement) {
|
|
14
|
+
if (isScrollable(parent)) return parent;
|
|
15
|
+
parent = parent.parentElement;
|
|
16
|
+
}
|
|
17
|
+
return null;
|
|
18
|
+
};
|
|
7
19
|
const useScrollToElements = (defaultOptions) => {
|
|
8
20
|
const elementsRef = useRef(/* @__PURE__ */ new Map());
|
|
9
21
|
const registerCallbacksRef = useRef(/* @__PURE__ */ new Map());
|
|
@@ -31,7 +43,7 @@ const useScrollToElements = (defaultOptions) => {
|
|
|
31
43
|
...options
|
|
32
44
|
};
|
|
33
45
|
if (offset != null) {
|
|
34
|
-
const containerElement = resolveContainer(container ?? null);
|
|
46
|
+
const containerElement = resolveContainer(container ?? null) ?? findScrollableAncestor(element);
|
|
35
47
|
if (containerElement) {
|
|
36
48
|
const containerRect = containerElement.getBoundingClientRect();
|
|
37
49
|
const elementRect = element.getBoundingClientRect();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-scroll-to-elements.mjs","names":[],"sources":["../../src/hooks/use-scroll-to-elements.ts"],"sourcesContent":["import { type RefObject, useCallback, useEffect, useRef } from 'react';\n\ntype ElementKey = string;\n\ntype ScrollContainer = HTMLElement | RefObject<HTMLElement | null> | null;\n\ninterface Options extends ScrollIntoViewOptions {\n offset?: number;\n //
|
|
1
|
+
{"version":3,"file":"use-scroll-to-elements.mjs","names":[],"sources":["../../src/hooks/use-scroll-to-elements.ts"],"sourcesContent":["import { type RefObject, useCallback, useEffect, useRef } from 'react';\n\ntype ElementKey = string;\n\ntype ScrollContainer = HTMLElement | RefObject<HTMLElement | null> | null;\n\ninterface Options extends ScrollIntoViewOptions {\n offset?: number;\n // Explicit scroll container for the `offset` path, for the cases where the\n // automatic lookup below can't pick the right one — e.g. a container that\n // isn't an ancestor of the target, or one that only becomes scrollable\n // later. Leave it unset and the nearest scrollable ancestor is used, with\n // `window` as the final fallback.\n container?: ScrollContainer;\n}\n\nconst resolveContainer = (container: ScrollContainer): HTMLElement | null => {\n if (!container) {\n return null;\n }\n return 'current' in container ? container.current : container;\n};\n\n// `overlay` is a legacy alias of `auto` that still shows up in older WebKit.\n// `hidden` is deliberately excluded: it is programmatically scrollable, but an\n// author who wrote `overflow: hidden` is describing a clipped box, not a\n// scroller, so moving it would be the surprising choice here.\nconst isScrollable = (element: HTMLElement) => {\n const { overflowY } = getComputedStyle(element);\n\n return (\n (overflowY === 'auto' ||\n overflowY === 'scroll' ||\n overflowY === 'overlay') &&\n element.scrollHeight > element.clientHeight\n );\n};\n\n// The no-offset path hands the work to `scrollIntoView`, which finds the\n// nearest scrollable ancestor by itself. The offset path can't use it (see the\n// comment in `scrollTo`), so it has to repeat that lookup — otherwise passing\n// `offset` would silently switch the scroll from the element's own container\n// to `window`, which is never what the call site means.\nconst findScrollableAncestor = (element: HTMLElement): HTMLElement | null => {\n let parent = element.parentElement;\n\n while (\n parent &&\n parent !== document.body &&\n parent !== document.documentElement\n ) {\n if (isScrollable(parent)) {\n return parent;\n }\n parent = parent.parentElement;\n }\n\n return null;\n};\n\nconst useScrollToElements = (defaultOptions?: Options) => {\n const elementsRef = useRef(new Map<ElementKey, HTMLElement>());\n const registerCallbacksRef = useRef(\n new Map<ElementKey, (node: HTMLElement | null) => void>(),\n );\n\n // `defaultOptions` is almost always an inline object literal at the call\n // site, so depending on it directly would recreate `scrollTo` on every\n // render — read the latest value from a ref instead.\n const defaultOptionsRef = useRef(defaultOptions);\n\n useEffect(() => {\n defaultOptionsRef.current = defaultOptions;\n });\n\n // Returns a stable callback per key so React doesn't detach/reattach the\n // ref (and thrash the Map) on every render — only a genuine unmount\n // (node === null) removes the entry.\n const register = useCallback((key: ElementKey) => {\n let callback = registerCallbacksRef.current.get(key);\n\n if (!callback) {\n callback = (node: HTMLElement | null) => {\n if (node) {\n elementsRef.current.set(key, node);\n } else {\n elementsRef.current.delete(key);\n }\n };\n registerCallbacksRef.current.set(key, callback);\n }\n\n return callback;\n }, []);\n\n const scrollTo = useCallback((key: ElementKey, options?: Options) => {\n const element = elementsRef.current.get(key);\n\n if (!element) {\n return;\n }\n\n const { offset, container, ...scrollIntoViewOptions } = {\n ...defaultOptionsRef.current,\n ...options,\n };\n\n // With an offset, `scrollIntoView` and `scrollTo` would both animate\n // the same scroll, fighting each other and settling in the wrong\n // place — use `scrollTo` alone, computed from the element's position\n // before any scrolling starts (not after `scrollIntoView`, where the\n // rect would reflect a mid-animation position).\n if (offset != null) {\n const containerElement =\n resolveContainer(container ?? null) ?? findScrollableAncestor(element);\n\n if (containerElement) {\n const containerRect = containerElement.getBoundingClientRect();\n const elementRect = element.getBoundingClientRect();\n const top =\n containerElement.scrollTop +\n (elementRect.top - containerRect.top) -\n offset;\n\n containerElement.scrollTo({\n top,\n behavior: scrollIntoViewOptions.behavior || 'smooth',\n });\n return;\n }\n\n const top = element.getBoundingClientRect().top + window.scrollY - offset;\n\n window.scrollTo({\n top,\n behavior: scrollIntoViewOptions.behavior || 'smooth',\n });\n return;\n }\n\n element.scrollIntoView({\n behavior: 'smooth',\n block: 'start',\n inline: 'start',\n ...scrollIntoViewOptions,\n });\n }, []);\n\n return { register, scrollTo };\n};\n\nexport default useScrollToElements;\n"],"mappings":";;AAgBA,MAAM,oBAAoB,cAAmD;CAC3E,IAAI,CAAC,WACH,OAAO;CAET,OAAO,aAAa,YAAY,UAAU,UAAU;AACtD;AAMA,MAAM,gBAAgB,YAAyB;CAC7C,MAAM,EAAE,cAAc,iBAAiB,OAAO;CAE9C,QACG,cAAc,UACb,cAAc,YACd,cAAc,cAChB,QAAQ,eAAe,QAAQ;AAEnC;AAOA,MAAM,0BAA0B,YAA6C;CAC3E,IAAI,SAAS,QAAQ;CAErB,OACE,UACA,WAAW,SAAS,QACpB,WAAW,SAAS,iBACpB;EACA,IAAI,aAAa,MAAM,GACrB,OAAO;EAET,SAAS,OAAO;CAClB;CAEA,OAAO;AACT;AAEA,MAAM,uBAAuB,mBAA6B;CACxD,MAAM,cAAc,uBAAO,IAAI,IAA6B,CAAC;CAC7D,MAAM,uBAAuB,uBAC3B,IAAI,IAAoD,CAC1D;CAKA,MAAM,oBAAoB,OAAO,cAAc;CAE/C,gBAAgB;EACd,kBAAkB,UAAU;CAC9B,CAAC;CA2ED,OAAO;EAAE,UAtEQ,aAAa,QAAoB;GAChD,IAAI,WAAW,qBAAqB,QAAQ,IAAI,GAAG;GAEnD,IAAI,CAAC,UAAU;IACb,YAAY,SAA6B;KACvC,IAAI,MACF,YAAY,QAAQ,IAAI,KAAK,IAAI;UAEjC,YAAY,QAAQ,OAAO,GAAG;IAElC;IACA,qBAAqB,QAAQ,IAAI,KAAK,QAAQ;GAChD;GAEA,OAAO;EACT,GAAG,CAAC,CAuDY;EAAG,UArDF,aAAa,KAAiB,YAAsB;GACnE,MAAM,UAAU,YAAY,QAAQ,IAAI,GAAG;GAE3C,IAAI,CAAC,SACH;GAGF,MAAM,EAAE,QAAQ,WAAW,GAAG,0BAA0B;IACtD,GAAG,kBAAkB;IACrB,GAAG;GACL;GAOA,IAAI,UAAU,MAAM;IAClB,MAAM,mBACJ,iBAAiB,aAAa,IAAI,KAAK,uBAAuB,OAAO;IAEvE,IAAI,kBAAkB;KACpB,MAAM,gBAAgB,iBAAiB,sBAAsB;KAC7D,MAAM,cAAc,QAAQ,sBAAsB;KAClD,MAAM,MACJ,iBAAiB,aAChB,YAAY,MAAM,cAAc,OACjC;KAEF,iBAAiB,SAAS;MACxB;MACA,UAAU,sBAAsB,YAAY;KAC9C,CAAC;KACD;IACF;IAEA,MAAM,MAAM,QAAQ,sBAAsB,CAAC,CAAC,MAAM,OAAO,UAAU;IAEnE,OAAO,SAAS;KACd;KACA,UAAU,sBAAsB,YAAY;IAC9C,CAAC;IACD;GACF;GAEA,QAAQ,eAAe;IACrB,UAAU;IACV,OAAO;IACP,QAAQ;IACR,GAAG;GACL,CAAC;EACH,GAAG,CAAC,CAEsB;CAAE;AAC9B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jbpark/use-hooks",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.2",
|
|
4
4
|
"description": "A collection of reusable React 19 hooks for common UI and interaction patterns",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -39,11 +39,8 @@
|
|
|
39
39
|
"dist"
|
|
40
40
|
],
|
|
41
41
|
"scripts": {
|
|
42
|
-
"dev": "vite",
|
|
43
42
|
"build": "tsc -b && tsdown",
|
|
44
|
-
"build:demo": "vite build",
|
|
45
43
|
"lint": "eslint .",
|
|
46
|
-
"preview": "vite preview",
|
|
47
44
|
"prepublishOnly": "pnpm build",
|
|
48
45
|
"prepare": "husky"
|
|
49
46
|
},
|
|
@@ -54,13 +51,10 @@
|
|
|
54
51
|
"devDependencies": {
|
|
55
52
|
"@changesets/cli": "^3.0.0",
|
|
56
53
|
"@eslint/js": "^9.39.5",
|
|
57
|
-
"@jbpark/ui-kit": "^5.2.0",
|
|
58
|
-
"@radix-ui/react-icons": "^1.3.2",
|
|
59
54
|
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
|
|
60
55
|
"@types/node": "^26.2.0",
|
|
61
56
|
"@types/react": "^19.2.18",
|
|
62
57
|
"@types/react-dom": "^19.2.4",
|
|
63
|
-
"@vitejs/plugin-react": "^6.0.5",
|
|
64
58
|
"eslint": "^9.39.5",
|
|
65
59
|
"eslint-plugin-react-hooks": "^6.1.1",
|
|
66
60
|
"eslint-plugin-react-refresh": "^0.5.4",
|
|
@@ -73,12 +67,9 @@
|
|
|
73
67
|
"prettier-plugin-tailwindcss": "^0.8.1",
|
|
74
68
|
"react": "^19.2.8",
|
|
75
69
|
"react-dom": "^19.2.8",
|
|
76
|
-
"react-router-dom": "^7.18.2",
|
|
77
70
|
"tsdown": "^0.22.14",
|
|
78
71
|
"typescript": "~6.0.3",
|
|
79
|
-
"typescript-eslint": "^8.67.0"
|
|
80
|
-
"vite": "^8.2.1",
|
|
81
|
-
"vite-plugin-dts": "^5.0.3"
|
|
72
|
+
"typescript-eslint": "^8.67.0"
|
|
82
73
|
},
|
|
83
74
|
"lint-staged": {
|
|
84
75
|
"**/*.{js,jsx,ts,tsx,css,scss,md}": "prettier --write",
|