@foundrykit/hooks 2.0.5 → 2.0.7
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/.turbo/turbo-build.log +17 -18
- package/.turbo/turbo-type-check.log +1 -1
- package/CHANGELOG.md +13 -0
- package/README.md +24 -434
- package/dist/index.d.ts +147 -147
- package/dist/index.js +85 -81
- package/dist/index.js.map +1 -1
- package/package.json +8 -6
- 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-media-query.ts +12 -8
- package/src/index.ts +14 -13
- package/eslint.config.js +0 -4
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,18 +1,17 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
>
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
[34mCLI[39m
|
|
7
|
-
[34mCLI[39m
|
|
8
|
-
[34mCLI[39m tsup
|
|
9
|
-
[34mCLI[39m
|
|
10
|
-
[34mCLI[39m
|
|
11
|
-
[
|
|
12
|
-
[
|
|
13
|
-
[32mESM[39m [1mdist/index.js
|
|
14
|
-
[32mESM[39m
|
|
15
|
-
[
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
DTS dist/index.d.ts 9.67 KB
|
|
1
|
+
|
|
2
|
+
> @foundrykit/hooks@2.0.7 build /home/runner/work/foundry/foundry/packages/hooks
|
|
3
|
+
> tsup
|
|
4
|
+
|
|
5
|
+
[34mCLI[39m Building entry: src/index.ts
|
|
6
|
+
[34mCLI[39m Using tsconfig: tsconfig.json
|
|
7
|
+
[34mCLI[39m tsup v8.5.0
|
|
8
|
+
[34mCLI[39m Using tsup config: /home/runner/work/foundry/foundry/packages/hooks/tsup.config.ts
|
|
9
|
+
[34mCLI[39m Target: es2022
|
|
10
|
+
[34mCLI[39m Cleaning output folder
|
|
11
|
+
[34mESM[39m Build start
|
|
12
|
+
[32mESM[39m [1mdist/index.js [22m[32m4.49 KB[39m
|
|
13
|
+
[32mESM[39m [1mdist/index.js.map [22m[32m17.15 KB[39m
|
|
14
|
+
[32mESM[39m ⚡️ Build success in 59ms
|
|
15
|
+
[34mDTS[39m Build start
|
|
16
|
+
[32mDTS[39m ⚡️ Build success in 4121ms
|
|
17
|
+
[32mDTS[39m [1mdist/index.d.ts [22m[32m9.79 KB[39m
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# @foundrykit/hooks
|
|
2
2
|
|
|
3
|
+
## 2.0.7
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#43](https://github.com/umi-labs/foundry/pull/43) [`b6fc94d`](https://github.com/umi-labs/foundry/commit/b6fc94d3b0f172aa309388f61bd5306af6405fdf) Thanks [@sneddonisaac](https://github.com/sneddonisaac)! - Package metadata now points at the `umi-labs/foundry` monorepo, and releases publish through npm trusted publishing.
|
|
8
|
+
|
|
9
|
+
## 2.0.6
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- feat(storybook, maps): massive updates to maps packages spliting and
|
|
14
|
+
developing into full suites + storybook for easy of test
|
|
15
|
+
|
|
3
16
|
## 2.0.5
|
|
4
17
|
|
|
5
18
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -1,16 +1,8 @@
|
|
|
1
1
|
# @foundrykit/hooks
|
|
2
2
|
|
|
3
|
-
A collection of custom React hooks for common UI patterns
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
## Features
|
|
8
|
-
|
|
9
|
-
- **Custom hooks** - Reusable logic for common UI patterns
|
|
10
|
-
- **TypeScript support** - Full type safety with comprehensive definitions
|
|
11
|
-
- **Performance optimized** - Efficient implementations with proper cleanup
|
|
12
|
-
- **Accessibility focused** - Hooks that support accessibility best practices
|
|
13
|
-
- **Framework agnostic** - Works with any React setup
|
|
3
|
+
A collection of custom React hooks for common UI patterns used across the
|
|
4
|
+
FoundryKit ecosystem — debouncing, persisted state, media queries, click
|
|
5
|
+
handling, form fields, and advanced search.
|
|
14
6
|
|
|
15
7
|
## Installation
|
|
16
8
|
|
|
@@ -18,448 +10,46 @@ behaviour.
|
|
|
18
10
|
pnpm add @foundrykit/hooks
|
|
19
11
|
```
|
|
20
12
|
|
|
21
|
-
## Available Hooks
|
|
22
|
-
|
|
23
|
-
### State Management
|
|
24
|
-
|
|
25
|
-
- **useLocalStorage** - Persist state in localStorage
|
|
26
|
-
- **useDebouncedValue** - Debounce values for performance
|
|
27
|
-
- **useMediaQuery** - React to media query changes
|
|
28
|
-
- **useClickOutside** - Detect clicks outside elements
|
|
29
|
-
|
|
30
|
-
### Form Hooks
|
|
31
|
-
|
|
32
|
-
- **useForm** - Form state management
|
|
33
|
-
- **useField** - Individual field management
|
|
34
|
-
- **useValidation** - Form validation logic
|
|
35
|
-
|
|
36
|
-
### UI Hooks
|
|
37
|
-
|
|
38
|
-
- **useDialog** - Dialog/modal state management
|
|
39
|
-
- **usePopover** - Popover positioning and state
|
|
40
|
-
- **useTooltip** - Tooltip positioning and visibility
|
|
41
|
-
|
|
42
|
-
### Utility Hooks
|
|
43
|
-
|
|
44
|
-
- **usePrevious** - Access previous value
|
|
45
|
-
- **useInterval** - Set up intervals with cleanup
|
|
46
|
-
- **useTimeout** - Set up timeouts with cleanup
|
|
47
|
-
|
|
48
13
|
## Usage
|
|
49
14
|
|
|
50
|
-
### State Management Hooks
|
|
51
|
-
|
|
52
|
-
#### useLocalStorage
|
|
53
|
-
|
|
54
|
-
Persist state in localStorage with automatic serialization:
|
|
55
|
-
|
|
56
|
-
```tsx
|
|
57
|
-
import { useLocalStorage } from '@foundrykit/hooks';
|
|
58
|
-
|
|
59
|
-
function UserPreferences() {
|
|
60
|
-
const [theme, setTheme] = useLocalStorage('theme', 'light');
|
|
61
|
-
const [language, setLanguage] = useLocalStorage('language', 'en');
|
|
62
|
-
|
|
63
|
-
return (
|
|
64
|
-
<div>
|
|
65
|
-
<select value={theme} onChange={e => setTheme(e.target.value)}>
|
|
66
|
-
<option value='light'>Light</option>
|
|
67
|
-
<option value='dark'>Dark</option>
|
|
68
|
-
</select>
|
|
69
|
-
|
|
70
|
-
<select value={language} onChange={e => setLanguage(e.target.value)}>
|
|
71
|
-
<option value='en'>English</option>
|
|
72
|
-
<option value='es'>Spanish</option>
|
|
73
|
-
</select>
|
|
74
|
-
</div>
|
|
75
|
-
);
|
|
76
|
-
}
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
#### useDebouncedValue
|
|
80
|
-
|
|
81
|
-
Debounce values to improve performance:
|
|
82
|
-
|
|
83
15
|
```tsx
|
|
84
|
-
import { useDebouncedValue } from '@foundrykit/hooks';
|
|
16
|
+
import { useDebouncedValue, useIsMobile } from '@foundrykit/hooks';
|
|
85
17
|
|
|
86
|
-
function
|
|
18
|
+
function Search() {
|
|
87
19
|
const [query, setQuery] = useState('');
|
|
88
20
|
const debouncedQuery = useDebouncedValue(query, 300);
|
|
89
|
-
|
|
90
|
-
// This effect only runs when debouncedQuery changes
|
|
91
|
-
useEffect(() => {
|
|
92
|
-
if (debouncedQuery) {
|
|
93
|
-
searchAPI(debouncedQuery);
|
|
94
|
-
}
|
|
95
|
-
}, [debouncedQuery]);
|
|
21
|
+
const isMobile = useIsMobile();
|
|
96
22
|
|
|
97
23
|
return (
|
|
98
24
|
<input
|
|
99
25
|
value={query}
|
|
100
26
|
onChange={e => setQuery(e.target.value)}
|
|
101
|
-
placeholder='Search...'
|
|
27
|
+
placeholder={isMobile ? 'Search' : 'Search the catalog...'}
|
|
102
28
|
/>
|
|
103
29
|
);
|
|
104
30
|
}
|
|
105
31
|
```
|
|
106
32
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
React to media query changes:
|
|
110
|
-
|
|
111
|
-
```tsx
|
|
112
|
-
import { useMediaQuery } from '@foundrykit/hooks';
|
|
113
|
-
|
|
114
|
-
function ResponsiveComponent() {
|
|
115
|
-
const isMobile = useMediaQuery('(max-width: 768px)');
|
|
116
|
-
const isTablet = useMediaQuery('(min-width: 769px) and (max-width: 1024px)');
|
|
117
|
-
const isDesktop = useMediaQuery('(min-width: 1025px)');
|
|
118
|
-
|
|
119
|
-
return (
|
|
120
|
-
<div>
|
|
121
|
-
{isMobile && <MobileLayout />}
|
|
122
|
-
{isTablet && <TabletLayout />}
|
|
123
|
-
{isDesktop && <DesktopLayout />}
|
|
124
|
-
</div>
|
|
125
|
-
);
|
|
126
|
-
}
|
|
127
|
-
```
|
|
128
|
-
|
|
129
|
-
### UI Interaction Hooks
|
|
130
|
-
|
|
131
|
-
#### useClickOutside
|
|
132
|
-
|
|
133
|
-
Detect clicks outside an element:
|
|
134
|
-
|
|
135
|
-
```tsx
|
|
136
|
-
import { useClickOutside } from '@foundrykit/hooks';
|
|
137
|
-
|
|
138
|
-
function Dropdown({ isOpen, onClose, children }) {
|
|
139
|
-
const ref = useRef(null);
|
|
140
|
-
|
|
141
|
-
useClickOutside(ref, () => {
|
|
142
|
-
if (isOpen) {
|
|
143
|
-
onClose();
|
|
144
|
-
}
|
|
145
|
-
});
|
|
146
|
-
|
|
147
|
-
if (!isOpen) return null;
|
|
148
|
-
|
|
149
|
-
return (
|
|
150
|
-
<div ref={ref} className='dropdown'>
|
|
151
|
-
{children}
|
|
152
|
-
</div>
|
|
153
|
-
);
|
|
154
|
-
}
|
|
155
|
-
```
|
|
156
|
-
|
|
157
|
-
#### useDialog
|
|
158
|
-
|
|
159
|
-
Manage dialog/modal state:
|
|
160
|
-
|
|
161
|
-
```tsx
|
|
162
|
-
import { useDialog } from '@foundrykit/hooks';
|
|
163
|
-
|
|
164
|
-
function ModalExample() {
|
|
165
|
-
const { isOpen, open, close, toggle } = useDialog();
|
|
166
|
-
|
|
167
|
-
return (
|
|
168
|
-
<div>
|
|
169
|
-
<button onClick={open}>Open Modal</button>
|
|
170
|
-
|
|
171
|
-
{isOpen && (
|
|
172
|
-
<div className='modal-overlay' onClick={close}>
|
|
173
|
-
<div className='modal-content' onClick={e => e.stopPropagation()}>
|
|
174
|
-
<h2>Modal Content</h2>
|
|
175
|
-
<button onClick={close}>Close</button>
|
|
176
|
-
</div>
|
|
177
|
-
</div>
|
|
178
|
-
)}
|
|
179
|
-
</div>
|
|
180
|
-
);
|
|
181
|
-
}
|
|
182
|
-
```
|
|
183
|
-
|
|
184
|
-
### Form Hooks
|
|
185
|
-
|
|
186
|
-
#### useForm
|
|
187
|
-
|
|
188
|
-
Complete form state management:
|
|
189
|
-
|
|
190
|
-
```tsx
|
|
191
|
-
import { useForm } from '@foundrykit/hooks';
|
|
192
|
-
|
|
193
|
-
function ContactForm() {
|
|
194
|
-
const {
|
|
195
|
-
values,
|
|
196
|
-
errors,
|
|
197
|
-
touched,
|
|
198
|
-
handleChange,
|
|
199
|
-
handleBlur,
|
|
200
|
-
handleSubmit,
|
|
201
|
-
isSubmitting,
|
|
202
|
-
} = useForm({
|
|
203
|
-
initialValues: {
|
|
204
|
-
name: '',
|
|
205
|
-
email: '',
|
|
206
|
-
message: '',
|
|
207
|
-
},
|
|
208
|
-
validate: values => {
|
|
209
|
-
const errors = {};
|
|
210
|
-
if (!values.name) errors.name = 'Name is required';
|
|
211
|
-
if (!values.email) errors.email = 'Email is required';
|
|
212
|
-
if (!values.message) errors.message = 'Message is required';
|
|
213
|
-
return errors;
|
|
214
|
-
},
|
|
215
|
-
onSubmit: async values => {
|
|
216
|
-
await submitForm(values);
|
|
217
|
-
},
|
|
218
|
-
});
|
|
219
|
-
|
|
220
|
-
return (
|
|
221
|
-
<form onSubmit={handleSubmit}>
|
|
222
|
-
<input
|
|
223
|
-
name='name'
|
|
224
|
-
value={values.name}
|
|
225
|
-
onChange={handleChange}
|
|
226
|
-
onBlur={handleBlur}
|
|
227
|
-
className={touched.name && errors.name ? 'error' : ''}
|
|
228
|
-
/>
|
|
229
|
-
{touched.name && errors.name && <span>{errors.name}</span>}
|
|
230
|
-
|
|
231
|
-
<input
|
|
232
|
-
name='email'
|
|
233
|
-
value={values.email}
|
|
234
|
-
onChange={handleChange}
|
|
235
|
-
onBlur={handleBlur}
|
|
236
|
-
className={touched.email && errors.email ? 'error' : ''}
|
|
237
|
-
/>
|
|
238
|
-
{touched.email && errors.email && <span>{errors.email}</span>}
|
|
239
|
-
|
|
240
|
-
<textarea
|
|
241
|
-
name='message'
|
|
242
|
-
value={values.message}
|
|
243
|
-
onChange={handleChange}
|
|
244
|
-
onBlur={handleBlur}
|
|
245
|
-
className={touched.message && errors.message ? 'error' : ''}
|
|
246
|
-
/>
|
|
247
|
-
{touched.message && errors.message && <span>{errors.message}</span>}
|
|
248
|
-
|
|
249
|
-
<button type='submit' disabled={isSubmitting}>
|
|
250
|
-
{isSubmitting ? 'Sending...' : 'Send Message'}
|
|
251
|
-
</button>
|
|
252
|
-
</form>
|
|
253
|
-
);
|
|
254
|
-
}
|
|
255
|
-
```
|
|
256
|
-
|
|
257
|
-
### Utility Hooks
|
|
258
|
-
|
|
259
|
-
#### usePrevious
|
|
260
|
-
|
|
261
|
-
Access the previous value:
|
|
262
|
-
|
|
263
|
-
```tsx
|
|
264
|
-
import { usePrevious } from '@foundrykit/hooks';
|
|
265
|
-
|
|
266
|
-
function Counter() {
|
|
267
|
-
const [count, setCount] = useState(0);
|
|
268
|
-
const previousCount = usePrevious(count);
|
|
269
|
-
|
|
270
|
-
return (
|
|
271
|
-
<div>
|
|
272
|
-
<p>Current: {count}</p>
|
|
273
|
-
<p>Previous: {previousCount}</p>
|
|
274
|
-
<button onClick={() => setCount(count + 1)}>Increment</button>
|
|
275
|
-
</div>
|
|
276
|
-
);
|
|
277
|
-
}
|
|
278
|
-
```
|
|
279
|
-
|
|
280
|
-
#### useInterval
|
|
281
|
-
|
|
282
|
-
Set up intervals with automatic cleanup:
|
|
283
|
-
|
|
284
|
-
```tsx
|
|
285
|
-
import { useInterval } from '@foundrykit/hooks';
|
|
286
|
-
|
|
287
|
-
function Timer() {
|
|
288
|
-
const [seconds, setSeconds] = useState(0);
|
|
289
|
-
const [isRunning, setIsRunning] = useState(false);
|
|
290
|
-
|
|
291
|
-
useInterval(() => setSeconds(seconds + 1), isRunning ? 1000 : null);
|
|
292
|
-
|
|
293
|
-
return (
|
|
294
|
-
<div>
|
|
295
|
-
<p>Seconds: {seconds}</p>
|
|
296
|
-
<button onClick={() => setIsRunning(!isRunning)}>
|
|
297
|
-
{isRunning ? 'Pause' : 'Start'}
|
|
298
|
-
</button>
|
|
299
|
-
</div>
|
|
300
|
-
);
|
|
301
|
-
}
|
|
302
|
-
```
|
|
303
|
-
|
|
304
|
-
## Advanced Usage
|
|
305
|
-
|
|
306
|
-
### Custom Hook Composition
|
|
307
|
-
|
|
308
|
-
Combine multiple hooks for complex functionality:
|
|
309
|
-
|
|
310
|
-
```tsx
|
|
311
|
-
import {
|
|
312
|
-
useLocalStorage,
|
|
313
|
-
useDebouncedValue,
|
|
314
|
-
useMediaQuery,
|
|
315
|
-
} from '@foundrykit/hooks';
|
|
316
|
-
|
|
317
|
-
function useResponsiveSearch() {
|
|
318
|
-
const [query, setQuery] = useLocalStorage('search-query', '');
|
|
319
|
-
const debouncedQuery = useDebouncedValue(query, 300);
|
|
320
|
-
const isMobile = useMediaQuery('(max-width: 768px)');
|
|
321
|
-
|
|
322
|
-
const searchResults = useMemo(() => {
|
|
323
|
-
if (!debouncedQuery) return [];
|
|
324
|
-
return performSearch(debouncedQuery, { limit: isMobile ? 5 : 10 });
|
|
325
|
-
}, [debouncedQuery, isMobile]);
|
|
326
|
-
|
|
327
|
-
return {
|
|
328
|
-
query,
|
|
329
|
-
setQuery,
|
|
330
|
-
debouncedQuery,
|
|
331
|
-
searchResults,
|
|
332
|
-
isMobile,
|
|
333
|
-
};
|
|
334
|
-
}
|
|
335
|
-
```
|
|
336
|
-
|
|
337
|
-
### Hook with Dependencies
|
|
338
|
-
|
|
339
|
-
```tsx
|
|
340
|
-
import { useClickOutside } from '@foundrykit/hooks';
|
|
341
|
-
|
|
342
|
-
function useDropdown(initialState = false) {
|
|
343
|
-
const [isOpen, setIsOpen] = useState(initialState);
|
|
344
|
-
const ref = useRef(null);
|
|
345
|
-
|
|
346
|
-
useClickOutside(ref, () => setIsOpen(false));
|
|
347
|
-
|
|
348
|
-
const open = useCallback(() => setIsOpen(true), []);
|
|
349
|
-
const close = useCallback(() => setIsOpen(false), []);
|
|
350
|
-
const toggle = useCallback(() => setIsOpen(!isOpen), [isOpen]);
|
|
351
|
-
|
|
352
|
-
return {
|
|
353
|
-
isOpen,
|
|
354
|
-
ref,
|
|
355
|
-
open,
|
|
356
|
-
close,
|
|
357
|
-
toggle,
|
|
358
|
-
};
|
|
359
|
-
}
|
|
360
|
-
```
|
|
361
|
-
|
|
362
|
-
### Performance Optimization
|
|
363
|
-
|
|
364
|
-
```tsx
|
|
365
|
-
import { useDebouncedValue } from '@foundrykit/hooks';
|
|
366
|
-
|
|
367
|
-
function OptimizedSearch() {
|
|
368
|
-
const [query, setQuery] = useState('');
|
|
369
|
-
const debouncedQuery = useDebouncedValue(query, 500);
|
|
370
|
-
|
|
371
|
-
// Memoize expensive operation
|
|
372
|
-
const searchResults = useMemo(() => {
|
|
373
|
-
if (!debouncedQuery) return [];
|
|
374
|
-
return expensiveSearch(debouncedQuery);
|
|
375
|
-
}, [debouncedQuery]);
|
|
376
|
-
|
|
377
|
-
return (
|
|
378
|
-
<div>
|
|
379
|
-
<input
|
|
380
|
-
value={query}
|
|
381
|
-
onChange={e => setQuery(e.target.value)}
|
|
382
|
-
placeholder='Search...'
|
|
383
|
-
/>
|
|
384
|
-
<SearchResults results={searchResults} />
|
|
385
|
-
</div>
|
|
386
|
-
);
|
|
387
|
-
}
|
|
388
|
-
```
|
|
389
|
-
|
|
390
|
-
## TypeScript Support
|
|
391
|
-
|
|
392
|
-
All hooks include comprehensive TypeScript definitions:
|
|
393
|
-
|
|
394
|
-
```tsx
|
|
395
|
-
import { useLocalStorage, useDebouncedValue } from '@foundrykit/hooks';
|
|
396
|
-
|
|
397
|
-
// Type-safe localStorage hook
|
|
398
|
-
const [user, setUser] = useLocalStorage<User>('user', null);
|
|
399
|
-
|
|
400
|
-
// Type-safe debounced value
|
|
401
|
-
const [searchTerm, setSearchTerm] = useState<string>('');
|
|
402
|
-
const debouncedSearchTerm = useDebouncedValue<string>(searchTerm, 300);
|
|
403
|
-
```
|
|
404
|
-
|
|
405
|
-
## Best Practices
|
|
406
|
-
|
|
407
|
-
### Hook Dependencies
|
|
408
|
-
|
|
409
|
-
```tsx
|
|
410
|
-
// ✅ Good - Stable callback
|
|
411
|
-
const handleClick = useCallback(() => {
|
|
412
|
-
console.log('clicked');
|
|
413
|
-
}, []);
|
|
414
|
-
|
|
415
|
-
// ❌ Avoid - Unstable callback
|
|
416
|
-
const handleClick = () => {
|
|
417
|
-
console.log('clicked');
|
|
418
|
-
};
|
|
419
|
-
```
|
|
420
|
-
|
|
421
|
-
### Cleanup
|
|
422
|
-
|
|
423
|
-
```tsx
|
|
424
|
-
// ✅ Good - Proper cleanup
|
|
425
|
-
useEffect(() => {
|
|
426
|
-
const timer = setTimeout(() => {
|
|
427
|
-
// do something
|
|
428
|
-
}, 1000);
|
|
429
|
-
|
|
430
|
-
return () => clearTimeout(timer);
|
|
431
|
-
}, []);
|
|
432
|
-
|
|
433
|
-
// ❌ Avoid - Missing cleanup
|
|
434
|
-
useEffect(() => {
|
|
435
|
-
setTimeout(() => {
|
|
436
|
-
// do something
|
|
437
|
-
}, 1000);
|
|
438
|
-
}, []);
|
|
439
|
-
```
|
|
440
|
-
|
|
441
|
-
### Performance
|
|
442
|
-
|
|
443
|
-
```tsx
|
|
444
|
-
// ✅ Good - Memoized expensive operations
|
|
445
|
-
const expensiveValue = useMemo(() => {
|
|
446
|
-
return computeExpensiveValue(data);
|
|
447
|
-
}, [data]);
|
|
448
|
-
|
|
449
|
-
// ❌ Avoid - Recomputing on every render
|
|
450
|
-
const expensiveValue = computeExpensiveValue(data);
|
|
451
|
-
```
|
|
33
|
+
## Available exports
|
|
452
34
|
|
|
453
|
-
|
|
35
|
+
- `useDebouncedValue` — debounce a changing value.
|
|
36
|
+
- `useLocalStorage` — state persisted to `localStorage`.
|
|
37
|
+
- `useMediaQuery` — reactively match a media query.
|
|
38
|
+
- `useClickOutside` — run a callback on clicks outside a ref.
|
|
39
|
+
- `useIsMobile` — boolean for a mobile-width viewport.
|
|
40
|
+
- `useFormField` — access form-field context (with `FormFieldContext`,
|
|
41
|
+
`FormItemContext`, and the `FormFieldContextValue` / `FormItemContextValue`
|
|
42
|
+
types).
|
|
43
|
+
- `useAdvancedSearch` — search state and behaviour (with `SearchContext` and the
|
|
44
|
+
`EmptyStateBehavior` / `EmptyStateBehaviour` types).
|
|
45
|
+
- Re-exported types: `SearchResult`, `SearchSection` (from
|
|
46
|
+
`@foundrykit/types`).
|
|
47
|
+
- `noop` — a no-operation utility function.
|
|
454
48
|
|
|
455
|
-
|
|
49
|
+
## Documentation
|
|
456
50
|
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
3. Add JSDoc documentation
|
|
460
|
-
4. Write unit tests
|
|
461
|
-
5. Include usage examples
|
|
462
|
-
6. Update this README
|
|
51
|
+
Each hook is documented with JSDoc at its point of export; hover in your editor
|
|
52
|
+
for signatures and usage notes. See `src/index.ts` for the full export surface.
|
|
463
53
|
|
|
464
54
|
## License
|
|
465
55
|
|
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,6 +175,27 @@ 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
201
|
* Automatically handles serialization/deserialization and SSR safety.
|
|
@@ -134,41 +279,6 @@ declare function useLocalStorage<T>(key: string, initialValue: T): readonly [T,
|
|
|
134
279
|
*/
|
|
135
280
|
declare function useMediaQuery(query: string): boolean;
|
|
136
281
|
|
|
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
282
|
/**
|
|
173
283
|
* Hook that detects if the current viewport is mobile-sized.
|
|
174
284
|
* Uses a breakpoint of 768px to determine mobile vs desktop.
|
|
@@ -210,116 +320,6 @@ declare function useClickOutside<T extends HTMLElement = HTMLElement>(ref: RefOb
|
|
|
210
320
|
*/
|
|
211
321
|
declare function useIsMobile(): boolean;
|
|
212
322
|
|
|
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
323
|
declare function noop(): void;
|
|
324
324
|
|
|
325
325
|
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,8 +1,47 @@
|
|
|
1
|
+
// src/hooks/use-advanced-search.ts
|
|
2
|
+
import * as React from "react";
|
|
3
|
+
var SearchContext = React.createContext(
|
|
4
|
+
null
|
|
5
|
+
);
|
|
6
|
+
function useAdvancedSearch() {
|
|
7
|
+
const context = React.useContext(SearchContext);
|
|
8
|
+
if (!context) {
|
|
9
|
+
throw new Error(
|
|
10
|
+
"useAdvancedSearch must be used within an AdvancedSearchProvider."
|
|
11
|
+
);
|
|
12
|
+
}
|
|
13
|
+
return context;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// src/hooks/use-click-outside.ts
|
|
17
|
+
import { useEffect, useRef } from "react";
|
|
18
|
+
function useClickOutside(ref, handler) {
|
|
19
|
+
const handlerRef = useRef(handler);
|
|
20
|
+
useEffect(() => {
|
|
21
|
+
handlerRef.current = handler;
|
|
22
|
+
}, [handler]);
|
|
23
|
+
useEffect(() => {
|
|
24
|
+
const listener = (event) => {
|
|
25
|
+
const el = ref?.current;
|
|
26
|
+
if (!el || el.contains(event?.target || null)) {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
handlerRef.current(event);
|
|
30
|
+
};
|
|
31
|
+
document.addEventListener("mousedown", listener);
|
|
32
|
+
document.addEventListener("touchstart", listener);
|
|
33
|
+
return () => {
|
|
34
|
+
document.removeEventListener("mousedown", listener);
|
|
35
|
+
document.removeEventListener("touchstart", listener);
|
|
36
|
+
};
|
|
37
|
+
}, [ref]);
|
|
38
|
+
}
|
|
39
|
+
|
|
1
40
|
// src/hooks/use-debounced-value.ts
|
|
2
|
-
import {
|
|
41
|
+
import { useEffect as useEffect2, useState } from "react";
|
|
3
42
|
function useDebouncedValue(value, delay) {
|
|
4
43
|
const [debouncedValue, setDebouncedValue] = useState(value);
|
|
5
|
-
|
|
44
|
+
useEffect2(() => {
|
|
6
45
|
const handler = setTimeout(() => {
|
|
7
46
|
setDebouncedValue(value);
|
|
8
47
|
}, delay);
|
|
@@ -13,6 +52,38 @@ function useDebouncedValue(value, delay) {
|
|
|
13
52
|
return debouncedValue;
|
|
14
53
|
}
|
|
15
54
|
|
|
55
|
+
// src/hooks/use-form-field.ts
|
|
56
|
+
import * as React2 from "react";
|
|
57
|
+
import {
|
|
58
|
+
useFormContext,
|
|
59
|
+
useFormState
|
|
60
|
+
} from "react-hook-form";
|
|
61
|
+
var FormFieldContext = React2.createContext(
|
|
62
|
+
{}
|
|
63
|
+
);
|
|
64
|
+
var FormItemContext = React2.createContext(
|
|
65
|
+
{}
|
|
66
|
+
);
|
|
67
|
+
function useFormField() {
|
|
68
|
+
const fieldContext = React2.useContext(FormFieldContext);
|
|
69
|
+
const itemContext = React2.useContext(FormItemContext);
|
|
70
|
+
const { getFieldState } = useFormContext();
|
|
71
|
+
const formState = useFormState({ name: fieldContext.name });
|
|
72
|
+
const fieldState = getFieldState(fieldContext.name, formState);
|
|
73
|
+
if (!fieldContext) {
|
|
74
|
+
throw new Error("useFormField should be used within <FormField>");
|
|
75
|
+
}
|
|
76
|
+
const { id } = itemContext;
|
|
77
|
+
return {
|
|
78
|
+
id,
|
|
79
|
+
name: fieldContext.name,
|
|
80
|
+
formItemId: `${id}-form-item`,
|
|
81
|
+
formDescriptionId: `${id}-form-item-description`,
|
|
82
|
+
formMessageId: `${id}-form-item-message`,
|
|
83
|
+
...fieldState
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
16
87
|
// src/hooks/use-local-storage.ts
|
|
17
88
|
import { useState as useState2 } from "react";
|
|
18
89
|
function useLocalStorage(key, initialValue) {
|
|
@@ -43,49 +114,29 @@ function useLocalStorage(key, initialValue) {
|
|
|
43
114
|
}
|
|
44
115
|
|
|
45
116
|
// src/hooks/use-media-query.ts
|
|
46
|
-
import {
|
|
117
|
+
import { useEffect as useEffect3, useState as useState3 } from "react";
|
|
47
118
|
function useMediaQuery(query) {
|
|
48
|
-
const [matches, setMatches] = useState3(
|
|
49
|
-
|
|
119
|
+
const [matches, setMatches] = useState3(
|
|
120
|
+
() => typeof window !== "undefined" ? window.matchMedia(query).matches : false
|
|
121
|
+
);
|
|
122
|
+
useEffect3(() => {
|
|
50
123
|
const media = window.matchMedia(query);
|
|
51
|
-
if (media.matches !== matches) {
|
|
52
|
-
setMatches(media.matches);
|
|
53
|
-
}
|
|
54
124
|
const listener = () => setMatches(media.matches);
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
125
|
+
listener();
|
|
126
|
+
media.addEventListener("change", listener);
|
|
127
|
+
return () => media.removeEventListener("change", listener);
|
|
128
|
+
}, [query]);
|
|
58
129
|
return matches;
|
|
59
130
|
}
|
|
60
131
|
|
|
61
|
-
// src/hooks/use-click-outside.ts
|
|
62
|
-
import { useEffect as useEffect3 } from "react";
|
|
63
|
-
function useClickOutside(ref, handler) {
|
|
64
|
-
useEffect3(() => {
|
|
65
|
-
const listener = (event) => {
|
|
66
|
-
const el = ref?.current;
|
|
67
|
-
if (!el || el.contains(event?.target || null)) {
|
|
68
|
-
return;
|
|
69
|
-
}
|
|
70
|
-
handler(event);
|
|
71
|
-
};
|
|
72
|
-
document.addEventListener("mousedown", listener);
|
|
73
|
-
document.addEventListener("touchstart", listener);
|
|
74
|
-
return () => {
|
|
75
|
-
document.removeEventListener("mousedown", listener);
|
|
76
|
-
document.removeEventListener("touchstart", listener);
|
|
77
|
-
};
|
|
78
|
-
}, [ref, handler]);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
132
|
// src/hooks/use-mobile.ts
|
|
82
|
-
import * as
|
|
133
|
+
import * as React3 from "react";
|
|
83
134
|
var MOBILE_BREAKPOINT = 768;
|
|
84
135
|
function useIsMobile() {
|
|
85
|
-
const [isMobile, setIsMobile] =
|
|
136
|
+
const [isMobile, setIsMobile] = React3.useState(
|
|
86
137
|
void 0
|
|
87
138
|
);
|
|
88
|
-
|
|
139
|
+
React3.useEffect(() => {
|
|
89
140
|
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
|
90
141
|
const onChange = () => {
|
|
91
142
|
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
|
@@ -97,53 +148,6 @@ function useIsMobile() {
|
|
|
97
148
|
return !!isMobile;
|
|
98
149
|
}
|
|
99
150
|
|
|
100
|
-
// src/hooks/use-form-field.ts
|
|
101
|
-
import * as React2 from "react";
|
|
102
|
-
import {
|
|
103
|
-
useFormContext,
|
|
104
|
-
useFormState
|
|
105
|
-
} from "react-hook-form";
|
|
106
|
-
var FormFieldContext = React2.createContext(
|
|
107
|
-
{}
|
|
108
|
-
);
|
|
109
|
-
var FormItemContext = React2.createContext(
|
|
110
|
-
{}
|
|
111
|
-
);
|
|
112
|
-
function useFormField() {
|
|
113
|
-
const fieldContext = React2.useContext(FormFieldContext);
|
|
114
|
-
const itemContext = React2.useContext(FormItemContext);
|
|
115
|
-
const { getFieldState } = useFormContext();
|
|
116
|
-
const formState = useFormState({ name: fieldContext.name });
|
|
117
|
-
const fieldState = getFieldState(fieldContext.name, formState);
|
|
118
|
-
if (!fieldContext) {
|
|
119
|
-
throw new Error("useFormField should be used within <FormField>");
|
|
120
|
-
}
|
|
121
|
-
const { id } = itemContext;
|
|
122
|
-
return {
|
|
123
|
-
id,
|
|
124
|
-
name: fieldContext.name,
|
|
125
|
-
formItemId: `${id}-form-item`,
|
|
126
|
-
formDescriptionId: `${id}-form-item-description`,
|
|
127
|
-
formMessageId: `${id}-form-item-message`,
|
|
128
|
-
...fieldState
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
// src/hooks/use-advanced-search.ts
|
|
133
|
-
import * as React3 from "react";
|
|
134
|
-
var SearchContext = React3.createContext(
|
|
135
|
-
null
|
|
136
|
-
);
|
|
137
|
-
function useAdvancedSearch() {
|
|
138
|
-
const context = React3.useContext(SearchContext);
|
|
139
|
-
if (!context) {
|
|
140
|
-
throw new Error(
|
|
141
|
-
"useAdvancedSearch must be used within an AdvancedSearchProvider."
|
|
142
|
-
);
|
|
143
|
-
}
|
|
144
|
-
return context;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
151
|
// src/lib/utils.ts
|
|
148
152
|
function noop() {
|
|
149
153
|
}
|
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;AACd,cAAQ,IAAI,KAAK;AAAA,IACnB;AAAA,EACF;AAEA,SAAO,CAAC,aAAa,QAAQ;AAC/B;;;AC5EA,SAAS,YAAAC,WAAU,aAAAC,kBAAiB;AAsC7B,SAAS,cAAc,OAAwB;AACpD,QAAM,CAAC,SAAS,UAAU,IAAID,UAAS,KAAK;AAE5C,EAAAC,WAAU,MAAM;AACd,UAAM,QAAQ,OAAO,WAAW,KAAK;AACrC,QAAI,MAAM,YAAY,SAAS;AAC7B,iBAAW,MAAM,OAAO;AAAA,IAC1B;AACA,UAAM,WAAW,MAAM,WAAW,MAAM,OAAO;AAC/C,WAAO,iBAAiB,UAAU,QAAQ;AAC1C,WAAO,MAAM,OAAO,oBAAoB,UAAU,QAAQ;AAAA,EAC5D,GAAG,CAAC,SAAS,KAAK,CAAC;AAEnB,SAAO;AACT;;;ACpDA,SAAS,aAAAC,kBAA4B;AAmC9B,SAAS,gBACd,KACA,SACA;AACA,EAAAA,WAAU,MAAM;AACd,UAAM,WAAW,CAAC,UAAmC;AACnD,YAAM,KAAK,KAAK;AAChB,UAAI,CAAC,MAAM,GAAG,SAAU,OAAO,UAAmB,IAAI,GAAG;AACvD;AAAA,MACF;AAEA,cAAQ,KAAK;AAAA,IACf;AAEA,aAAS,iBAAiB,aAAa,QAAQ;AAC/C,aAAS,iBAAiB,cAAc,QAAQ;AAEhD,WAAO,MAAM;AACX,eAAS,oBAAoB,aAAa,QAAQ;AAClD,eAAS,oBAAoB,cAAc,QAAQ;AAAA,IACrD;AAAA,EACF,GAAG,CAAC,KAAK,OAAO,CAAC;AACnB;;;ACzDA,YAAY,WAAW;AAGvB,IAAM,oBAAoB;AAyCnB,SAAS,cAAc;AAC5B,QAAM,CAAC,UAAU,WAAW,IAAU;AAAA,IACpC;AAAA,EACF;AAEA,EAAM,gBAAU,MAAM;AACpB,UAAM,MAAM,OAAO,WAAW,eAAe,oBAAoB,CAAC,KAAK;AACvE,UAAM,WAAW,MAAM;AACrB,kBAAY,OAAO,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 { 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 { 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":"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","names":["useEffect","React","useState","useEffect","useState","React"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@foundrykit/hooks",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.7",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"private": false,
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -26,22 +26,24 @@
|
|
|
26
26
|
"@types/node": "^20.19.9",
|
|
27
27
|
"@types/react": "^19.1.9",
|
|
28
28
|
"@types/react-dom": "^19.1.7",
|
|
29
|
-
"eslint": "^9.0.0",
|
|
30
29
|
"tsup": "^8.0.0",
|
|
31
30
|
"typescript": "^5.9.2",
|
|
32
|
-
"@foundrykit/
|
|
33
|
-
"@foundrykit/types": "2.0.
|
|
34
|
-
"@foundrykit/typescript-config": "1.0.5"
|
|
31
|
+
"@foundrykit/typescript-config": "1.0.6",
|
|
32
|
+
"@foundrykit/types": "2.0.7"
|
|
35
33
|
},
|
|
36
34
|
"peerDependencies": {
|
|
37
35
|
"react": "^19.1.1",
|
|
38
36
|
"react-dom": "^19.1.1",
|
|
39
37
|
"react-hook-form": "^7.62.0"
|
|
40
38
|
},
|
|
39
|
+
"repository": {
|
|
40
|
+
"type": "git",
|
|
41
|
+
"url": "git+https://github.com/umi-labs/foundry.git",
|
|
42
|
+
"directory": "packages/hooks"
|
|
43
|
+
},
|
|
41
44
|
"scripts": {
|
|
42
45
|
"build": "tsup",
|
|
43
46
|
"dev": "tsup --watch",
|
|
44
|
-
"lint": "eslint . --max-warnings 0",
|
|
45
47
|
"type-check": "tsc --noEmit"
|
|
46
48
|
}
|
|
47
49
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useEffect,
|
|
1
|
+
import { type RefObject, useEffect, useRef } from 'react';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Hook that detects clicks outside of a specified element.
|
|
@@ -37,6 +37,13 @@ export function useClickOutside<T extends HTMLElement = HTMLElement>(
|
|
|
37
37
|
ref: RefObject<T>,
|
|
38
38
|
handler: (event: MouseEvent | TouchEvent) => void
|
|
39
39
|
) {
|
|
40
|
+
// Keep the latest handler in a ref so an inline handler (the common call
|
|
41
|
+
// site) doesn't re-add/remove the listeners on every render.
|
|
42
|
+
const handlerRef = useRef(handler);
|
|
43
|
+
useEffect(() => {
|
|
44
|
+
handlerRef.current = handler;
|
|
45
|
+
}, [handler]);
|
|
46
|
+
|
|
40
47
|
useEffect(() => {
|
|
41
48
|
const listener = (event: MouseEvent | TouchEvent) => {
|
|
42
49
|
const el = ref?.current;
|
|
@@ -44,7 +51,7 @@ export function useClickOutside<T extends HTMLElement = HTMLElement>(
|
|
|
44
51
|
return;
|
|
45
52
|
}
|
|
46
53
|
|
|
47
|
-
|
|
54
|
+
handlerRef.current(event);
|
|
48
55
|
};
|
|
49
56
|
|
|
50
57
|
document.addEventListener('mousedown', listener);
|
|
@@ -54,5 +61,5 @@ export function useClickOutside<T extends HTMLElement = HTMLElement>(
|
|
|
54
61
|
document.removeEventListener('mousedown', listener);
|
|
55
62
|
document.removeEventListener('touchstart', listener);
|
|
56
63
|
};
|
|
57
|
-
}, [ref
|
|
64
|
+
}, [ref]);
|
|
58
65
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { useEffect, useState } from 'react';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Hook that tracks whether a CSS media query matches the current viewport.
|
|
@@ -37,17 +37,21 @@ import { useState, useEffect } from 'react';
|
|
|
37
37
|
* ```
|
|
38
38
|
*/
|
|
39
39
|
export function useMediaQuery(query: string): boolean {
|
|
40
|
-
|
|
40
|
+
// SSR-safe initial value; hydrated to the real match in the effect.
|
|
41
|
+
const [matches, setMatches] = useState(() =>
|
|
42
|
+
typeof window !== 'undefined' ? window.matchMedia(query).matches : false
|
|
43
|
+
);
|
|
41
44
|
|
|
42
45
|
useEffect(() => {
|
|
43
46
|
const media = window.matchMedia(query);
|
|
44
|
-
if (media.matches !== matches) {
|
|
45
|
-
setMatches(media.matches);
|
|
46
|
-
}
|
|
47
47
|
const listener = () => setMatches(media.matches);
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
48
|
+
// Subscribe to the MediaQueryList's own `change` event so non-viewport
|
|
49
|
+
// queries (prefers-color-scheme, prefers-reduced-motion, orientation, …)
|
|
50
|
+
// update too — a `resize` listener never fires for those.
|
|
51
|
+
listener();
|
|
52
|
+
media.addEventListener('change', listener);
|
|
53
|
+
return () => media.removeEventListener('change', listener);
|
|
54
|
+
}, [query]);
|
|
51
55
|
|
|
52
56
|
return matches;
|
|
53
57
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,23 +1,24 @@
|
|
|
1
1
|
// Export all hooks
|
|
2
|
-
|
|
3
|
-
export {
|
|
4
|
-
export {
|
|
2
|
+
|
|
3
|
+
export type { SearchResult, SearchSection } from '@foundrykit/types';
|
|
4
|
+
export {
|
|
5
|
+
type EmptyStateBehavior,
|
|
6
|
+
type EmptyStateBehaviour,
|
|
7
|
+
SearchContext,
|
|
8
|
+
useAdvancedSearch,
|
|
9
|
+
} from './hooks/use-advanced-search.js';
|
|
5
10
|
export { useClickOutside } from './hooks/use-click-outside.js';
|
|
6
|
-
export {
|
|
11
|
+
export { useDebouncedValue } from './hooks/use-debounced-value.js';
|
|
7
12
|
export {
|
|
8
|
-
useFormField,
|
|
9
13
|
FormFieldContext,
|
|
10
|
-
FormItemContext,
|
|
11
14
|
type FormFieldContextValue,
|
|
15
|
+
FormItemContext,
|
|
12
16
|
type FormItemContextValue,
|
|
17
|
+
useFormField,
|
|
13
18
|
} from './hooks/use-form-field.js';
|
|
14
|
-
export {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
type EmptyStateBehavior,
|
|
18
|
-
type EmptyStateBehaviour,
|
|
19
|
-
} from './hooks/use-advanced-search.js';
|
|
20
|
-
export type { SearchResult, SearchSection } from '@foundrykit/types';
|
|
19
|
+
export { useLocalStorage } from './hooks/use-local-storage.js';
|
|
20
|
+
export { useMediaQuery } from './hooks/use-media-query.js';
|
|
21
|
+
export { useIsMobile } from './hooks/use-mobile.js';
|
|
21
22
|
|
|
22
23
|
// Export utilities
|
|
23
24
|
export * from './lib/utils.js';
|
package/eslint.config.js
DELETED