@jbpark/use-hooks 2.11.0 → 4.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.ko.md +40 -22
- package/README.md +40 -22
- package/dist/hooks/index.d.mts +14 -3
- package/dist/hooks/index.mjs +14 -3
- package/dist/hooks/use-click-outside.d.mts +9 -2
- package/dist/hooks/use-click-outside.mjs +27 -11
- package/dist/hooks/use-click-outside.mjs.map +1 -1
- package/dist/hooks/use-debounced-callback.d.mts +14 -0
- package/dist/hooks/{use-debounce.mjs → use-debounced-callback.mjs} +4 -4
- package/dist/hooks/use-debounced-callback.mjs.map +1 -0
- package/dist/hooks/use-debounced-value.d.mts +5 -0
- package/dist/hooks/use-debounced-value.mjs +20 -0
- package/dist/hooks/use-debounced-value.mjs.map +1 -0
- package/dist/hooks/use-event-listener.d.mts +21 -0
- package/dist/hooks/use-event-listener.mjs +50 -0
- package/dist/hooks/use-event-listener.mjs.map +1 -0
- package/dist/hooks/use-file-drop.d.mts +14 -0
- package/dist/hooks/use-file-drop.mjs +85 -0
- package/dist/hooks/use-file-drop.mjs.map +1 -0
- package/dist/hooks/use-image.d.mts +2 -1
- package/dist/hooks/use-image.mjs +4 -3
- package/dist/hooks/use-image.mjs.map +1 -1
- package/dist/hooks/use-intersection-observer.d.mts +8 -1
- package/dist/hooks/use-intersection-observer.mjs +37 -5
- package/dist/hooks/use-intersection-observer.mjs.map +1 -1
- package/dist/hooks/use-interval.d.mts +5 -0
- package/dist/hooks/use-interval.mjs +20 -0
- package/dist/hooks/use-interval.mjs.map +1 -0
- package/dist/hooks/use-key-press.d.mts +14 -0
- package/dist/hooks/use-key-press.mjs +85 -0
- package/dist/hooks/use-key-press.mjs.map +1 -0
- package/dist/hooks/use-merged-ref.d.mts +8 -0
- package/dist/hooks/use-merged-ref.mjs +31 -0
- package/dist/hooks/use-merged-ref.mjs.map +1 -0
- package/dist/hooks/use-mutation-observer.d.mts +11 -0
- package/dist/hooks/use-mutation-observer.mjs +47 -0
- package/dist/hooks/use-mutation-observer.mjs.map +1 -0
- package/dist/hooks/use-previous.d.mts +5 -0
- package/dist/hooks/use-previous.mjs +14 -0
- package/dist/hooks/use-previous.mjs.map +1 -0
- package/dist/hooks/use-resize-observer.d.mts +12 -0
- package/dist/hooks/use-resize-observer.mjs +53 -0
- package/dist/hooks/use-resize-observer.mjs.map +1 -0
- package/dist/hooks/use-responsive-size.mjs +2 -2
- package/dist/hooks/use-responsive-size.mjs.map +1 -1
- package/dist/hooks/use-scroll-to-elements.d.mts +7 -5
- package/dist/hooks/use-scroll-to-elements.mjs +52 -27
- package/dist/hooks/use-scroll-to-elements.mjs.map +1 -1
- package/dist/hooks/use-throttled-callback.d.mts +12 -0
- package/dist/hooks/use-throttled-callback.mjs +54 -0
- package/dist/hooks/use-throttled-callback.mjs.map +1 -0
- package/dist/hooks/use-throttled-value.d.mts +9 -0
- package/dist/hooks/use-throttled-value.mjs +16 -0
- package/dist/hooks/use-throttled-value.mjs.map +1 -0
- package/dist/hooks/use-timeout.d.mts +8 -0
- package/dist/hooks/use-timeout.mjs +38 -0
- package/dist/hooks/use-timeout.mjs.map +1 -0
- package/dist/hooks/use-toggle.d.mts +5 -0
- package/dist/hooks/use-toggle.mjs +17 -0
- package/dist/hooks/use-toggle.mjs.map +1 -0
- package/dist/index.d.mts +15 -4
- package/dist/index.mjs +15 -4
- package/package.json +1 -1
- package/dist/hooks/use-debounce.d.mts +0 -14
- package/dist/hooks/use-debounce.mjs.map +0 -1
- package/dist/hooks/use-throttle.d.mts +0 -5
- package/dist/hooks/use-throttle.mjs +0 -42
- package/dist/hooks/use-throttle.mjs.map +0 -1
- package/dist/hooks/use-timeline.d.mts +0 -50
- package/dist/hooks/use-timeline.mjs +0 -211
- package/dist/hooks/use-timeline.mjs.map +0 -1
package/README.ko.md
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
## 기능
|
|
13
13
|
|
|
14
|
-
- 📦 **
|
|
14
|
+
- 📦 **30개 프로덕션 레디 훅** - 스크롤, 뷰포트, 스토리지, 옵저버, 이벤트, 타이밍 등 다양한 유틸리티
|
|
15
15
|
- 🎯 **TypeScript 지원** - 완전한 타입 지원으로 더 나은 개발 경험
|
|
16
16
|
- ⚡ **트리 셰이킹 지원** - 필요한 것만 임포트하세요
|
|
17
17
|
- 🔒 **SSR 안전** - window/document 전역 변수에 대한 보호
|
|
@@ -36,7 +36,7 @@ pnpm add @jbpark/use-hooks
|
|
|
36
36
|
import {
|
|
37
37
|
useLocalStorage,
|
|
38
38
|
useResponsiveSize,
|
|
39
|
-
|
|
39
|
+
useThrottledValue,
|
|
40
40
|
useWindowScroll,
|
|
41
41
|
} from '@jbpark/use-hooks';
|
|
42
42
|
|
|
@@ -51,7 +51,7 @@ function MyComponent() {
|
|
|
51
51
|
const { size, breakpoint, ref } = useResponsiveSize();
|
|
52
52
|
|
|
53
53
|
// 너비 업데이트를 스로틀링
|
|
54
|
-
const throttledWidth =
|
|
54
|
+
const throttledWidth = useThrottledValue(size.width, 200);
|
|
55
55
|
|
|
56
56
|
return (
|
|
57
57
|
<div ref={ref}>
|
|
@@ -67,25 +67,43 @@ function MyComponent() {
|
|
|
67
67
|
|
|
68
68
|
## 사용 가능한 훅
|
|
69
69
|
|
|
70
|
-
| 훅 | 설명
|
|
71
|
-
| ------------------------- |
|
|
72
|
-
| `useLocalStorage` | 에러 핸들링이 포함된 JSON 기반 영속 상태 (SSR 안전)
|
|
73
|
-
| `
|
|
74
|
-
| `
|
|
75
|
-
| `
|
|
76
|
-
| `
|
|
77
|
-
| `
|
|
78
|
-
| `
|
|
79
|
-
| `
|
|
80
|
-
| `
|
|
81
|
-
| `
|
|
82
|
-
| `useViewport` | visualViewport 지원, 인앱 모드 옵션, debounce 포함
|
|
83
|
-
| `
|
|
84
|
-
| `
|
|
85
|
-
| `
|
|
86
|
-
| `
|
|
87
|
-
| `
|
|
88
|
-
| `
|
|
70
|
+
| 훅 | 설명 |
|
|
71
|
+
| ------------------------- | ------------------------------------------------------------------------------------------- |
|
|
72
|
+
| `useLocalStorage` | 에러 핸들링이 포함된 JSON 기반 영속 상태 (SSR 안전) |
|
|
73
|
+
| `useHistoryState` | 히스토리 개수 제한을 설정할 수 있는 실행 취소/다시 실행 상태 관리 |
|
|
74
|
+
| `useControllableState` | value/defaultValue/onChange prop 조합을 훅 하나로 제어/비제어 상태 관리 |
|
|
75
|
+
| `usePrevious` | 이전 렌더 시점의 값을 반환 |
|
|
76
|
+
| `useToggle` | 토글 함수와 명시적 setter를 제공하는 불리언 상태 |
|
|
77
|
+
| `useMultiSelect` | shift-클릭 범위 선택을 지원하는 체크박스 스타일 다중 선택 |
|
|
78
|
+
| `useWindowScroll` | 윈도우 스크롤 위치 및 백분율 추적 (iOS visualViewport 대응) |
|
|
79
|
+
| `useElementScroll` | ResizeObserver를 사용한 특정 요소의 스크롤 상태 추적 |
|
|
80
|
+
| `useElementPosition` | 스크롤/리사이즈 시 요소의 바운딩 렉트 모니터링 (요소 참조 지원) |
|
|
81
|
+
| `useResponsiveSize` | Tailwind 유사 브레이크포인트를 포함한 요소 크기 추적 (debounce) |
|
|
82
|
+
| `useViewport` | visualViewport 지원, 인앱 모드 옵션, debounce 포함 |
|
|
83
|
+
| `useScrollToElements` | 키로 요소를 등록하고 키로 스크롤 (오프셋 조절, 컨테이너 지정 가능) |
|
|
84
|
+
| `useBodyScrollLock` | 스타일 보존을 포함한 바디 스크롤 잠금/해제 (iOS 특별 처리) |
|
|
85
|
+
| `useIntersectionObserver` | 뷰포트 교차 추적, `[ref, { entry, isIntersecting }]` 반환, `freezeOnceVisible` 옵션 |
|
|
86
|
+
| `useResizeObserver` | 콜백 ref로 요소 자체의 너비/높이 추적 (content-box/border-box) |
|
|
87
|
+
| `useMutationObserver` | ref 또는 raw 노드(예: `document.head`)의 DOM 변경 관측 |
|
|
88
|
+
| `useEventListener` | `window`, ref, raw 타겟에 이벤트 리스너 등록/해제 |
|
|
89
|
+
| `useClickOutside` | 참조한 요소(들) 바깥 클릭/터치(또는 opt-in `escape`로 `Escape`) 시 콜백 실행, 다중 ref 지원 |
|
|
90
|
+
| `useKeyPress` | `mod`/`ctrl`/`meta`/`shift`/`alt` 조합과 `space`/`esc` 별칭으로 키 콜백 실행 |
|
|
91
|
+
| `useFileDrop` | `accept`/`multiple` 필터링을 갖춘 드래그앤드롭 존, `{ dropRef, isDragging }` 반환 |
|
|
92
|
+
| `useFileToDataUrl` | `File`/`Blob`을 data URL로 변환 |
|
|
93
|
+
| `useDebouncedCallback` | deps 변경 시 debounce된 콜백 자동 실행 (`leading`/`autoInvoke` 옵션); 별칭: `useDebounce` |
|
|
94
|
+
| `useDebouncedValue` | 변하는 값을 일정 지연으로 debounce |
|
|
95
|
+
| `useThrottledValue` | 값 업데이트를 일정 간격으로 제한; 별칭: `useThrottle` |
|
|
96
|
+
| `useThrottledCallback` | 콜백을 일정 간격으로 제한 |
|
|
97
|
+
| `useTimeout` | 지연 후 콜백 1회 실행, `{ reset, clear }` 반환 (`null`이면 일시정지) |
|
|
98
|
+
| `useInterval` | 일정 간격으로 콜백 실행 (`null`이면 일시정지) |
|
|
99
|
+
| `useRecursiveTimeout` | 비동기/동기 콜백을 재귀적으로 스케줄링 |
|
|
100
|
+
| `useMergedRef` | 여러 객체/콜백 ref를 하나의 콜백 ref로 병합 |
|
|
101
|
+
| `useImage` | 이미지 사전로드 및 `loading`/`error`(`Error`)/`loaded`/`attemptCount`/`retry` 노출 |
|
|
102
|
+
|
|
103
|
+
## v2에서 마이그레이션
|
|
104
|
+
|
|
105
|
+
v3.0.0은 breaking change가 여럿 포함된 메이저 릴리스입니다. 전후 예제는
|
|
106
|
+
[마이그레이션 가이드](./MIGRATION.ko.md)를 참고하세요.
|
|
89
107
|
|
|
90
108
|
## 개발
|
|
91
109
|
|
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ A collection of reusable React 19 hooks for common UI and interaction patterns.
|
|
|
11
11
|
|
|
12
12
|
## Features
|
|
13
13
|
|
|
14
|
-
- 📦 **
|
|
14
|
+
- 📦 **30 Production-Ready Hooks** - Utilities for scrolling, viewport, storage, observers, events, timing, and more
|
|
15
15
|
- 🎯 **Full TypeScript Support** - Complete type definitions for better development experience
|
|
16
16
|
- ⚡ **Tree-Shakeable** - Import only what you need
|
|
17
17
|
- 🔒 **SSR-Safe** - Built-in protection for window/document globals
|
|
@@ -36,7 +36,7 @@ pnpm add @jbpark/use-hooks
|
|
|
36
36
|
import {
|
|
37
37
|
useLocalStorage,
|
|
38
38
|
useResponsiveSize,
|
|
39
|
-
|
|
39
|
+
useThrottledValue,
|
|
40
40
|
useWindowScroll,
|
|
41
41
|
} from '@jbpark/use-hooks';
|
|
42
42
|
|
|
@@ -51,7 +51,7 @@ function MyComponent() {
|
|
|
51
51
|
const { size, breakpoint, ref } = useResponsiveSize();
|
|
52
52
|
|
|
53
53
|
// Throttled width update
|
|
54
|
-
const throttledWidth =
|
|
54
|
+
const throttledWidth = useThrottledValue(size.width, 200);
|
|
55
55
|
|
|
56
56
|
return (
|
|
57
57
|
<div ref={ref}>
|
|
@@ -67,25 +67,43 @@ function MyComponent() {
|
|
|
67
67
|
|
|
68
68
|
## Available Hooks
|
|
69
69
|
|
|
70
|
-
| Hook | Description
|
|
71
|
-
| ------------------------- |
|
|
72
|
-
| `useLocalStorage` | JSON-based persistent state with error handling (SSR-safe)
|
|
73
|
-
| `
|
|
74
|
-
| `
|
|
75
|
-
| `
|
|
76
|
-
| `
|
|
77
|
-
| `
|
|
78
|
-
| `
|
|
79
|
-
| `
|
|
80
|
-
| `
|
|
81
|
-
| `
|
|
82
|
-
| `useViewport` | visualViewport support with in-app mode option and debounce
|
|
83
|
-
| `
|
|
84
|
-
| `
|
|
85
|
-
| `
|
|
86
|
-
| `
|
|
87
|
-
| `
|
|
88
|
-
| `
|
|
70
|
+
| Hook | Description |
|
|
71
|
+
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
|
72
|
+
| `useLocalStorage` | JSON-based persistent state with error handling (SSR-safe) |
|
|
73
|
+
| `useHistoryState` | Undo/redo state management with a configurable history limit |
|
|
74
|
+
| `useControllableState` | Back a value/defaultValue/onChange prop pair with one controlled/uncontrolled state hook |
|
|
75
|
+
| `usePrevious` | Return a value as it was on the previous render |
|
|
76
|
+
| `useToggle` | Boolean state with a toggle and an explicit setter |
|
|
77
|
+
| `useMultiSelect` | Checkbox-style multi-select for a list, with shift-click range selection |
|
|
78
|
+
| `useWindowScroll` | Track window scroll position and percentage (iOS visualViewport compatible) |
|
|
79
|
+
| `useElementScroll` | Monitor scroll state of specific elements using ResizeObserver |
|
|
80
|
+
| `useElementPosition` | Monitor element bounding rect on scroll/resize (element ref support) |
|
|
81
|
+
| `useResponsiveSize` | Track element size with Tailwind-like breakpoints (debounced) |
|
|
82
|
+
| `useViewport` | visualViewport support with in-app mode option and debounce |
|
|
83
|
+
| `useScrollToElements` | Register elements by key and scroll to them by key (adjustable offset, optional container) |
|
|
84
|
+
| `useBodyScrollLock` | Lock/unlock body scroll with style preservation (iOS-specific handling) |
|
|
85
|
+
| `useIntersectionObserver` | Track viewport intersection; returns `[ref, { entry, isIntersecting }]` with optional `freezeOnceVisible` |
|
|
86
|
+
| `useResizeObserver` | Track an element's own width/height via a callback ref (content-box or border-box) |
|
|
87
|
+
| `useMutationObserver` | Observe DOM mutations on a ref or a raw node (e.g. `document.head`) |
|
|
88
|
+
| `useEventListener` | Add/remove an event listener on `window`, a ref, or a raw target |
|
|
89
|
+
| `useClickOutside` | Run a callback when a click/touch (or `Escape`, opt-in via `escape`) happens outside the referenced element(s); accepts multiple refs |
|
|
90
|
+
| `useKeyPress` | Run a callback on key combos with `mod`/`ctrl`/`meta`/`shift`/`alt` and aliases like `space`/`esc` |
|
|
91
|
+
| `useFileDrop` | Drag-and-drop file zone with `accept`/`multiple` filtering; returns `{ dropRef, isDragging }` |
|
|
92
|
+
| `useFileToDataUrl` | Read a `File`/`Blob` into a data URL |
|
|
93
|
+
| `useDebouncedCallback` | Auto-invoke a debounced callback when deps change (`leading`/`autoInvoke` options); alias: `useDebounce` |
|
|
94
|
+
| `useDebouncedValue` | Debounce a changing value to a fixed delay |
|
|
95
|
+
| `useThrottledValue` | Throttle value updates to a fixed interval; alias: `useThrottle` |
|
|
96
|
+
| `useThrottledCallback` | Throttle a callback to a fixed interval |
|
|
97
|
+
| `useTimeout` | Run a callback once after a delay; returns `{ reset, clear }` (`null` pauses) |
|
|
98
|
+
| `useInterval` | Run a callback on an interval (`null` pauses) |
|
|
99
|
+
| `useRecursiveTimeout` | Recursively schedule async/sync callbacks |
|
|
100
|
+
| `useMergedRef` | Merge multiple object/callback refs into one callback ref |
|
|
101
|
+
| `useImage` | Preload an image and expose `loading`/`error` (an `Error`)/`loaded`/`attemptCount`/`retry` |
|
|
102
|
+
|
|
103
|
+
## Migrating from v2
|
|
104
|
+
|
|
105
|
+
v3.0.0 is a major release with several breaking changes. See the
|
|
106
|
+
[Migration Guide](./MIGRATION.md) for before/after examples.
|
|
89
107
|
|
|
90
108
|
## Development
|
|
91
109
|
|
package/dist/hooks/index.d.mts
CHANGED
|
@@ -1,19 +1,30 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { useDebouncedCallback } from "./use-debounced-callback.mjs";
|
|
2
|
+
import { useDebouncedValue } from "./use-debounced-value.mjs";
|
|
2
3
|
import { useBodyScrollLock } from "./use-body-scroll-lock.mjs";
|
|
3
4
|
import { useClickOutside } from "./use-click-outside.mjs";
|
|
4
5
|
import { useControllableState } from "./use-controllable-state.mjs";
|
|
5
6
|
import { useElementPosition } from "./use-element-position.mjs";
|
|
6
7
|
import { useElementScroll } from "./use-element-scroll.mjs";
|
|
8
|
+
import { useEventListener } from "./use-event-listener.mjs";
|
|
9
|
+
import { useFileDrop } from "./use-file-drop.mjs";
|
|
7
10
|
import { useFileToDataUrl } from "./use-file-to-data-url.mjs";
|
|
8
11
|
import { useHistoryState } from "./use-history-state.mjs";
|
|
9
12
|
import { useIntersectionObserver } from "./use-intersection-observer.mjs";
|
|
13
|
+
import { useInterval } from "./use-interval.mjs";
|
|
10
14
|
import { useResponsiveSize } from "./use-responsive-size.mjs";
|
|
11
15
|
import { useImage } from "./use-image.mjs";
|
|
16
|
+
import { useKeyPress } from "./use-key-press.mjs";
|
|
12
17
|
import { useLocalStorage } from "./use-local-storage.mjs";
|
|
18
|
+
import { useMergedRef } from "./use-merged-ref.mjs";
|
|
13
19
|
import { useMultiSelect } from "./use-multi-select.mjs";
|
|
20
|
+
import { useMutationObserver } from "./use-mutation-observer.mjs";
|
|
21
|
+
import { usePrevious } from "./use-previous.mjs";
|
|
14
22
|
import { useRecursiveTimeout } from "./use-recursive-timeout.mjs";
|
|
23
|
+
import { useResizeObserver } from "./use-resize-observer.mjs";
|
|
15
24
|
import { useScrollToElements } from "./use-scroll-to-elements.mjs";
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
25
|
+
import { useThrottledValue } from "./use-throttled-value.mjs";
|
|
26
|
+
import { useThrottledCallback } from "./use-throttled-callback.mjs";
|
|
27
|
+
import { useTimeout } from "./use-timeout.mjs";
|
|
28
|
+
import { useToggle } from "./use-toggle.mjs";
|
|
18
29
|
import { useWindowScroll } from "./use-window-scroll.mjs";
|
|
19
30
|
import { useViewport } from "./use-viewport.mjs";
|
package/dist/hooks/index.mjs
CHANGED
|
@@ -1,20 +1,31 @@
|
|
|
1
|
-
import
|
|
1
|
+
import useDebouncedCallback from "./use-debounced-callback.mjs";
|
|
2
|
+
import useDebouncedValue from "./use-debounced-value.mjs";
|
|
2
3
|
import useBodyScrollLock from "./use-body-scroll-lock.mjs";
|
|
3
4
|
import useClickOutside from "./use-click-outside.mjs";
|
|
4
5
|
import useControllableState from "./use-controllable-state.mjs";
|
|
5
6
|
import useElementPosition from "./use-element-position.mjs";
|
|
6
7
|
import useElementScroll from "./use-element-scroll.mjs";
|
|
8
|
+
import useEventListener from "./use-event-listener.mjs";
|
|
9
|
+
import useFileDrop from "./use-file-drop.mjs";
|
|
7
10
|
import useFileToDataUrl from "./use-file-to-data-url.mjs";
|
|
8
11
|
import useHistoryState from "./use-history-state.mjs";
|
|
9
12
|
import useIntersectionObserver from "./use-intersection-observer.mjs";
|
|
13
|
+
import useInterval from "./use-interval.mjs";
|
|
10
14
|
import useResponsiveSize from "./use-responsive-size.mjs";
|
|
11
15
|
import useImage from "./use-image.mjs";
|
|
16
|
+
import useKeyPress from "./use-key-press.mjs";
|
|
12
17
|
import useLocalStorage from "./use-local-storage.mjs";
|
|
18
|
+
import useMergedRef from "./use-merged-ref.mjs";
|
|
13
19
|
import useMultiSelect from "./use-multi-select.mjs";
|
|
20
|
+
import useMutationObserver from "./use-mutation-observer.mjs";
|
|
21
|
+
import usePrevious from "./use-previous.mjs";
|
|
14
22
|
import useRecursiveTimeout from "./use-recursive-timeout.mjs";
|
|
23
|
+
import useResizeObserver from "./use-resize-observer.mjs";
|
|
15
24
|
import useScrollToElements from "./use-scroll-to-elements.mjs";
|
|
16
|
-
import
|
|
17
|
-
import
|
|
25
|
+
import useThrottledCallback from "./use-throttled-callback.mjs";
|
|
26
|
+
import useThrottledValue from "./use-throttled-value.mjs";
|
|
27
|
+
import useTimeout from "./use-timeout.mjs";
|
|
28
|
+
import useToggle from "./use-toggle.mjs";
|
|
18
29
|
import useWindowScroll from "./use-window-scroll.mjs";
|
|
19
30
|
import useViewport from "./use-viewport.mjs";
|
|
20
31
|
|
|
@@ -1,7 +1,14 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { RefObject } from "react";
|
|
2
2
|
|
|
3
3
|
//#region src/hooks/use-click-outside.d.ts
|
|
4
|
-
|
|
4
|
+
type ClickOutsideRef = RefObject<HTMLElement | null> | null | undefined;
|
|
5
|
+
type ClickOutsideEvent = PointerEvent | MouseEvent | TouchEvent | KeyboardEvent;
|
|
6
|
+
interface Options {
|
|
7
|
+
enabled?: boolean;
|
|
8
|
+
events?: ('pointerdown' | 'mousedown' | 'touchstart')[];
|
|
9
|
+
escape?: boolean;
|
|
10
|
+
}
|
|
11
|
+
declare const useClickOutside: (refs: ClickOutsideRef | ClickOutsideRef[], handler: (event: ClickOutsideEvent) => void, options?: Options) => void;
|
|
5
12
|
//#endregion
|
|
6
13
|
export { useClickOutside };
|
|
7
14
|
//# sourceMappingURL=use-click-outside.d.mts.map
|
|
@@ -1,27 +1,43 @@
|
|
|
1
1
|
import { useEffect, useRef } from "react";
|
|
2
2
|
|
|
3
3
|
//#region src/hooks/use-click-outside.ts
|
|
4
|
-
const useClickOutside = (handler,
|
|
5
|
-
const
|
|
4
|
+
const useClickOutside = (refs, handler, options = {}) => {
|
|
5
|
+
const { enabled = true, events = ["pointerdown"], escape = false } = options;
|
|
6
6
|
const handlerRef = useRef(handler);
|
|
7
7
|
useEffect(() => {
|
|
8
8
|
handlerRef.current = handler;
|
|
9
9
|
});
|
|
10
|
+
const refList = Array.isArray(refs) ? refs : [refs];
|
|
11
|
+
const refListRef = useRef(refList);
|
|
12
|
+
useEffect(() => {
|
|
13
|
+
refListRef.current = refList;
|
|
14
|
+
});
|
|
10
15
|
useEffect(() => {
|
|
11
16
|
if (!enabled || typeof document === "undefined") return;
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
17
|
+
const isInside = (target) => refListRef.current.some((ref) => ref?.current?.contains(target));
|
|
18
|
+
const onPointerEvent = (event) => {
|
|
19
|
+
const target = event.target;
|
|
20
|
+
if (!target || isInside(target)) return;
|
|
15
21
|
handlerRef.current(event);
|
|
16
22
|
};
|
|
17
|
-
|
|
18
|
-
|
|
23
|
+
const onKeyDown = (event) => {
|
|
24
|
+
if (event.key === "Escape") handlerRef.current(event);
|
|
25
|
+
};
|
|
26
|
+
events.forEach((eventName) => {
|
|
27
|
+
document.addEventListener(eventName, onPointerEvent);
|
|
28
|
+
});
|
|
29
|
+
if (escape) document.addEventListener("keydown", onKeyDown);
|
|
19
30
|
return () => {
|
|
20
|
-
|
|
21
|
-
|
|
31
|
+
events.forEach((eventName) => {
|
|
32
|
+
document.removeEventListener(eventName, onPointerEvent);
|
|
33
|
+
});
|
|
34
|
+
if (escape) document.removeEventListener("keydown", onKeyDown);
|
|
22
35
|
};
|
|
23
|
-
}, [
|
|
24
|
-
|
|
36
|
+
}, [
|
|
37
|
+
enabled,
|
|
38
|
+
escape,
|
|
39
|
+
events.join(",")
|
|
40
|
+
]);
|
|
25
41
|
};
|
|
26
42
|
|
|
27
43
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-click-outside.mjs","names":[],"sources":["../../src/hooks/use-click-outside.ts"],"sourcesContent":["import { useEffect, useRef } from 'react';\n\
|
|
1
|
+
{"version":3,"file":"use-click-outside.mjs","names":[],"sources":["../../src/hooks/use-click-outside.ts"],"sourcesContent":["import { type RefObject, useEffect, useRef } from 'react';\n\ntype ClickOutsideRef = RefObject<HTMLElement | null> | null | undefined;\n\ntype ClickOutsideEvent = PointerEvent | MouseEvent | TouchEvent | KeyboardEvent;\n\ninterface Options {\n enabled?: boolean;\n events?: ('pointerdown' | 'mousedown' | 'touchstart')[];\n escape?: boolean;\n}\n\n// Takes the \"inside\" ref(s) as an argument instead of creating and\n// returning one — lets a caller pass multiple exclusion targets (e.g. a\n// dropdown's trigger button *and* its portaled panel, which live in\n// different DOM subtrees) instead of only ever watching one element.\nconst useClickOutside = (\n refs: ClickOutsideRef | ClickOutsideRef[],\n handler: (event: ClickOutsideEvent) => void,\n options: Options = {},\n) => {\n // `escape` is opt-in (default `false`): the hook is named for clicks, and\n // an always-on Escape handler both surprises callers who already handle\n // Escape themselves (double-fire) and closes every layer at once in\n // nested UI (a dropdown inside a modal). Turn it on where you want it.\n const { enabled = true, events = ['pointerdown'], escape = false } = options;\n\n const handlerRef = useRef(handler);\n\n useEffect(() => {\n handlerRef.current = handler;\n });\n\n const refList = Array.isArray(refs) ? refs : [refs];\n // `refs` is almost always an inline array literal at the call site, so\n // depending on it directly would tear down/rebuild the listeners on\n // every render — read the latest value from a ref instead.\n const refListRef = useRef(refList);\n\n useEffect(() => {\n refListRef.current = refList;\n });\n\n const eventsKey = events.join(',');\n\n useEffect(() => {\n if (!enabled || typeof document === 'undefined') {\n return;\n }\n\n const isInside = (target: Node) =>\n refListRef.current.some(ref => ref?.current?.contains(target));\n\n const onPointerEvent = (event: Event) => {\n const target = event.target as Node | null;\n\n if (!target || isInside(target)) {\n return;\n }\n\n handlerRef.current(event as ClickOutsideEvent);\n };\n\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n handlerRef.current(event);\n }\n };\n\n events.forEach(eventName => {\n document.addEventListener(eventName, onPointerEvent);\n });\n\n if (escape) {\n document.addEventListener('keydown', onKeyDown);\n }\n\n return () => {\n events.forEach(eventName => {\n document.removeEventListener(eventName, onPointerEvent);\n });\n\n if (escape) {\n document.removeEventListener('keydown', onKeyDown);\n }\n };\n // `events` is covered by `eventsKey` below instead of the array\n // itself, which (like `refs`) is usually a fresh literal every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [enabled, escape, eventsKey]);\n};\n\nexport default useClickOutside;\n"],"mappings":";;;AAgBA,MAAM,mBACJ,MACA,SACA,UAAmB,EAAE,KAClB;CAKH,MAAM,EAAE,UAAU,MAAM,SAAS,CAAC,cAAc,EAAE,SAAS,UAAU;CAErE,MAAM,aAAa,OAAO,QAAQ;AAElC,iBAAgB;AACd,aAAW,UAAU;GACrB;CAEF,MAAM,UAAU,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC,KAAK;CAInD,MAAM,aAAa,OAAO,QAAQ;AAElC,iBAAgB;AACd,aAAW,UAAU;GACrB;AAIF,iBAAgB;AACd,MAAI,CAAC,WAAW,OAAO,aAAa,YAClC;EAGF,MAAM,YAAY,WAChB,WAAW,QAAQ,MAAK,QAAO,KAAK,SAAS,SAAS,OAAO,CAAC;EAEhE,MAAM,kBAAkB,UAAiB;GACvC,MAAM,SAAS,MAAM;AAErB,OAAI,CAAC,UAAU,SAAS,OAAO,CAC7B;AAGF,cAAW,QAAQ,MAA2B;;EAGhD,MAAM,aAAa,UAAyB;AAC1C,OAAI,MAAM,QAAQ,SAChB,YAAW,QAAQ,MAAM;;AAI7B,SAAO,SAAQ,cAAa;AAC1B,YAAS,iBAAiB,WAAW,eAAe;IACpD;AAEF,MAAI,OACF,UAAS,iBAAiB,WAAW,UAAU;AAGjD,eAAa;AACX,UAAO,SAAQ,cAAa;AAC1B,aAAS,oBAAoB,WAAW,eAAe;KACvD;AAEF,OAAI,OACF,UAAS,oBAAoB,WAAW,UAAU;;IAMrD;EAAC;EAAS;EA9CK,OAAO,KAAK,IAAI;EA8CH,CAAC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/hooks/use-debounced-callback.d.ts
|
|
2
|
+
interface Options {
|
|
3
|
+
delay?: number;
|
|
4
|
+
autoInvoke?: boolean;
|
|
5
|
+
leading?: boolean;
|
|
6
|
+
}
|
|
7
|
+
declare const useDebouncedCallback: (callback: () => unknown, {
|
|
8
|
+
delay,
|
|
9
|
+
autoInvoke,
|
|
10
|
+
leading
|
|
11
|
+
}: Options, deps?: React.DependencyList) => () => void;
|
|
12
|
+
//#endregion
|
|
13
|
+
export { useDebouncedCallback };
|
|
14
|
+
//# sourceMappingURL=use-debounced-callback.d.mts.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useEffect, useRef } from "react";
|
|
2
2
|
|
|
3
|
-
//#region src/hooks/use-
|
|
4
|
-
const
|
|
3
|
+
//#region src/hooks/use-debounced-callback.ts
|
|
4
|
+
const useDebouncedCallback = (callback, { delay = 100, autoInvoke = true, leading = true }, deps = []) => {
|
|
5
5
|
const timeoutRef = useRef(null);
|
|
6
6
|
const callbackRef = useRef(callback);
|
|
7
7
|
const delayRef = useRef(delay);
|
|
@@ -33,5 +33,5 @@ const useDebounce = (callback, { delay = 100, autoInvoke = true, leading = true
|
|
|
33
33
|
};
|
|
34
34
|
|
|
35
35
|
//#endregion
|
|
36
|
-
export {
|
|
37
|
-
//# sourceMappingURL=use-
|
|
36
|
+
export { useDebouncedCallback as default };
|
|
37
|
+
//# sourceMappingURL=use-debounced-callback.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-debounced-callback.mjs","names":[],"sources":["../../src/hooks/use-debounced-callback.ts"],"sourcesContent":["import { useEffect, useRef } from 'react';\n\ninterface Options {\n delay?: number;\n autoInvoke?: boolean;\n leading?: boolean;\n}\n\n// Auto-invokes `callback` (debounced by `delay`ms) whenever `deps` change,\n// and also returns a stable debounced version of `callback` for manual use.\n// `callback` intentionally takes no arguments — the deps-triggered\n// auto-invoke has no natural argument to supply, so an arg-taking callback\n// here was a latent type hole (it was always invoked with zero args\n// regardless of what the callback's own signature claimed).\nconst useDebouncedCallback = (\n callback: () => unknown,\n { delay = 100, autoInvoke = true, leading = true }: Options,\n deps: React.DependencyList = [],\n) => {\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const callbackRef = useRef(callback);\n // Read the latest `delay` when the timeout actually fires, instead of\n // baking in whatever `delay` was on the render that created the stable\n // debounced function (which otherwise never updates again).\n const delayRef = useRef(delay);\n const prevDeps = useRef<React.DependencyList | undefined>(undefined);\n\n useEffect(() => {\n callbackRef.current = callback;\n delayRef.current = delay;\n });\n\n const stableDebouncedCallback = useRef<(() => void) | null>(null);\n\n if (!stableDebouncedCallback.current) {\n stableDebouncedCallback.current = () => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n\n timeoutRef.current = setTimeout(() => {\n callbackRef.current();\n }, delayRef.current);\n };\n }\n\n useEffect(() => {\n const depsChanged =\n prevDeps.current === undefined ||\n prevDeps.current.length !== deps.length ||\n prevDeps.current.some((dep, i) => dep !== deps[i]);\n\n if (depsChanged && timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n\n if (autoInvoke && depsChanged) {\n const isFirstRender = prevDeps.current === undefined;\n\n // `leading` makes the \"first invocation fires immediately, without\n // waiting `delay`ms\" behavior explicit and opt-out-able, instead of\n // an unconditional special case baked into the first render.\n if (isFirstRender && leading) {\n callbackRef.current();\n } else {\n stableDebouncedCallback.current?.();\n }\n }\n\n prevDeps.current = deps;\n });\n\n useEffect(() => {\n return () => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n };\n }, []);\n\n return stableDebouncedCallback.current;\n};\n\nexport default useDebouncedCallback;\n"],"mappings":";;;AAcA,MAAM,wBACJ,UACA,EAAE,QAAQ,KAAK,aAAa,MAAM,UAAU,QAC5C,OAA6B,EAAE,KAC5B;CACH,MAAM,aAAa,OAA6C,KAAK;CACrE,MAAM,cAAc,OAAO,SAAS;CAIpC,MAAM,WAAW,OAAO,MAAM;CAC9B,MAAM,WAAW,OAAyC,OAAU;AAEpE,iBAAgB;AACd,cAAY,UAAU;AACtB,WAAS,UAAU;GACnB;CAEF,MAAM,0BAA0B,OAA4B,KAAK;AAEjE,KAAI,CAAC,wBAAwB,QAC3B,yBAAwB,gBAAgB;AACtC,MAAI,WAAW,QACb,cAAa,WAAW,QAAQ;AAGlC,aAAW,UAAU,iBAAiB;AACpC,eAAY,SAAS;KACpB,SAAS,QAAQ;;AAIxB,iBAAgB;EACd,MAAM,cACJ,SAAS,YAAY,UACrB,SAAS,QAAQ,WAAW,KAAK,UACjC,SAAS,QAAQ,MAAM,KAAK,MAAM,QAAQ,KAAK,GAAG;AAEpD,MAAI,eAAe,WAAW,QAC5B,cAAa,WAAW,QAAQ;AAGlC,MAAI,cAAc,YAMhB,KALsB,SAAS,YAAY,UAKtB,QACnB,aAAY,SAAS;MAErB,yBAAwB,WAAW;AAIvC,WAAS,UAAU;GACnB;AAEF,iBAAgB;AACd,eAAa;AACX,OAAI,WAAW,QACb,cAAa,WAAW,QAAQ;;IAGnC,EAAE,CAAC;AAEN,QAAO,wBAAwB"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from "react";
|
|
2
|
+
|
|
3
|
+
//#region src/hooks/use-debounced-value.ts
|
|
4
|
+
const useDebouncedValue = (value, delay = 100) => {
|
|
5
|
+
const [debouncedValue, setDebouncedValue] = useState(value);
|
|
6
|
+
const timeoutRef = useRef(null);
|
|
7
|
+
useEffect(() => {
|
|
8
|
+
timeoutRef.current = setTimeout(() => {
|
|
9
|
+
setDebouncedValue(value);
|
|
10
|
+
}, delay);
|
|
11
|
+
return () => {
|
|
12
|
+
if (timeoutRef.current) clearTimeout(timeoutRef.current);
|
|
13
|
+
};
|
|
14
|
+
}, [value, delay]);
|
|
15
|
+
return debouncedValue;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
//#endregion
|
|
19
|
+
export { useDebouncedValue as default };
|
|
20
|
+
//# sourceMappingURL=use-debounced-value.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-debounced-value.mjs","names":[],"sources":["../../src/hooks/use-debounced-value.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\n\n// The value-shaped counterpart to useDebounce (which is callback-shaped),\n// symmetric with useThrottle's `(value, delay) => value` signature. The\n// common \"just give me the debounced value\" case otherwise needs two\n// pieces of state and an effect built on useDebounce by hand.\nconst useDebouncedValue = <T>(value: T, delay = 100): T => {\n const [debouncedValue, setDebouncedValue] = useState(value);\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n timeoutRef.current = setTimeout(() => {\n setDebouncedValue(value);\n }, delay);\n\n return () => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n };\n }, [value, delay]);\n\n return debouncedValue;\n};\n\nexport default useDebouncedValue;\n"],"mappings":";;;AAMA,MAAM,qBAAwB,OAAU,QAAQ,QAAW;CACzD,MAAM,CAAC,gBAAgB,qBAAqB,SAAS,MAAM;CAC3D,MAAM,aAAa,OAA6C,KAAK;AAErE,iBAAgB;AACd,aAAW,UAAU,iBAAiB;AACpC,qBAAkB,MAAM;KACvB,MAAM;AAET,eAAa;AACX,OAAI,WAAW,QACb,cAAa,WAAW,QAAQ;;IAGnC,CAAC,OAAO,MAAM,CAAC;AAElB,QAAO"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { RefObject } from "react";
|
|
2
|
+
|
|
3
|
+
//#region src/hooks/use-event-listener.d.ts
|
|
4
|
+
interface Options {
|
|
5
|
+
capture?: boolean;
|
|
6
|
+
passive?: boolean;
|
|
7
|
+
once?: boolean;
|
|
8
|
+
enabled?: boolean;
|
|
9
|
+
}
|
|
10
|
+
declare function useEventListener<K extends keyof WindowEventMap>(type: K, handler: (event: WindowEventMap[K]) => void, options?: Options & {
|
|
11
|
+
target?: Window | null;
|
|
12
|
+
}): void;
|
|
13
|
+
declare function useEventListener<K extends keyof DocumentEventMap>(type: K, handler: (event: DocumentEventMap[K]) => void, options: Options & {
|
|
14
|
+
target: Document | RefObject<Document | null>;
|
|
15
|
+
}): void;
|
|
16
|
+
declare function useEventListener<T extends HTMLElement, K extends keyof HTMLElementEventMap>(type: K, handler: (event: HTMLElementEventMap[K]) => void, options: Options & {
|
|
17
|
+
target: RefObject<T | null>;
|
|
18
|
+
}): void;
|
|
19
|
+
//#endregion
|
|
20
|
+
export { useEventListener };
|
|
21
|
+
//# sourceMappingURL=use-event-listener.d.mts.map
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { useEffect, useRef } from "react";
|
|
2
|
+
|
|
3
|
+
//#region src/hooks/use-event-listener.ts
|
|
4
|
+
function useEventListener(type, handler, options = {}) {
|
|
5
|
+
const { target, capture, passive, once, enabled = true } = options;
|
|
6
|
+
const handlerRef = useRef(handler);
|
|
7
|
+
useEffect(() => {
|
|
8
|
+
handlerRef.current = handler;
|
|
9
|
+
});
|
|
10
|
+
useEffect(() => {
|
|
11
|
+
if (!enabled) return;
|
|
12
|
+
let cancelled = false;
|
|
13
|
+
let rafId;
|
|
14
|
+
let resolvedTarget = null;
|
|
15
|
+
const listener = (event) => {
|
|
16
|
+
handlerRef.current(event);
|
|
17
|
+
};
|
|
18
|
+
const attach = () => {
|
|
19
|
+
if (cancelled) return;
|
|
20
|
+
if (target && "current" in target && !target.current) {
|
|
21
|
+
rafId = requestAnimationFrame(attach);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
resolvedTarget = target && "current" in target ? target.current : target ?? (typeof window === "undefined" ? null : window);
|
|
25
|
+
if (!resolvedTarget) return;
|
|
26
|
+
resolvedTarget.addEventListener(type, listener, {
|
|
27
|
+
capture,
|
|
28
|
+
passive,
|
|
29
|
+
once
|
|
30
|
+
});
|
|
31
|
+
};
|
|
32
|
+
attach();
|
|
33
|
+
return () => {
|
|
34
|
+
cancelled = true;
|
|
35
|
+
if (rafId !== void 0) cancelAnimationFrame(rafId);
|
|
36
|
+
resolvedTarget?.removeEventListener(type, listener, { capture });
|
|
37
|
+
};
|
|
38
|
+
}, [
|
|
39
|
+
type,
|
|
40
|
+
target,
|
|
41
|
+
capture,
|
|
42
|
+
passive,
|
|
43
|
+
once,
|
|
44
|
+
enabled
|
|
45
|
+
]);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
//#endregion
|
|
49
|
+
export { useEventListener as default };
|
|
50
|
+
//# sourceMappingURL=use-event-listener.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-event-listener.mjs","names":[],"sources":["../../src/hooks/use-event-listener.ts"],"sourcesContent":["import { type RefObject, useEffect, useRef } from 'react';\n\ninterface Options {\n capture?: boolean;\n passive?: boolean;\n once?: boolean;\n enabled?: boolean;\n}\n\ntype EventListenerTarget = EventTarget | RefObject<EventTarget | null> | null;\n\nfunction useEventListener<K extends keyof WindowEventMap>(\n type: K,\n handler: (event: WindowEventMap[K]) => void,\n options?: Options & { target?: Window | null },\n): void;\nfunction useEventListener<K extends keyof DocumentEventMap>(\n type: K,\n handler: (event: DocumentEventMap[K]) => void,\n options: Options & { target: Document | RefObject<Document | null> },\n): void;\nfunction useEventListener<\n T extends HTMLElement,\n K extends keyof HTMLElementEventMap,\n>(\n type: K,\n handler: (event: HTMLElementEventMap[K]) => void,\n options: Options & { target: RefObject<T | null> },\n): void;\n\n// Resolves `target` (default `window`, or a raw EventTarget, or a\n// RefObject pointing at one) and (de)registers `type` on it — the pair of\n// addEventListener/removeEventListener calls duplicated across ui-kit\n// (marquee item) and live-editor (error handlers). `handler` is read\n// through a ref so a fresh function every render doesn't tear down and\n// re-add the listener.\nfunction useEventListener(\n type: string,\n handler: (event: Event) => void,\n options: Options & { target?: EventListenerTarget } = {},\n) {\n const { target, capture, passive, once, enabled = true } = options;\n\n const handlerRef = useRef(handler);\n\n useEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n if (!enabled) {\n return;\n }\n\n let cancelled = false;\n let rafId: number | undefined;\n let resolvedTarget: EventTarget | null = null;\n\n const listener = (event: Event) => {\n handlerRef.current(event);\n };\n\n const attach = () => {\n if (cancelled) {\n return;\n }\n\n // A RefObject target can still be null right after mount (conditional\n // render, portal, lazy mount) — retry every frame until it's\n // populated instead of giving up on the first effect run. A raw\n // target or the default window has nothing to wait for.\n if (target && 'current' in target && !target.current) {\n rafId = requestAnimationFrame(attach);\n return;\n }\n\n resolvedTarget =\n target && 'current' in target\n ? target.current\n : (target ?? (typeof window === 'undefined' ? null : window));\n\n if (!resolvedTarget) {\n return;\n }\n\n resolvedTarget.addEventListener(type, listener, {\n capture,\n passive,\n once,\n });\n };\n\n attach();\n\n return () => {\n cancelled = true;\n if (rafId !== undefined) {\n cancelAnimationFrame(rafId);\n }\n resolvedTarget?.removeEventListener(type, listener, { capture });\n };\n }, [type, target, capture, passive, once, enabled]);\n}\n\nexport default useEventListener;\n"],"mappings":";;;AAoCA,SAAS,iBACP,MACA,SACA,UAAsD,EAAE,EACxD;CACA,MAAM,EAAE,QAAQ,SAAS,SAAS,MAAM,UAAU,SAAS;CAE3D,MAAM,aAAa,OAAO,QAAQ;AAElC,iBAAgB;AACd,aAAW,UAAU;GACrB;AAEF,iBAAgB;AACd,MAAI,CAAC,QACH;EAGF,IAAI,YAAY;EAChB,IAAI;EACJ,IAAI,iBAAqC;EAEzC,MAAM,YAAY,UAAiB;AACjC,cAAW,QAAQ,MAAM;;EAG3B,MAAM,eAAe;AACnB,OAAI,UACF;AAOF,OAAI,UAAU,aAAa,UAAU,CAAC,OAAO,SAAS;AACpD,YAAQ,sBAAsB,OAAO;AACrC;;AAGF,oBACE,UAAU,aAAa,SACnB,OAAO,UACN,WAAW,OAAO,WAAW,cAAc,OAAO;AAEzD,OAAI,CAAC,eACH;AAGF,kBAAe,iBAAiB,MAAM,UAAU;IAC9C;IACA;IACA;IACD,CAAC;;AAGJ,UAAQ;AAER,eAAa;AACX,eAAY;AACZ,OAAI,UAAU,OACZ,sBAAqB,MAAM;AAE7B,mBAAgB,oBAAoB,MAAM,UAAU,EAAE,SAAS,CAAC;;IAEjE;EAAC;EAAM;EAAQ;EAAS;EAAS;EAAM;EAAQ,CAAC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/hooks/use-file-drop.d.ts
|
|
2
|
+
interface Options {
|
|
3
|
+
onDrop?: (files: File[]) => void;
|
|
4
|
+
accept?: string;
|
|
5
|
+
multiple?: boolean;
|
|
6
|
+
disabled?: boolean;
|
|
7
|
+
}
|
|
8
|
+
declare const useFileDrop: <T extends HTMLElement = HTMLElement>(options?: Options) => {
|
|
9
|
+
dropRef: (node: T | null) => void;
|
|
10
|
+
isDragging: boolean;
|
|
11
|
+
};
|
|
12
|
+
//#endregion
|
|
13
|
+
export { useFileDrop };
|
|
14
|
+
//# sourceMappingURL=use-file-drop.d.mts.map
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
2
|
+
|
|
3
|
+
//#region src/hooks/use-file-drop.ts
|
|
4
|
+
const matchesAccept = (file, accept) => {
|
|
5
|
+
if (!accept) return true;
|
|
6
|
+
const patterns = accept.split(",").map((pattern) => pattern.trim()).filter(Boolean);
|
|
7
|
+
if (patterns.length === 0) return true;
|
|
8
|
+
return patterns.some((pattern) => {
|
|
9
|
+
if (pattern.startsWith(".")) return file.name.toLowerCase().endsWith(pattern.toLowerCase());
|
|
10
|
+
if (pattern.endsWith("/*")) return file.type.startsWith(pattern.slice(0, -1));
|
|
11
|
+
return file.type === pattern;
|
|
12
|
+
});
|
|
13
|
+
};
|
|
14
|
+
const useFileDrop = (options = {}) => {
|
|
15
|
+
const { onDrop, accept, multiple = true, disabled = false } = options;
|
|
16
|
+
const [isDragging, setIsDragging] = useState(false);
|
|
17
|
+
const dragCounterRef = useRef(0);
|
|
18
|
+
const onDropRef = useRef(onDrop);
|
|
19
|
+
const acceptRef = useRef(accept);
|
|
20
|
+
const multipleRef = useRef(multiple);
|
|
21
|
+
const disabledRef = useRef(disabled);
|
|
22
|
+
useEffect(() => {
|
|
23
|
+
onDropRef.current = onDrop;
|
|
24
|
+
acceptRef.current = accept;
|
|
25
|
+
multipleRef.current = multiple;
|
|
26
|
+
disabledRef.current = disabled;
|
|
27
|
+
});
|
|
28
|
+
useEffect(() => {
|
|
29
|
+
if (disabled) {
|
|
30
|
+
dragCounterRef.current = 0;
|
|
31
|
+
setIsDragging(false);
|
|
32
|
+
}
|
|
33
|
+
}, [disabled]);
|
|
34
|
+
const cleanupRef = useRef(null);
|
|
35
|
+
return {
|
|
36
|
+
dropRef: useCallback((node) => {
|
|
37
|
+
cleanupRef.current?.();
|
|
38
|
+
cleanupRef.current = null;
|
|
39
|
+
if (!node) return;
|
|
40
|
+
const onDragEnter = (event) => {
|
|
41
|
+
if (disabledRef.current) return;
|
|
42
|
+
event.preventDefault();
|
|
43
|
+
dragCounterRef.current += 1;
|
|
44
|
+
if (dragCounterRef.current === 1) setIsDragging(true);
|
|
45
|
+
};
|
|
46
|
+
const onDragLeave = (event) => {
|
|
47
|
+
if (disabledRef.current) return;
|
|
48
|
+
event.preventDefault();
|
|
49
|
+
dragCounterRef.current = Math.max(0, dragCounterRef.current - 1);
|
|
50
|
+
if (dragCounterRef.current === 0) setIsDragging(false);
|
|
51
|
+
};
|
|
52
|
+
const onDragOver = (event) => {
|
|
53
|
+
if (disabledRef.current) return;
|
|
54
|
+
event.preventDefault();
|
|
55
|
+
};
|
|
56
|
+
const onDrop = (event) => {
|
|
57
|
+
if (disabledRef.current) return;
|
|
58
|
+
event.preventDefault();
|
|
59
|
+
dragCounterRef.current = 0;
|
|
60
|
+
setIsDragging(false);
|
|
61
|
+
const fileList = event.dataTransfer?.files;
|
|
62
|
+
if (!fileList || fileList.length === 0) return;
|
|
63
|
+
let files = Array.from(fileList).filter((file) => matchesAccept(file, acceptRef.current));
|
|
64
|
+
if (!multipleRef.current) files = files.slice(0, 1);
|
|
65
|
+
if (files.length > 0) onDropRef.current?.(files);
|
|
66
|
+
};
|
|
67
|
+
node.addEventListener("dragenter", onDragEnter);
|
|
68
|
+
node.addEventListener("dragleave", onDragLeave);
|
|
69
|
+
node.addEventListener("dragover", onDragOver);
|
|
70
|
+
node.addEventListener("drop", onDrop);
|
|
71
|
+
cleanupRef.current = () => {
|
|
72
|
+
node.removeEventListener("dragenter", onDragEnter);
|
|
73
|
+
node.removeEventListener("dragleave", onDragLeave);
|
|
74
|
+
node.removeEventListener("dragover", onDragOver);
|
|
75
|
+
node.removeEventListener("drop", onDrop);
|
|
76
|
+
dragCounterRef.current = 0;
|
|
77
|
+
};
|
|
78
|
+
}, []),
|
|
79
|
+
isDragging
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
//#endregion
|
|
84
|
+
export { useFileDrop as default };
|
|
85
|
+
//# sourceMappingURL=use-file-drop.mjs.map
|