@foundrykit/hooks 2.0.6 → 2.0.8
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/CHANGELOG.md +12 -0
- package/README.md +24 -434
- package/dist/index.d.ts +150 -148
- package/dist/index.js +92 -89
- package/dist/index.js.map +1 -1
- package/package.json +13 -9
- package/src/hooks/use-advanced-search.ts +1 -1
- package/src/hooks/use-click-outside.ts +10 -3
- package/src/hooks/use-debounced-value.ts +1 -1
- package/src/hooks/use-form-field.ts +2 -2
- package/src/hooks/use-local-storage.ts +10 -10
- package/src/hooks/use-media-query.ts +12 -8
- package/src/index.ts +14 -13
- package/tsup.config.ts +3 -0
- package/.turbo/turbo-build.log +0 -17
- package/.turbo/turbo-type-check.log +0 -4
- package/eslint.config.js +0 -4
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,133 @@
|
|
|
1
|
+
import { SearchResult } from '@foundrykit/types';
|
|
2
|
+
export { SearchResult, SearchSection } from '@foundrykit/types';
|
|
1
3
|
import * as React from 'react';
|
|
2
4
|
import { RefObject } from 'react';
|
|
3
5
|
import * as react_hook_form from 'react-hook-form';
|
|
4
6
|
import { FieldValues, FieldPath } from 'react-hook-form';
|
|
5
|
-
|
|
6
|
-
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Defines the behavior when search results are empty or query is too short.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```tsx
|
|
13
|
+
* // Show "No results found" message
|
|
14
|
+
* emptyStateBehaviour="show-empty-message"
|
|
15
|
+
*
|
|
16
|
+
* // Hide results until minimum characters typed
|
|
17
|
+
* emptyStateBehaviour="hide-until-min-chars"
|
|
18
|
+
*
|
|
19
|
+
* // Show all results initially
|
|
20
|
+
* emptyStateBehaviour="show-all-results"
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
type EmptyStateBehavior = 'show-empty-message' | 'hide-until-min-chars' | 'show-all-results';
|
|
24
|
+
/** @deprecated Use EmptyStateBehavior instead. */
|
|
25
|
+
type EmptyStateBehaviour = EmptyStateBehavior;
|
|
26
|
+
/**
|
|
27
|
+
* Context properties for the advanced search functionality.
|
|
28
|
+
* Provides all necessary state and handlers for search components.
|
|
29
|
+
*/
|
|
30
|
+
type SearchContextProps = {
|
|
31
|
+
/** Current search query string */
|
|
32
|
+
query: string;
|
|
33
|
+
/** Function to update the search query */
|
|
34
|
+
setQuery: (query: string) => void;
|
|
35
|
+
/** Whether the search results dropdown is open */
|
|
36
|
+
isOpen: boolean;
|
|
37
|
+
/** Function to control the dropdown open state */
|
|
38
|
+
setIsOpen: (open: boolean) => void;
|
|
39
|
+
/** Stable id for the input element */
|
|
40
|
+
inputId: string;
|
|
41
|
+
/** Stable id for the results container */
|
|
42
|
+
resultsId: string;
|
|
43
|
+
/** Currently highlighted result index for keyboard navigation */
|
|
44
|
+
activeIndex: number;
|
|
45
|
+
/** Function to update the highlighted result index */
|
|
46
|
+
setActiveIndex: (index: number) => void;
|
|
47
|
+
/** Array of current search results */
|
|
48
|
+
results: SearchResult[];
|
|
49
|
+
/** Function to update the search results */
|
|
50
|
+
setResults: (results: SearchResult[]) => void;
|
|
51
|
+
/** Whether a search request is currently in progress */
|
|
52
|
+
isLoading: boolean;
|
|
53
|
+
/** Function to control the loading state */
|
|
54
|
+
setIsLoading: (loading: boolean) => void;
|
|
55
|
+
/** Function to trigger a search with the given query */
|
|
56
|
+
onSearch: (query: string) => void;
|
|
57
|
+
/** Function called when a search result is selected */
|
|
58
|
+
onResultSelect: (result: SearchResult) => void;
|
|
59
|
+
/** Behavior configuration for empty states */
|
|
60
|
+
emptyStateBehaviour: EmptyStateBehavior;
|
|
61
|
+
/** Minimum number of characters required before triggering search */
|
|
62
|
+
minQueryLength: number;
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* React context for sharing search state between components.
|
|
66
|
+
* Created with null as default to ensure proper error handling.
|
|
67
|
+
*/
|
|
68
|
+
declare const SearchContext: React.Context<SearchContextProps | null>;
|
|
69
|
+
/**
|
|
70
|
+
* Hook to access the advanced search context.
|
|
71
|
+
* Must be used within an AdvancedSearchProvider component.
|
|
72
|
+
*
|
|
73
|
+
* @returns SearchContextProps - The search context containing state and handlers
|
|
74
|
+
* @throws Error if used outside of AdvancedSearchProvider
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* ```tsx
|
|
78
|
+
* function SearchComponent() {
|
|
79
|
+
* const { query, setQuery, results, onSearch } = useAdvancedSearch();
|
|
80
|
+
*
|
|
81
|
+
* return (
|
|
82
|
+
* <div>
|
|
83
|
+
* <input
|
|
84
|
+
* value={query}
|
|
85
|
+
* onChange={(e) => setQuery(e.target.value)}
|
|
86
|
+
* />
|
|
87
|
+
* {results.map(result => (
|
|
88
|
+
* <div key={result.id}>{result.title}</div>
|
|
89
|
+
* ))}
|
|
90
|
+
* </div>
|
|
91
|
+
* );
|
|
92
|
+
* }
|
|
93
|
+
* ```
|
|
94
|
+
*/
|
|
95
|
+
declare function useAdvancedSearch(): SearchContextProps;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Hook that detects clicks outside of a specified element.
|
|
99
|
+
* Useful for closing dropdowns, modals, or other overlay components.
|
|
100
|
+
*
|
|
101
|
+
* @template T - The HTML element type (defaults to HTMLElement)
|
|
102
|
+
* @param ref - React ref object pointing to the element to monitor
|
|
103
|
+
* @param handler - Function called when a click outside is detected
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* ```tsx
|
|
107
|
+
* function Dropdown() {
|
|
108
|
+
* const [isOpen, setIsOpen] = useState(false);
|
|
109
|
+
* const dropdownRef = useRef<HTMLDivElement>(null);
|
|
110
|
+
*
|
|
111
|
+
* useClickOutside(dropdownRef, () => {
|
|
112
|
+
* setIsOpen(false);
|
|
113
|
+
* });
|
|
114
|
+
*
|
|
115
|
+
* return (
|
|
116
|
+
* <div ref={dropdownRef}>
|
|
117
|
+
* {isOpen && <div>Dropdown content</div>}
|
|
118
|
+
* </div>
|
|
119
|
+
* );
|
|
120
|
+
* }
|
|
121
|
+
* ```
|
|
122
|
+
*
|
|
123
|
+
* @example
|
|
124
|
+
* ```tsx
|
|
125
|
+
* // With custom element type
|
|
126
|
+
* const modalRef = useRef<HTMLDialogElement>(null);
|
|
127
|
+
* useClickOutside(modalRef, () => closeModal());
|
|
128
|
+
* ```
|
|
129
|
+
*/
|
|
130
|
+
declare function useClickOutside<T extends HTMLElement = HTMLElement>(ref: RefObject<T>, handler: (event: MouseEvent | TouchEvent) => void): void;
|
|
7
131
|
|
|
8
132
|
/**
|
|
9
133
|
* Hook that returns a debounced version of the provided value.
|
|
@@ -51,9 +175,32 @@ export { SearchResult, SearchSection } from '@foundrykit/types';
|
|
|
51
175
|
*/
|
|
52
176
|
declare function useDebouncedValue<T>(value: T, delay: number): T;
|
|
53
177
|
|
|
178
|
+
type FormFieldContextValue<TFieldValues extends FieldValues = FieldValues, TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>> = {
|
|
179
|
+
name: TName;
|
|
180
|
+
};
|
|
181
|
+
declare const FormFieldContext: React.Context<FormFieldContextValue<FieldValues, string>>;
|
|
182
|
+
type FormItemContextValue = {
|
|
183
|
+
id: string;
|
|
184
|
+
};
|
|
185
|
+
declare const FormItemContext: React.Context<FormItemContextValue>;
|
|
186
|
+
declare function useFormField(): {
|
|
187
|
+
readonly invalid: boolean;
|
|
188
|
+
readonly isDirty: boolean;
|
|
189
|
+
readonly isTouched: boolean;
|
|
190
|
+
readonly isValidating: boolean;
|
|
191
|
+
readonly error?: react_hook_form.FieldError;
|
|
192
|
+
readonly id: string;
|
|
193
|
+
readonly name: string;
|
|
194
|
+
readonly formItemId: `${string}-form-item`;
|
|
195
|
+
readonly formDescriptionId: `${string}-form-item-description`;
|
|
196
|
+
readonly formMessageId: `${string}-form-item-message`;
|
|
197
|
+
};
|
|
198
|
+
|
|
54
199
|
/**
|
|
55
200
|
* Hook that provides localStorage functionality with React state synchronization.
|
|
56
|
-
* Automatically handles serialization/deserialization and SSR safety
|
|
201
|
+
* Automatically handles serialization/deserialization and SSR safety: the server
|
|
202
|
+
* and the first client render both use `initialValue`, and the stored value is
|
|
203
|
+
* read after mount, so hydration never mismatches.
|
|
57
204
|
*
|
|
58
205
|
* @template T - The type of the value to store
|
|
59
206
|
* @param key - The localStorage key
|
|
@@ -134,41 +281,6 @@ declare function useLocalStorage<T>(key: string, initialValue: T): readonly [T,
|
|
|
134
281
|
*/
|
|
135
282
|
declare function useMediaQuery(query: string): boolean;
|
|
136
283
|
|
|
137
|
-
/**
|
|
138
|
-
* Hook that detects clicks outside of a specified element.
|
|
139
|
-
* Useful for closing dropdowns, modals, or other overlay components.
|
|
140
|
-
*
|
|
141
|
-
* @template T - The HTML element type (defaults to HTMLElement)
|
|
142
|
-
* @param ref - React ref object pointing to the element to monitor
|
|
143
|
-
* @param handler - Function called when a click outside is detected
|
|
144
|
-
*
|
|
145
|
-
* @example
|
|
146
|
-
* ```tsx
|
|
147
|
-
* function Dropdown() {
|
|
148
|
-
* const [isOpen, setIsOpen] = useState(false);
|
|
149
|
-
* const dropdownRef = useRef<HTMLDivElement>(null);
|
|
150
|
-
*
|
|
151
|
-
* useClickOutside(dropdownRef, () => {
|
|
152
|
-
* setIsOpen(false);
|
|
153
|
-
* });
|
|
154
|
-
*
|
|
155
|
-
* return (
|
|
156
|
-
* <div ref={dropdownRef}>
|
|
157
|
-
* {isOpen && <div>Dropdown content</div>}
|
|
158
|
-
* </div>
|
|
159
|
-
* );
|
|
160
|
-
* }
|
|
161
|
-
* ```
|
|
162
|
-
*
|
|
163
|
-
* @example
|
|
164
|
-
* ```tsx
|
|
165
|
-
* // With custom element type
|
|
166
|
-
* const modalRef = useRef<HTMLDialogElement>(null);
|
|
167
|
-
* useClickOutside(modalRef, () => closeModal());
|
|
168
|
-
* ```
|
|
169
|
-
*/
|
|
170
|
-
declare function useClickOutside<T extends HTMLElement = HTMLElement>(ref: RefObject<T>, handler: (event: MouseEvent | TouchEvent) => void): void;
|
|
171
|
-
|
|
172
284
|
/**
|
|
173
285
|
* Hook that detects if the current viewport is mobile-sized.
|
|
174
286
|
* Uses a breakpoint of 768px to determine mobile vs desktop.
|
|
@@ -210,116 +322,6 @@ declare function useClickOutside<T extends HTMLElement = HTMLElement>(ref: RefOb
|
|
|
210
322
|
*/
|
|
211
323
|
declare function useIsMobile(): boolean;
|
|
212
324
|
|
|
213
|
-
type FormFieldContextValue<TFieldValues extends FieldValues = FieldValues, TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>> = {
|
|
214
|
-
name: TName;
|
|
215
|
-
};
|
|
216
|
-
declare const FormFieldContext: React.Context<FormFieldContextValue<FieldValues, string>>;
|
|
217
|
-
type FormItemContextValue = {
|
|
218
|
-
id: string;
|
|
219
|
-
};
|
|
220
|
-
declare const FormItemContext: React.Context<FormItemContextValue>;
|
|
221
|
-
declare function useFormField(): {
|
|
222
|
-
readonly invalid: boolean;
|
|
223
|
-
readonly isDirty: boolean;
|
|
224
|
-
readonly isTouched: boolean;
|
|
225
|
-
readonly isValidating: boolean;
|
|
226
|
-
readonly error?: react_hook_form.FieldError;
|
|
227
|
-
readonly id: string;
|
|
228
|
-
readonly name: string;
|
|
229
|
-
readonly formItemId: `${string}-form-item`;
|
|
230
|
-
readonly formDescriptionId: `${string}-form-item-description`;
|
|
231
|
-
readonly formMessageId: `${string}-form-item-message`;
|
|
232
|
-
};
|
|
233
|
-
|
|
234
|
-
/**
|
|
235
|
-
* Defines the behavior when search results are empty or query is too short.
|
|
236
|
-
*
|
|
237
|
-
* @example
|
|
238
|
-
* ```tsx
|
|
239
|
-
* // Show "No results found" message
|
|
240
|
-
* emptyStateBehaviour="show-empty-message"
|
|
241
|
-
*
|
|
242
|
-
* // Hide results until minimum characters typed
|
|
243
|
-
* emptyStateBehaviour="hide-until-min-chars"
|
|
244
|
-
*
|
|
245
|
-
* // Show all results initially
|
|
246
|
-
* emptyStateBehaviour="show-all-results"
|
|
247
|
-
* ```
|
|
248
|
-
*/
|
|
249
|
-
type EmptyStateBehavior = 'show-empty-message' | 'hide-until-min-chars' | 'show-all-results';
|
|
250
|
-
/** @deprecated Use EmptyStateBehavior instead. */
|
|
251
|
-
type EmptyStateBehaviour = EmptyStateBehavior;
|
|
252
|
-
/**
|
|
253
|
-
* Context properties for the advanced search functionality.
|
|
254
|
-
* Provides all necessary state and handlers for search components.
|
|
255
|
-
*/
|
|
256
|
-
type SearchContextProps = {
|
|
257
|
-
/** Current search query string */
|
|
258
|
-
query: string;
|
|
259
|
-
/** Function to update the search query */
|
|
260
|
-
setQuery: (query: string) => void;
|
|
261
|
-
/** Whether the search results dropdown is open */
|
|
262
|
-
isOpen: boolean;
|
|
263
|
-
/** Function to control the dropdown open state */
|
|
264
|
-
setIsOpen: (open: boolean) => void;
|
|
265
|
-
/** Stable id for the input element */
|
|
266
|
-
inputId: string;
|
|
267
|
-
/** Stable id for the results container */
|
|
268
|
-
resultsId: string;
|
|
269
|
-
/** Currently highlighted result index for keyboard navigation */
|
|
270
|
-
activeIndex: number;
|
|
271
|
-
/** Function to update the highlighted result index */
|
|
272
|
-
setActiveIndex: (index: number) => void;
|
|
273
|
-
/** Array of current search results */
|
|
274
|
-
results: SearchResult[];
|
|
275
|
-
/** Function to update the search results */
|
|
276
|
-
setResults: (results: SearchResult[]) => void;
|
|
277
|
-
/** Whether a search request is currently in progress */
|
|
278
|
-
isLoading: boolean;
|
|
279
|
-
/** Function to control the loading state */
|
|
280
|
-
setIsLoading: (loading: boolean) => void;
|
|
281
|
-
/** Function to trigger a search with the given query */
|
|
282
|
-
onSearch: (query: string) => void;
|
|
283
|
-
/** Function called when a search result is selected */
|
|
284
|
-
onResultSelect: (result: SearchResult) => void;
|
|
285
|
-
/** Behavior configuration for empty states */
|
|
286
|
-
emptyStateBehaviour: EmptyStateBehavior;
|
|
287
|
-
/** Minimum number of characters required before triggering search */
|
|
288
|
-
minQueryLength: number;
|
|
289
|
-
};
|
|
290
|
-
/**
|
|
291
|
-
* React context for sharing search state between components.
|
|
292
|
-
* Created with null as default to ensure proper error handling.
|
|
293
|
-
*/
|
|
294
|
-
declare const SearchContext: React.Context<SearchContextProps | null>;
|
|
295
|
-
/**
|
|
296
|
-
* Hook to access the advanced search context.
|
|
297
|
-
* Must be used within an AdvancedSearchProvider component.
|
|
298
|
-
*
|
|
299
|
-
* @returns SearchContextProps - The search context containing state and handlers
|
|
300
|
-
* @throws Error if used outside of AdvancedSearchProvider
|
|
301
|
-
*
|
|
302
|
-
* @example
|
|
303
|
-
* ```tsx
|
|
304
|
-
* function SearchComponent() {
|
|
305
|
-
* const { query, setQuery, results, onSearch } = useAdvancedSearch();
|
|
306
|
-
*
|
|
307
|
-
* return (
|
|
308
|
-
* <div>
|
|
309
|
-
* <input
|
|
310
|
-
* value={query}
|
|
311
|
-
* onChange={(e) => setQuery(e.target.value)}
|
|
312
|
-
* />
|
|
313
|
-
* {results.map(result => (
|
|
314
|
-
* <div key={result.id}>{result.title}</div>
|
|
315
|
-
* ))}
|
|
316
|
-
* </div>
|
|
317
|
-
* );
|
|
318
|
-
* }
|
|
319
|
-
* ```
|
|
320
|
-
*/
|
|
321
|
-
declare function useAdvancedSearch(): SearchContextProps;
|
|
322
|
-
|
|
323
325
|
declare function noop(): void;
|
|
324
326
|
|
|
325
327
|
export { type EmptyStateBehavior, type EmptyStateBehaviour, FormFieldContext, type FormFieldContextValue, FormItemContext, type FormItemContextValue, SearchContext, noop, useAdvancedSearch, useClickOutside, useDebouncedValue, useFormField, useIsMobile, useLocalStorage, useMediaQuery };
|
package/dist/index.js
CHANGED
|
@@ -1,73 +1,34 @@
|
|
|
1
|
-
|
|
2
|
-
import { useState, useEffect } from "react";
|
|
3
|
-
function useDebouncedValue(value, delay) {
|
|
4
|
-
const [debouncedValue, setDebouncedValue] = useState(value);
|
|
5
|
-
useEffect(() => {
|
|
6
|
-
const handler = setTimeout(() => {
|
|
7
|
-
setDebouncedValue(value);
|
|
8
|
-
}, delay);
|
|
9
|
-
return () => {
|
|
10
|
-
clearTimeout(handler);
|
|
11
|
-
};
|
|
12
|
-
}, [value, delay]);
|
|
13
|
-
return debouncedValue;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
// src/hooks/use-local-storage.ts
|
|
17
|
-
import { useState as useState2 } from "react";
|
|
18
|
-
function useLocalStorage(key, initialValue) {
|
|
19
|
-
const [storedValue, setStoredValue] = useState2(() => {
|
|
20
|
-
if (typeof window === "undefined") {
|
|
21
|
-
return initialValue;
|
|
22
|
-
}
|
|
23
|
-
try {
|
|
24
|
-
const item = window.localStorage.getItem(key);
|
|
25
|
-
return item ? JSON.parse(item) : initialValue;
|
|
26
|
-
} catch (error) {
|
|
27
|
-
console.log(error);
|
|
28
|
-
return initialValue;
|
|
29
|
-
}
|
|
30
|
-
});
|
|
31
|
-
const setValue = (value) => {
|
|
32
|
-
try {
|
|
33
|
-
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
|
34
|
-
setStoredValue(valueToStore);
|
|
35
|
-
if (typeof window !== "undefined") {
|
|
36
|
-
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
|
37
|
-
}
|
|
38
|
-
} catch (error) {
|
|
39
|
-
console.log(error);
|
|
40
|
-
}
|
|
41
|
-
};
|
|
42
|
-
return [storedValue, setValue];
|
|
43
|
-
}
|
|
1
|
+
'use client';
|
|
44
2
|
|
|
45
|
-
// src/hooks/use-
|
|
46
|
-
import
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
return matches;
|
|
3
|
+
// src/hooks/use-advanced-search.ts
|
|
4
|
+
import * as React from "react";
|
|
5
|
+
var SearchContext = React.createContext(
|
|
6
|
+
null
|
|
7
|
+
);
|
|
8
|
+
function useAdvancedSearch() {
|
|
9
|
+
const context = React.useContext(SearchContext);
|
|
10
|
+
if (!context) {
|
|
11
|
+
throw new Error(
|
|
12
|
+
"useAdvancedSearch must be used within an AdvancedSearchProvider."
|
|
13
|
+
);
|
|
14
|
+
}
|
|
15
|
+
return context;
|
|
59
16
|
}
|
|
60
17
|
|
|
61
18
|
// src/hooks/use-click-outside.ts
|
|
62
|
-
import { useEffect
|
|
19
|
+
import { useEffect, useRef } from "react";
|
|
63
20
|
function useClickOutside(ref, handler) {
|
|
64
|
-
|
|
21
|
+
const handlerRef = useRef(handler);
|
|
22
|
+
useEffect(() => {
|
|
23
|
+
handlerRef.current = handler;
|
|
24
|
+
}, [handler]);
|
|
25
|
+
useEffect(() => {
|
|
65
26
|
const listener = (event) => {
|
|
66
27
|
const el = ref?.current;
|
|
67
28
|
if (!el || el.contains(event?.target || null)) {
|
|
68
29
|
return;
|
|
69
30
|
}
|
|
70
|
-
|
|
31
|
+
handlerRef.current(event);
|
|
71
32
|
};
|
|
72
33
|
document.addEventListener("mousedown", listener);
|
|
73
34
|
document.addEventListener("touchstart", listener);
|
|
@@ -75,26 +36,22 @@ function useClickOutside(ref, handler) {
|
|
|
75
36
|
document.removeEventListener("mousedown", listener);
|
|
76
37
|
document.removeEventListener("touchstart", listener);
|
|
77
38
|
};
|
|
78
|
-
}, [ref
|
|
39
|
+
}, [ref]);
|
|
79
40
|
}
|
|
80
41
|
|
|
81
|
-
// src/hooks/use-
|
|
82
|
-
import
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
|
42
|
+
// src/hooks/use-debounced-value.ts
|
|
43
|
+
import { useEffect as useEffect2, useState } from "react";
|
|
44
|
+
function useDebouncedValue(value, delay) {
|
|
45
|
+
const [debouncedValue, setDebouncedValue] = useState(value);
|
|
46
|
+
useEffect2(() => {
|
|
47
|
+
const handler = setTimeout(() => {
|
|
48
|
+
setDebouncedValue(value);
|
|
49
|
+
}, delay);
|
|
50
|
+
return () => {
|
|
51
|
+
clearTimeout(handler);
|
|
92
52
|
};
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
return () => mql.removeEventListener("change", onChange);
|
|
96
|
-
}, []);
|
|
97
|
-
return !!isMobile;
|
|
53
|
+
}, [value, delay]);
|
|
54
|
+
return debouncedValue;
|
|
98
55
|
}
|
|
99
56
|
|
|
100
57
|
// src/hooks/use-form-field.ts
|
|
@@ -129,19 +86,65 @@ function useFormField() {
|
|
|
129
86
|
};
|
|
130
87
|
}
|
|
131
88
|
|
|
132
|
-
// src/hooks/use-
|
|
89
|
+
// src/hooks/use-local-storage.ts
|
|
90
|
+
import { useEffect as useEffect3, useState as useState2 } from "react";
|
|
91
|
+
function useLocalStorage(key, initialValue) {
|
|
92
|
+
const [storedValue, setStoredValue] = useState2(initialValue);
|
|
93
|
+
useEffect3(() => {
|
|
94
|
+
try {
|
|
95
|
+
const item = window.localStorage.getItem(key);
|
|
96
|
+
if (item !== null) setStoredValue(JSON.parse(item));
|
|
97
|
+
} catch (error) {
|
|
98
|
+
console.log(error);
|
|
99
|
+
}
|
|
100
|
+
}, [key]);
|
|
101
|
+
const setValue = (value) => {
|
|
102
|
+
try {
|
|
103
|
+
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
|
104
|
+
setStoredValue(valueToStore);
|
|
105
|
+
if (typeof window !== "undefined") {
|
|
106
|
+
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
|
107
|
+
}
|
|
108
|
+
} catch (error) {
|
|
109
|
+
console.log(error);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
return [storedValue, setValue];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// src/hooks/use-media-query.ts
|
|
116
|
+
import { useEffect as useEffect4, useState as useState3 } from "react";
|
|
117
|
+
function useMediaQuery(query) {
|
|
118
|
+
const [matches, setMatches] = useState3(
|
|
119
|
+
() => typeof window !== "undefined" ? window.matchMedia(query).matches : false
|
|
120
|
+
);
|
|
121
|
+
useEffect4(() => {
|
|
122
|
+
const media = window.matchMedia(query);
|
|
123
|
+
const listener = () => setMatches(media.matches);
|
|
124
|
+
listener();
|
|
125
|
+
media.addEventListener("change", listener);
|
|
126
|
+
return () => media.removeEventListener("change", listener);
|
|
127
|
+
}, [query]);
|
|
128
|
+
return matches;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// src/hooks/use-mobile.ts
|
|
133
132
|
import * as React3 from "react";
|
|
134
|
-
var
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
133
|
+
var MOBILE_BREAKPOINT = 768;
|
|
134
|
+
function useIsMobile() {
|
|
135
|
+
const [isMobile, setIsMobile] = React3.useState(
|
|
136
|
+
void 0
|
|
137
|
+
);
|
|
138
|
+
React3.useEffect(() => {
|
|
139
|
+
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
|
140
|
+
const onChange = () => {
|
|
141
|
+
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
|
142
|
+
};
|
|
143
|
+
mql.addEventListener("change", onChange);
|
|
144
|
+
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
|
145
|
+
return () => mql.removeEventListener("change", onChange);
|
|
146
|
+
}, []);
|
|
147
|
+
return !!isMobile;
|
|
145
148
|
}
|
|
146
149
|
|
|
147
150
|
// src/lib/utils.ts
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-debounced-value.ts","../src/hooks/use-local-storage.ts","../src/hooks/use-media-query.ts","../src/hooks/use-click-outside.ts","../src/hooks/use-mobile.ts","../src/hooks/use-form-field.ts","../src/hooks/use-advanced-search.ts","../src/lib/utils.ts"],"sourcesContent":["import { useState, useEffect } from 'react';\n\n/**\n * Hook that returns a debounced version of the provided value.\n * The returned value will only update after the specified delay has passed\n * since the last time the input value changed.\n *\n * @template T - The type of the value to debounce\n * @param value - The value to debounce\n * @param delay - The delay in milliseconds\n * @returns The debounced value\n *\n * @example\n * ```tsx\n * function SearchInput() {\n * const [query, setQuery] = useState('');\n * const debouncedQuery = useDebouncedValue(query, 300);\n *\n * useEffect(() => {\n * if (debouncedQuery) {\n * // Perform search with debounced query\n * searchAPI(debouncedQuery);\n * }\n * }, [debouncedQuery]);\n *\n * return (\n * <input\n * value={query}\n * onChange={(e) => setQuery(e.target.value)}\n * />\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Debouncing form validation\n * const debouncedEmail = useDebouncedValue(email, 500);\n *\n * useEffect(() => {\n * if (debouncedEmail) {\n * validateEmail(debouncedEmail);\n * }\n * }, [debouncedEmail]);\n * ```\n */\nexport function useDebouncedValue<T>(value: T, delay: number): T {\n const [debouncedValue, setDebouncedValue] = useState<T>(value);\n\n useEffect(() => {\n const handler = setTimeout(() => {\n setDebouncedValue(value);\n }, delay);\n\n return () => {\n clearTimeout(handler);\n };\n }, [value, delay]);\n\n return debouncedValue;\n}\n","import { useState } from 'react';\n\n/**\n * Hook that provides localStorage functionality with React state synchronization.\n * Automatically handles serialization/deserialization and SSR safety.\n *\n * @template T - The type of the value to store\n * @param key - The localStorage key\n * @param initialValue - The initial value if no stored value exists\n * @returns A tuple containing the stored value and a setter function\n *\n * @example\n * ```tsx\n * function UserPreferences() {\n * const [theme, setTheme] = useLocalStorage('theme', 'light');\n * const [language, setLanguage] = useLocalStorage('language', 'en');\n *\n * return (\n * <div>\n * <select value={theme} onChange={(e) => setTheme(e.target.value)}>\n * <option value=\"light\">Light</option>\n * <option value=\"dark\">Dark</option>\n * </select>\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // With complex objects\n * interface UserSettings {\n * notifications: boolean;\n * fontSize: number;\n * }\n *\n * const [settings, setSettings] = useLocalStorage<UserSettings>('user-settings', {\n * notifications: true,\n * fontSize: 14\n * });\n *\n * // Update with function (like useState)\n * setSettings(prev => ({ ...prev, fontSize: 16 }));\n * ```\n */\nexport function useLocalStorage<T>(key: string, initialValue: T) {\n // Get from local storage then parse stored json or return initialValue\n const [storedValue, setStoredValue] = useState<T>(() => {\n if (typeof window === 'undefined') {\n return initialValue;\n }\n try {\n const item = window.localStorage.getItem(key);\n return item ? JSON.parse(item) : initialValue;\n } catch (error) {\n console.log(error);\n return initialValue;\n }\n });\n\n // Return a wrapped version of useState's setter function that persists the new value to localStorage\n const setValue = (value: T | ((val: T) => T)) => {\n try {\n // Allow value to be a function so we have the same API as useState\n const valueToStore =\n value instanceof Function ? value(storedValue) : value;\n setStoredValue(valueToStore);\n if (typeof window !== 'undefined') {\n window.localStorage.setItem(key, JSON.stringify(valueToStore));\n }\n } catch (error) {\n console.log(error);\n }\n };\n\n return [storedValue, setValue] as const;\n}\n","import { useState, useEffect } from 'react';\n\n/**\n * Hook that tracks whether a CSS media query matches the current viewport.\n * Automatically updates when the viewport size changes.\n *\n * @param query - The CSS media query string to match\n * @returns Boolean indicating whether the media query currently matches\n *\n * @example\n * ```tsx\n * function ResponsiveComponent() {\n * const isMobile = useMediaQuery('(max-width: 768px)');\n * const isTablet = useMediaQuery('(min-width: 769px) and (max-width: 1024px)');\n * const isDesktop = useMediaQuery('(min-width: 1025px)');\n *\n * return (\n * <div>\n * {isMobile && <MobileLayout />}\n * {isTablet && <TabletLayout />}\n * {isDesktop && <DesktopLayout />}\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Dark mode detection\n * const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');\n *\n * // High contrast mode\n * const prefersHighContrast = useMediaQuery('(prefers-contrast: high)');\n *\n * // Reduced motion\n * const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');\n * ```\n */\nexport function useMediaQuery(query: string): boolean {\n const [matches, setMatches] = useState(false);\n\n useEffect(() => {\n const media = window.matchMedia(query);\n if (media.matches !== matches) {\n setMatches(media.matches);\n }\n const listener = () => setMatches(media.matches);\n window.addEventListener('resize', listener);\n return () => window.removeEventListener('resize', listener);\n }, [matches, query]);\n\n return matches;\n}\n","import { useEffect, RefObject } from 'react';\n\n/**\n * Hook that detects clicks outside of a specified element.\n * Useful for closing dropdowns, modals, or other overlay components.\n *\n * @template T - The HTML element type (defaults to HTMLElement)\n * @param ref - React ref object pointing to the element to monitor\n * @param handler - Function called when a click outside is detected\n *\n * @example\n * ```tsx\n * function Dropdown() {\n * const [isOpen, setIsOpen] = useState(false);\n * const dropdownRef = useRef<HTMLDivElement>(null);\n *\n * useClickOutside(dropdownRef, () => {\n * setIsOpen(false);\n * });\n *\n * return (\n * <div ref={dropdownRef}>\n * {isOpen && <div>Dropdown content</div>}\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // With custom element type\n * const modalRef = useRef<HTMLDialogElement>(null);\n * useClickOutside(modalRef, () => closeModal());\n * ```\n */\nexport function useClickOutside<T extends HTMLElement = HTMLElement>(\n ref: RefObject<T>,\n handler: (event: MouseEvent | TouchEvent) => void\n) {\n useEffect(() => {\n const listener = (event: MouseEvent | TouchEvent) => {\n const el = ref?.current;\n if (!el || el.contains((event?.target as Node) || null)) {\n return;\n }\n\n handler(event);\n };\n\n document.addEventListener('mousedown', listener);\n document.addEventListener('touchstart', listener);\n\n return () => {\n document.removeEventListener('mousedown', listener);\n document.removeEventListener('touchstart', listener);\n };\n }, [ref, handler]);\n}\n","import * as React from 'react';\n\n/** The breakpoint width in pixels below which a device is considered mobile */\nconst MOBILE_BREAKPOINT = 768;\n\n/**\n * Hook that detects if the current viewport is mobile-sized.\n * Uses a breakpoint of 768px to determine mobile vs desktop.\n *\n * @returns Boolean indicating whether the current viewport is mobile-sized\n *\n * @example\n * ```tsx\n * function ResponsiveHeader() {\n * const isMobile = useIsMobile();\n *\n * return (\n * <header>\n * {isMobile ? (\n * <MobileNavigation />\n * ) : (\n * <DesktopNavigation />\n * )}\n * </header>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Conditional rendering based on mobile state\n * function ProductGrid() {\n * const isMobile = useIsMobile();\n *\n * return (\n * <div className={isMobile ? 'grid-cols-1' : 'grid-cols-3'}>\n * {products.map(product => (\n * <ProductCard key={product.id} product={product} />\n * ))}\n * </div>\n * );\n * }\n * ```\n */\nexport function useIsMobile() {\n const [isMobile, setIsMobile] = React.useState<boolean | undefined>(\n undefined\n );\n\n React.useEffect(() => {\n const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);\n const onChange = () => {\n setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);\n };\n mql.addEventListener('change', onChange);\n setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);\n return () => mql.removeEventListener('change', onChange);\n }, []);\n\n return !!isMobile;\n}\n","import * as React from 'react';\nimport {\n useFormContext,\n useFormState,\n type FieldPath,\n type FieldValues,\n} from 'react-hook-form';\n\nexport type FormFieldContextValue<\n TFieldValues extends FieldValues = FieldValues,\n TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n> = {\n name: TName;\n};\n\nexport const FormFieldContext = React.createContext<FormFieldContextValue>(\n {} as FormFieldContextValue\n);\n\nexport type FormItemContextValue = {\n id: string;\n};\n\nexport const FormItemContext = React.createContext<FormItemContextValue>(\n {} as FormItemContextValue\n);\n\nexport function useFormField() {\n const fieldContext = React.useContext(FormFieldContext);\n const itemContext = React.useContext(FormItemContext);\n const { getFieldState } = useFormContext();\n const formState = useFormState({ name: fieldContext.name });\n const fieldState = getFieldState(fieldContext.name, formState);\n\n if (!fieldContext) {\n throw new Error('useFormField should be used within <FormField>');\n }\n\n const { id } = itemContext;\n\n return {\n id,\n name: fieldContext.name,\n formItemId: `${id}-form-item`,\n formDescriptionId: `${id}-form-item-description`,\n formMessageId: `${id}-form-item-message`,\n ...fieldState,\n } as const;\n}\n","import * as React from 'react';\nimport type { SearchResult } from '@foundrykit/types';\n\n/**\n * Defines the behavior when search results are empty or query is too short.\n *\n * @example\n * ```tsx\n * // Show \"No results found\" message\n * emptyStateBehaviour=\"show-empty-message\"\n *\n * // Hide results until minimum characters typed\n * emptyStateBehaviour=\"hide-until-min-chars\"\n *\n * // Show all results initially\n * emptyStateBehaviour=\"show-all-results\"\n * ```\n */\nexport type EmptyStateBehavior =\n | 'show-empty-message' // Show \"No results found\" message\n | 'hide-until-min-chars' // Don't show popover until min characters\n | 'show-all-results'; // Show all results initially or after min chars\n\n/** @deprecated Use EmptyStateBehavior instead. */\nexport type EmptyStateBehaviour = EmptyStateBehavior;\n\n/**\n * Context properties for the advanced search functionality.\n * Provides all necessary state and handlers for search components.\n */\ntype SearchContextProps = {\n /** Current search query string */\n query: string;\n /** Function to update the search query */\n setQuery: (query: string) => void;\n /** Whether the search results dropdown is open */\n isOpen: boolean;\n /** Function to control the dropdown open state */\n setIsOpen: (open: boolean) => void;\n /** Stable id for the input element */\n inputId: string;\n /** Stable id for the results container */\n resultsId: string;\n /** Currently highlighted result index for keyboard navigation */\n activeIndex: number;\n /** Function to update the highlighted result index */\n setActiveIndex: (index: number) => void;\n /** Array of current search results */\n results: SearchResult[];\n /** Function to update the search results */\n setResults: (results: SearchResult[]) => void;\n /** Whether a search request is currently in progress */\n isLoading: boolean;\n /** Function to control the loading state */\n setIsLoading: (loading: boolean) => void;\n /** Function to trigger a search with the given query */\n onSearch: (query: string) => void;\n /** Function called when a search result is selected */\n onResultSelect: (result: SearchResult) => void;\n /** Behavior configuration for empty states */\n emptyStateBehaviour: EmptyStateBehavior;\n /** Minimum number of characters required before triggering search */\n minQueryLength: number;\n};\n\n/**\n * React context for sharing search state between components.\n * Created with null as default to ensure proper error handling.\n */\nexport const SearchContext = React.createContext<SearchContextProps | null>(\n null\n);\n\n/**\n * Hook to access the advanced search context.\n * Must be used within an AdvancedSearchProvider component.\n *\n * @returns SearchContextProps - The search context containing state and handlers\n * @throws Error if used outside of AdvancedSearchProvider\n *\n * @example\n * ```tsx\n * function SearchComponent() {\n * const { query, setQuery, results, onSearch } = useAdvancedSearch();\n *\n * return (\n * <div>\n * <input\n * value={query}\n * onChange={(e) => setQuery(e.target.value)}\n * />\n * {results.map(result => (\n * <div key={result.id}>{result.title}</div>\n * ))}\n * </div>\n * );\n * }\n * ```\n */\nexport function useAdvancedSearch() {\n const context = React.useContext(SearchContext);\n if (!context) {\n throw new Error(\n 'useAdvancedSearch must be used within an AdvancedSearchProvider.'\n );\n }\n return context;\n}\n","// Utility functions for hooks package\nexport function noop() {\n // No operation function\n}\n"],"mappings":";AAAA,SAAS,UAAU,iBAAiB;AA8C7B,SAAS,kBAAqB,OAAU,OAAkB;AAC/D,QAAM,CAAC,gBAAgB,iBAAiB,IAAI,SAAY,KAAK;AAE7D,YAAU,MAAM;AACd,UAAM,UAAU,WAAW,MAAM;AAC/B,wBAAkB,KAAK;AAAA,IACzB,GAAG,KAAK;AAER,WAAO,MAAM;AACX,mBAAa,OAAO;AAAA,IACtB;AAAA,EACF,GAAG,CAAC,OAAO,KAAK,CAAC;AAEjB,SAAO;AACT;;;AC5DA,SAAS,YAAAA,iBAAgB;AA6ClB,SAAS,gBAAmB,KAAa,cAAiB;AAE/D,QAAM,CAAC,aAAa,cAAc,IAAIA,UAAY,MAAM;AACtD,QAAI,OAAO,WAAW,aAAa;AACjC,aAAO;AAAA,IACT;AACA,QAAI;AACF,YAAM,OAAO,OAAO,aAAa,QAAQ,GAAG;AAC5C,aAAO,OAAO,KAAK,MAAM,IAAI,IAAI;AAAA,IACnC,SAAS,OAAO;AACd,cAAQ,IAAI,KAAK;AACjB,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AAGD,QAAM,WAAW,CAAC,UAA+B;AAC/C,QAAI;AAEF,YAAM,eACJ,iBAAiB,WAAW,MAAM,WAAW,IAAI;AACnD,qBAAe,YAAY;AAC3B,UAAI,OAAO,WAAW,aAAa;AACjC,eAAO,aAAa,QAAQ,KAAK,KAAK,UAAU,YAAY,CAAC;AAAA,MAC/D;AAAA,IACF,SAAS,OAAO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,aAAa,iBAAiB;AAAA,IACnD;AACA,QAAI,iBAAiB,UAAU,QAAQ;AACvC,gBAAY,OAAO,aAAa,iBAAiB;AACjD,WAAO,MAAM,IAAI,oBAAoB,UAAU,QAAQ;AAAA,EACzD,GAAG,CAAC,CAAC;AAEL,SAAO,CAAC,CAAC;AACX;;;AC5DA,YAAYC,YAAW;AACvB;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AASA,IAAM,mBAAyB;AAAA,EACpC,CAAC;AACH;AAMO,IAAM,kBAAwB;AAAA,EACnC,CAAC;AACH;AAEO,SAAS,eAAe;AAC7B,QAAM,eAAqB,kBAAW,gBAAgB;AACtD,QAAM,cAAoB,kBAAW,eAAe;AACpD,QAAM,EAAE,cAAc,IAAI,eAAe;AACzC,QAAM,YAAY,aAAa,EAAE,MAAM,aAAa,KAAK,CAAC;AAC1D,QAAM,aAAa,cAAc,aAAa,MAAM,SAAS;AAE7D,MAAI,CAAC,cAAc;AACjB,UAAM,IAAI,MAAM,gDAAgD;AAAA,EAClE;AAEA,QAAM,EAAE,GAAG,IAAI;AAEf,SAAO;AAAA,IACL;AAAA,IACA,MAAM,aAAa;AAAA,IACnB,YAAY,GAAG,EAAE;AAAA,IACjB,mBAAmB,GAAG,EAAE;AAAA,IACxB,eAAe,GAAG,EAAE;AAAA,IACpB,GAAG;AAAA,EACL;AACF;;;AChDA,YAAYC,YAAW;AAqEhB,IAAM,gBAAsB;AAAA,EACjC;AACF;AA4BO,SAAS,oBAAoB;AAClC,QAAM,UAAgB,kBAAW,aAAa;AAC9C,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;;;AC1GO,SAAS,OAAO;AAEvB;","names":["useState","useState","useEffect","useEffect","React","React"]}
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-advanced-search.ts","../src/hooks/use-click-outside.ts","../src/hooks/use-debounced-value.ts","../src/hooks/use-form-field.ts","../src/hooks/use-local-storage.ts","../src/hooks/use-media-query.ts","../src/hooks/use-mobile.ts","../src/lib/utils.ts"],"sourcesContent":["import type { SearchResult } from '@foundrykit/types';\nimport * as React from 'react';\n\n/**\n * Defines the behavior when search results are empty or query is too short.\n *\n * @example\n * ```tsx\n * // Show \"No results found\" message\n * emptyStateBehaviour=\"show-empty-message\"\n *\n * // Hide results until minimum characters typed\n * emptyStateBehaviour=\"hide-until-min-chars\"\n *\n * // Show all results initially\n * emptyStateBehaviour=\"show-all-results\"\n * ```\n */\nexport type EmptyStateBehavior =\n | 'show-empty-message' // Show \"No results found\" message\n | 'hide-until-min-chars' // Don't show popover until min characters\n | 'show-all-results'; // Show all results initially or after min chars\n\n/** @deprecated Use EmptyStateBehavior instead. */\nexport type EmptyStateBehaviour = EmptyStateBehavior;\n\n/**\n * Context properties for the advanced search functionality.\n * Provides all necessary state and handlers for search components.\n */\ntype SearchContextProps = {\n /** Current search query string */\n query: string;\n /** Function to update the search query */\n setQuery: (query: string) => void;\n /** Whether the search results dropdown is open */\n isOpen: boolean;\n /** Function to control the dropdown open state */\n setIsOpen: (open: boolean) => void;\n /** Stable id for the input element */\n inputId: string;\n /** Stable id for the results container */\n resultsId: string;\n /** Currently highlighted result index for keyboard navigation */\n activeIndex: number;\n /** Function to update the highlighted result index */\n setActiveIndex: (index: number) => void;\n /** Array of current search results */\n results: SearchResult[];\n /** Function to update the search results */\n setResults: (results: SearchResult[]) => void;\n /** Whether a search request is currently in progress */\n isLoading: boolean;\n /** Function to control the loading state */\n setIsLoading: (loading: boolean) => void;\n /** Function to trigger a search with the given query */\n onSearch: (query: string) => void;\n /** Function called when a search result is selected */\n onResultSelect: (result: SearchResult) => void;\n /** Behavior configuration for empty states */\n emptyStateBehaviour: EmptyStateBehavior;\n /** Minimum number of characters required before triggering search */\n minQueryLength: number;\n};\n\n/**\n * React context for sharing search state between components.\n * Created with null as default to ensure proper error handling.\n */\nexport const SearchContext = React.createContext<SearchContextProps | null>(\n null\n);\n\n/**\n * Hook to access the advanced search context.\n * Must be used within an AdvancedSearchProvider component.\n *\n * @returns SearchContextProps - The search context containing state and handlers\n * @throws Error if used outside of AdvancedSearchProvider\n *\n * @example\n * ```tsx\n * function SearchComponent() {\n * const { query, setQuery, results, onSearch } = useAdvancedSearch();\n *\n * return (\n * <div>\n * <input\n * value={query}\n * onChange={(e) => setQuery(e.target.value)}\n * />\n * {results.map(result => (\n * <div key={result.id}>{result.title}</div>\n * ))}\n * </div>\n * );\n * }\n * ```\n */\nexport function useAdvancedSearch() {\n const context = React.useContext(SearchContext);\n if (!context) {\n throw new Error(\n 'useAdvancedSearch must be used within an AdvancedSearchProvider.'\n );\n }\n return context;\n}\n","import { type RefObject, useEffect, useRef } from 'react';\n\n/**\n * Hook that detects clicks outside of a specified element.\n * Useful for closing dropdowns, modals, or other overlay components.\n *\n * @template T - The HTML element type (defaults to HTMLElement)\n * @param ref - React ref object pointing to the element to monitor\n * @param handler - Function called when a click outside is detected\n *\n * @example\n * ```tsx\n * function Dropdown() {\n * const [isOpen, setIsOpen] = useState(false);\n * const dropdownRef = useRef<HTMLDivElement>(null);\n *\n * useClickOutside(dropdownRef, () => {\n * setIsOpen(false);\n * });\n *\n * return (\n * <div ref={dropdownRef}>\n * {isOpen && <div>Dropdown content</div>}\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // With custom element type\n * const modalRef = useRef<HTMLDialogElement>(null);\n * useClickOutside(modalRef, () => closeModal());\n * ```\n */\nexport function useClickOutside<T extends HTMLElement = HTMLElement>(\n ref: RefObject<T>,\n handler: (event: MouseEvent | TouchEvent) => void\n) {\n // Keep the latest handler in a ref so an inline handler (the common call\n // site) doesn't re-add/remove the listeners on every render.\n const handlerRef = useRef(handler);\n useEffect(() => {\n handlerRef.current = handler;\n }, [handler]);\n\n useEffect(() => {\n const listener = (event: MouseEvent | TouchEvent) => {\n const el = ref?.current;\n if (!el || el.contains((event?.target as Node) || null)) {\n return;\n }\n\n handlerRef.current(event);\n };\n\n document.addEventListener('mousedown', listener);\n document.addEventListener('touchstart', listener);\n\n return () => {\n document.removeEventListener('mousedown', listener);\n document.removeEventListener('touchstart', listener);\n };\n }, [ref]);\n}\n","import { useEffect, useState } from 'react';\n\n/**\n * Hook that returns a debounced version of the provided value.\n * The returned value will only update after the specified delay has passed\n * since the last time the input value changed.\n *\n * @template T - The type of the value to debounce\n * @param value - The value to debounce\n * @param delay - The delay in milliseconds\n * @returns The debounced value\n *\n * @example\n * ```tsx\n * function SearchInput() {\n * const [query, setQuery] = useState('');\n * const debouncedQuery = useDebouncedValue(query, 300);\n *\n * useEffect(() => {\n * if (debouncedQuery) {\n * // Perform search with debounced query\n * searchAPI(debouncedQuery);\n * }\n * }, [debouncedQuery]);\n *\n * return (\n * <input\n * value={query}\n * onChange={(e) => setQuery(e.target.value)}\n * />\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Debouncing form validation\n * const debouncedEmail = useDebouncedValue(email, 500);\n *\n * useEffect(() => {\n * if (debouncedEmail) {\n * validateEmail(debouncedEmail);\n * }\n * }, [debouncedEmail]);\n * ```\n */\nexport function useDebouncedValue<T>(value: T, delay: number): T {\n const [debouncedValue, setDebouncedValue] = useState<T>(value);\n\n useEffect(() => {\n const handler = setTimeout(() => {\n setDebouncedValue(value);\n }, delay);\n\n return () => {\n clearTimeout(handler);\n };\n }, [value, delay]);\n\n return debouncedValue;\n}\n","import * as React from 'react';\nimport {\n type FieldPath,\n type FieldValues,\n useFormContext,\n useFormState,\n} from 'react-hook-form';\n\nexport type FormFieldContextValue<\n TFieldValues extends FieldValues = FieldValues,\n TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n> = {\n name: TName;\n};\n\nexport const FormFieldContext = React.createContext<FormFieldContextValue>(\n {} as FormFieldContextValue\n);\n\nexport type FormItemContextValue = {\n id: string;\n};\n\nexport const FormItemContext = React.createContext<FormItemContextValue>(\n {} as FormItemContextValue\n);\n\nexport function useFormField() {\n const fieldContext = React.useContext(FormFieldContext);\n const itemContext = React.useContext(FormItemContext);\n const { getFieldState } = useFormContext();\n const formState = useFormState({ name: fieldContext.name });\n const fieldState = getFieldState(fieldContext.name, formState);\n\n if (!fieldContext) {\n throw new Error('useFormField should be used within <FormField>');\n }\n\n const { id } = itemContext;\n\n return {\n id,\n name: fieldContext.name,\n formItemId: `${id}-form-item`,\n formDescriptionId: `${id}-form-item-description`,\n formMessageId: `${id}-form-item-message`,\n ...fieldState,\n } as const;\n}\n","import { useEffect, useState } from 'react';\n\n/**\n * Hook that provides localStorage functionality with React state synchronization.\n * Automatically handles serialization/deserialization and SSR safety: the server\n * and the first client render both use `initialValue`, and the stored value is\n * read after mount, so hydration never mismatches.\n *\n * @template T - The type of the value to store\n * @param key - The localStorage key\n * @param initialValue - The initial value if no stored value exists\n * @returns A tuple containing the stored value and a setter function\n *\n * @example\n * ```tsx\n * function UserPreferences() {\n * const [theme, setTheme] = useLocalStorage('theme', 'light');\n * const [language, setLanguage] = useLocalStorage('language', 'en');\n *\n * return (\n * <div>\n * <select value={theme} onChange={(e) => setTheme(e.target.value)}>\n * <option value=\"light\">Light</option>\n * <option value=\"dark\">Dark</option>\n * </select>\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // With complex objects\n * interface UserSettings {\n * notifications: boolean;\n * fontSize: number;\n * }\n *\n * const [settings, setSettings] = useLocalStorage<UserSettings>('user-settings', {\n * notifications: true,\n * fontSize: 14\n * });\n *\n * // Update with function (like useState)\n * setSettings(prev => ({ ...prev, fontSize: 16 }));\n * ```\n */\nexport function useLocalStorage<T>(key: string, initialValue: T) {\n const [storedValue, setStoredValue] = useState<T>(initialValue);\n\n // Read the stored value after mount so the first client render matches the server.\n useEffect(() => {\n try {\n const item = window.localStorage.getItem(key);\n if (item !== null) setStoredValue(JSON.parse(item));\n } catch (error) {\n console.log(error);\n }\n }, [key]);\n\n // Return a wrapped version of useState's setter function that persists the new value to localStorage\n const setValue = (value: T | ((val: T) => T)) => {\n try {\n // Allow value to be a function so we have the same API as useState\n const valueToStore =\n value instanceof Function ? value(storedValue) : value;\n setStoredValue(valueToStore);\n if (typeof window !== 'undefined') {\n window.localStorage.setItem(key, JSON.stringify(valueToStore));\n }\n } catch (error) {\n console.log(error);\n }\n };\n\n return [storedValue, setValue] as const;\n}\n","import { useEffect, useState } from 'react';\n\n/**\n * Hook that tracks whether a CSS media query matches the current viewport.\n * Automatically updates when the viewport size changes.\n *\n * @param query - The CSS media query string to match\n * @returns Boolean indicating whether the media query currently matches\n *\n * @example\n * ```tsx\n * function ResponsiveComponent() {\n * const isMobile = useMediaQuery('(max-width: 768px)');\n * const isTablet = useMediaQuery('(min-width: 769px) and (max-width: 1024px)');\n * const isDesktop = useMediaQuery('(min-width: 1025px)');\n *\n * return (\n * <div>\n * {isMobile && <MobileLayout />}\n * {isTablet && <TabletLayout />}\n * {isDesktop && <DesktopLayout />}\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Dark mode detection\n * const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');\n *\n * // High contrast mode\n * const prefersHighContrast = useMediaQuery('(prefers-contrast: high)');\n *\n * // Reduced motion\n * const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');\n * ```\n */\nexport function useMediaQuery(query: string): boolean {\n // SSR-safe initial value; hydrated to the real match in the effect.\n const [matches, setMatches] = useState(() =>\n typeof window !== 'undefined' ? window.matchMedia(query).matches : false\n );\n\n useEffect(() => {\n const media = window.matchMedia(query);\n const listener = () => setMatches(media.matches);\n // Subscribe to the MediaQueryList's own `change` event so non-viewport\n // queries (prefers-color-scheme, prefers-reduced-motion, orientation, …)\n // update too — a `resize` listener never fires for those.\n listener();\n media.addEventListener('change', listener);\n return () => media.removeEventListener('change', listener);\n }, [query]);\n\n return matches;\n}\n","import * as React from 'react';\n\n/** The breakpoint width in pixels below which a device is considered mobile */\nconst MOBILE_BREAKPOINT = 768;\n\n/**\n * Hook that detects if the current viewport is mobile-sized.\n * Uses a breakpoint of 768px to determine mobile vs desktop.\n *\n * @returns Boolean indicating whether the current viewport is mobile-sized\n *\n * @example\n * ```tsx\n * function ResponsiveHeader() {\n * const isMobile = useIsMobile();\n *\n * return (\n * <header>\n * {isMobile ? (\n * <MobileNavigation />\n * ) : (\n * <DesktopNavigation />\n * )}\n * </header>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Conditional rendering based on mobile state\n * function ProductGrid() {\n * const isMobile = useIsMobile();\n *\n * return (\n * <div className={isMobile ? 'grid-cols-1' : 'grid-cols-3'}>\n * {products.map(product => (\n * <ProductCard key={product.id} product={product} />\n * ))}\n * </div>\n * );\n * }\n * ```\n */\nexport function useIsMobile() {\n const [isMobile, setIsMobile] = React.useState<boolean | undefined>(\n undefined\n );\n\n React.useEffect(() => {\n const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);\n const onChange = () => {\n setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);\n };\n mql.addEventListener('change', onChange);\n setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);\n return () => mql.removeEventListener('change', onChange);\n }, []);\n\n return !!isMobile;\n}\n","// Utility functions for hooks package\nexport function noop() {\n // No operation function\n}\n"],"mappings":";;;AACA,YAAY,WAAW;AAoEhB,IAAM,gBAAsB;AAAA,EACjC;AACF;AA4BO,SAAS,oBAAoB;AAClC,QAAM,UAAgB,iBAAW,aAAa;AAC9C,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;;;AC3GA,SAAyB,WAAW,cAAc;AAmC3C,SAAS,gBACd,KACA,SACA;AAGA,QAAM,aAAa,OAAO,OAAO;AACjC,YAAU,MAAM;AACd,eAAW,UAAU;AAAA,EACvB,GAAG,CAAC,OAAO,CAAC;AAEZ,YAAU,MAAM;AACd,UAAM,WAAW,CAAC,UAAmC;AACnD,YAAM,KAAK,KAAK;AAChB,UAAI,CAAC,MAAM,GAAG,SAAU,OAAO,UAA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