@foundrykit/hooks 1.0.7 → 1.0.9

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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # @foundrykit/hooks
2
2
 
3
+ ## 1.0.9
4
+
5
+ ### Patch Changes
6
+
7
+ - moving hooks and context for forms to the hooks package
8
+
9
+ ## 1.0.8
10
+
11
+ ### Patch Changes
12
+
13
+ - Adding in JSdocs for better DX
14
+
3
15
  ## 1.0.7
4
16
 
5
17
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -1,36 +1,315 @@
1
1
  import * as React from 'react';
2
2
  import { RefObject } from 'react';
3
+ import * as react_hook_form from 'react-hook-form';
4
+ import { FieldValues, FieldPath } from 'react-hook-form';
3
5
  import { SearchResult } from '@foundrykit/types';
4
6
  export { SearchResult, SearchSection } from '@foundrykit/types';
5
7
 
8
+ /**
9
+ * Hook that returns a debounced version of the provided value.
10
+ * The returned value will only update after the specified delay has passed
11
+ * since the last time the input value changed.
12
+ *
13
+ * @template T - The type of the value to debounce
14
+ * @param value - The value to debounce
15
+ * @param delay - The delay in milliseconds
16
+ * @returns The debounced value
17
+ *
18
+ * @example
19
+ * ```tsx
20
+ * function SearchInput() {
21
+ * const [query, setQuery] = useState('');
22
+ * const debouncedQuery = useDebouncedValue(query, 300);
23
+ *
24
+ * useEffect(() => {
25
+ * if (debouncedQuery) {
26
+ * // Perform search with debounced query
27
+ * searchAPI(debouncedQuery);
28
+ * }
29
+ * }, [debouncedQuery]);
30
+ *
31
+ * return (
32
+ * <input
33
+ * value={query}
34
+ * onChange={(e) => setQuery(e.target.value)}
35
+ * />
36
+ * );
37
+ * }
38
+ * ```
39
+ *
40
+ * @example
41
+ * ```tsx
42
+ * // Debouncing form validation
43
+ * const debouncedEmail = useDebouncedValue(email, 500);
44
+ *
45
+ * useEffect(() => {
46
+ * if (debouncedEmail) {
47
+ * validateEmail(debouncedEmail);
48
+ * }
49
+ * }, [debouncedEmail]);
50
+ * ```
51
+ */
6
52
  declare function useDebouncedValue<T>(value: T, delay: number): T;
7
53
 
54
+ /**
55
+ * Hook that provides localStorage functionality with React state synchronization.
56
+ * Automatically handles serialization/deserialization and SSR safety.
57
+ *
58
+ * @template T - The type of the value to store
59
+ * @param key - The localStorage key
60
+ * @param initialValue - The initial value if no stored value exists
61
+ * @returns A tuple containing the stored value and a setter function
62
+ *
63
+ * @example
64
+ * ```tsx
65
+ * function UserPreferences() {
66
+ * const [theme, setTheme] = useLocalStorage('theme', 'light');
67
+ * const [language, setLanguage] = useLocalStorage('language', 'en');
68
+ *
69
+ * return (
70
+ * <div>
71
+ * <select value={theme} onChange={(e) => setTheme(e.target.value)}>
72
+ * <option value="light">Light</option>
73
+ * <option value="dark">Dark</option>
74
+ * </select>
75
+ * </div>
76
+ * );
77
+ * }
78
+ * ```
79
+ *
80
+ * @example
81
+ * ```tsx
82
+ * // With complex objects
83
+ * interface UserSettings {
84
+ * notifications: boolean;
85
+ * fontSize: number;
86
+ * }
87
+ *
88
+ * const [settings, setSettings] = useLocalStorage<UserSettings>('user-settings', {
89
+ * notifications: true,
90
+ * fontSize: 14
91
+ * });
92
+ *
93
+ * // Update with function (like useState)
94
+ * setSettings(prev => ({ ...prev, fontSize: 16 }));
95
+ * ```
96
+ */
8
97
  declare function useLocalStorage<T>(key: string, initialValue: T): readonly [T, (value: T | ((val: T) => T)) => void];
9
98
 
99
+ /**
100
+ * Hook that tracks whether a CSS media query matches the current viewport.
101
+ * Automatically updates when the viewport size changes.
102
+ *
103
+ * @param query - The CSS media query string to match
104
+ * @returns Boolean indicating whether the media query currently matches
105
+ *
106
+ * @example
107
+ * ```tsx
108
+ * function ResponsiveComponent() {
109
+ * const isMobile = useMediaQuery('(max-width: 768px)');
110
+ * const isTablet = useMediaQuery('(min-width: 769px) and (max-width: 1024px)');
111
+ * const isDesktop = useMediaQuery('(min-width: 1025px)');
112
+ *
113
+ * return (
114
+ * <div>
115
+ * {isMobile && <MobileLayout />}
116
+ * {isTablet && <TabletLayout />}
117
+ * {isDesktop && <DesktopLayout />}
118
+ * </div>
119
+ * );
120
+ * }
121
+ * ```
122
+ *
123
+ * @example
124
+ * ```tsx
125
+ * // Dark mode detection
126
+ * const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');
127
+ *
128
+ * // High contrast mode
129
+ * const prefersHighContrast = useMediaQuery('(prefers-contrast: high)');
130
+ *
131
+ * // Reduced motion
132
+ * const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');
133
+ * ```
134
+ */
10
135
  declare function useMediaQuery(query: string): boolean;
11
136
 
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
+ */
12
170
  declare function useClickOutside<T extends HTMLElement = HTMLElement>(ref: RefObject<T>, handler: (event: MouseEvent | TouchEvent) => void): void;
13
171
 
172
+ /**
173
+ * Hook that detects if the current viewport is mobile-sized.
174
+ * Uses a breakpoint of 768px to determine mobile vs desktop.
175
+ *
176
+ * @returns Boolean indicating whether the current viewport is mobile-sized
177
+ *
178
+ * @example
179
+ * ```tsx
180
+ * function ResponsiveHeader() {
181
+ * const isMobile = useIsMobile();
182
+ *
183
+ * return (
184
+ * <header>
185
+ * {isMobile ? (
186
+ * <MobileNavigation />
187
+ * ) : (
188
+ * <DesktopNavigation />
189
+ * )}
190
+ * </header>
191
+ * );
192
+ * }
193
+ * ```
194
+ *
195
+ * @example
196
+ * ```tsx
197
+ * // Conditional rendering based on mobile state
198
+ * function ProductGrid() {
199
+ * const isMobile = useIsMobile();
200
+ *
201
+ * return (
202
+ * <div className={isMobile ? 'grid-cols-1' : 'grid-cols-3'}>
203
+ * {products.map(product => (
204
+ * <ProductCard key={product.id} product={product} />
205
+ * ))}
206
+ * </div>
207
+ * );
208
+ * }
209
+ * ```
210
+ */
14
211
  declare function useIsMobile(): boolean;
15
212
 
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
+ * emptyStateBehavior="show-empty-message"
241
+ *
242
+ * // Hide results until minimum characters typed
243
+ * emptyStateBehavior="hide-until-min-chars"
244
+ *
245
+ * // Show all results initially
246
+ * emptyStateBehavior="show-all-results"
247
+ * ```
248
+ */
16
249
  type EmptyStateBehavior = 'show-empty-message' | 'hide-until-min-chars' | 'show-all-results';
250
+ /**
251
+ * Context properties for the advanced search functionality.
252
+ * Provides all necessary state and handlers for search components.
253
+ */
17
254
  type SearchContextProps = {
255
+ /** Current search query string */
18
256
  query: string;
257
+ /** Function to update the search query */
19
258
  setQuery: (query: string) => void;
259
+ /** Whether the search results dropdown is open */
20
260
  isOpen: boolean;
261
+ /** Function to control the dropdown open state */
21
262
  setIsOpen: (open: boolean) => void;
263
+ /** Array of current search results */
22
264
  results: SearchResult[];
265
+ /** Function to update the search results */
23
266
  setResults: (results: SearchResult[]) => void;
267
+ /** Whether a search request is currently in progress */
24
268
  isLoading: boolean;
269
+ /** Function to control the loading state */
25
270
  setIsLoading: (loading: boolean) => void;
271
+ /** Function to trigger a search with the given query */
26
272
  onSearch: (query: string) => void;
273
+ /** Function called when a search result is selected */
27
274
  onResultSelect: (result: SearchResult) => void;
275
+ /** Behavior configuration for empty states */
28
276
  emptyStateBehavior: EmptyStateBehavior;
277
+ /** Minimum number of characters required before triggering search */
29
278
  minQueryLength: number;
30
279
  };
280
+ /**
281
+ * React context for sharing search state between components.
282
+ * Created with null as default to ensure proper error handling.
283
+ */
31
284
  declare const SearchContext: React.Context<SearchContextProps | null>;
285
+ /**
286
+ * Hook to access the advanced search context.
287
+ * Must be used within an AdvancedSearchProvider component.
288
+ *
289
+ * @returns SearchContextProps - The search context containing state and handlers
290
+ * @throws Error if used outside of AdvancedSearchProvider
291
+ *
292
+ * @example
293
+ * ```tsx
294
+ * function SearchComponent() {
295
+ * const { query, setQuery, results, onSearch } = useAdvancedSearch();
296
+ *
297
+ * return (
298
+ * <div>
299
+ * <input
300
+ * value={query}
301
+ * onChange={(e) => setQuery(e.target.value)}
302
+ * />
303
+ * {results.map(result => (
304
+ * <div key={result.id}>{result.title}</div>
305
+ * ))}
306
+ * </div>
307
+ * );
308
+ * }
309
+ * ```
310
+ */
32
311
  declare function useAdvancedSearch(): SearchContextProps;
33
312
 
34
313
  declare function noop(): void;
35
314
 
36
- export { type EmptyStateBehavior, SearchContext, noop, useAdvancedSearch, useClickOutside, useDebouncedValue, useIsMobile, useLocalStorage, useMediaQuery };
315
+ export { type EmptyStateBehavior, FormFieldContext, type FormFieldContextValue, FormItemContext, type FormItemContextValue, SearchContext, noop, useAdvancedSearch, useClickOutside, useDebouncedValue, useFormField, useIsMobile, useLocalStorage, useMediaQuery };
package/dist/index.js CHANGED
@@ -43,10 +43,10 @@ function useLocalStorage(key, initialValue) {
43
43
  }
44
44
 
45
45
  // src/hooks/use-media-query.ts
46
- import { useState as useState3, useEffect as useEffect3 } from "react";
46
+ import { useState as useState3, useEffect as useEffect2 } from "react";
47
47
  function useMediaQuery(query) {
48
48
  const [matches, setMatches] = useState3(false);
49
- useEffect3(() => {
49
+ useEffect2(() => {
50
50
  const media = window.matchMedia(query);
51
51
  if (media.matches !== matches) {
52
52
  setMatches(media.matches);
@@ -59,9 +59,9 @@ function useMediaQuery(query) {
59
59
  }
60
60
 
61
61
  // src/hooks/use-click-outside.ts
62
- import { useEffect as useEffect4 } from "react";
62
+ import { useEffect as useEffect3 } from "react";
63
63
  function useClickOutside(ref, handler) {
64
- useEffect4(() => {
64
+ useEffect3(() => {
65
65
  const listener = (event) => {
66
66
  const el = ref?.current;
67
67
  if (!el || el.contains(event?.target || null)) {
@@ -97,13 +97,45 @@ function useIsMobile() {
97
97
  return !!isMobile;
98
98
  }
99
99
 
100
- // src/hooks/use-advanced-search.ts
100
+ // src/hooks/use-form-field.ts
101
101
  import * as React2 from "react";
102
- var SearchContext = React2.createContext(
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(
103
135
  null
104
136
  );
105
137
  function useAdvancedSearch() {
106
- const context = React2.useContext(SearchContext);
138
+ const context = React3.useContext(SearchContext);
107
139
  if (!context) {
108
140
  throw new Error(
109
141
  "useAdvancedSearch must be used within an AdvancedSearchProvider."
@@ -116,11 +148,14 @@ function useAdvancedSearch() {
116
148
  function noop() {
117
149
  }
118
150
  export {
151
+ FormFieldContext,
152
+ FormItemContext,
119
153
  SearchContext,
120
154
  noop,
121
155
  useAdvancedSearch,
122
156
  useClickOutside,
123
157
  useDebouncedValue,
158
+ useFormField,
124
159
  useIsMobile,
125
160
  useLocalStorage,
126
161
  useMediaQuery
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-advanced-search.ts","../src/lib/utils.ts"],"sourcesContent":["import { useState, useEffect } from 'react';\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, useEffect } from 'react';\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\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\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\nconst MOBILE_BREAKPOINT = 768;\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 type { SearchResult } from '@foundrykit/types';\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// Search Context\ntype SearchContextProps = {\n query: string;\n setQuery: (query: string) => void;\n isOpen: boolean;\n setIsOpen: (open: boolean) => void;\n results: SearchResult[];\n setResults: (results: SearchResult[]) => void;\n isLoading: boolean;\n setIsLoading: (loading: boolean) => void;\n onSearch: (query: string) => void;\n onResultSelect: (result: SearchResult) => void;\n emptyStateBehavior: EmptyStateBehavior;\n minQueryLength: number;\n};\n\nexport const SearchContext = React.createContext<SearchContextProps | null>(\n null\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;AAE7B,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;;;AChBA,SAAS,YAAAA,iBAA2B;AAE7B,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,IA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oB,cAAc,QAAQ;AAAA,IACrD;AAAA,EACF,GAAG,CAAC,KAAK,OAAO,CAAC;AACnB;;;ACxBA,YAAY,WAAW;AAEvB,IAAM,oBAAoB;AAEnB,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;;;ACpBA,YAAYC,YAAW;AAwBhB,IAAM,gBAAsB;AAAA,EACjC;AACF;AAEO,SAAS,oBAAoB;AAClC,QAAM,UAAgB,kBAAW,aAAa;AAC9C,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;;;ACnCO,SAAS,OAAO;AAEvB;","names":["useState","useState","useEffect","useEffect","React"]}
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 * emptyStateBehavior=\"show-empty-message\"\n *\n * // Hide results until minimum characters typed\n * emptyStateBehavior=\"hide-until-min-chars\"\n *\n * // Show all results initially\n * emptyStateBehavior=\"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/**\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 /** 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 emptyStateBehavior: 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,gBAA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,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;AA0DhB,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;;;AC/FO,SAAS,OAAO;AAEvB;","names":["useState","useState","useEffect","useEffect","React","React"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foundrykit/hooks",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "main": "./dist/index.js",
@@ -19,7 +19,8 @@
19
19
  },
20
20
  "dependencies": {
21
21
  "react": "^19.1.1",
22
- "react-dom": "^19.1.1"
22
+ "react-dom": "^19.1.1",
23
+ "react-hook-form": "^7.62.0"
23
24
  },
24
25
  "devDependencies": {
25
26
  "@types/node": "^20.19.9",
@@ -34,7 +35,8 @@
34
35
  },
35
36
  "peerDependencies": {
36
37
  "react": "^19.1.1",
37
- "react-dom": "^19.1.1"
38
+ "react-dom": "^19.1.1",
39
+ "react-hook-form": "^7.62.0"
38
40
  },
39
41
  "scripts": {
40
42
  "build": "tsup",
@@ -1,31 +1,91 @@
1
1
  import * as React from 'react';
2
2
  import type { SearchResult } from '@foundrykit/types';
3
3
 
4
+ /**
5
+ * Defines the behavior when search results are empty or query is too short.
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * // Show "No results found" message
10
+ * emptyStateBehavior="show-empty-message"
11
+ *
12
+ * // Hide results until minimum characters typed
13
+ * emptyStateBehavior="hide-until-min-chars"
14
+ *
15
+ * // Show all results initially
16
+ * emptyStateBehavior="show-all-results"
17
+ * ```
18
+ */
4
19
  export type EmptyStateBehavior =
5
20
  | 'show-empty-message' // Show "No results found" message
6
21
  | 'hide-until-min-chars' // Don't show popover until min characters
7
22
  | 'show-all-results'; // Show all results initially or after min chars
8
23
 
9
- // Search Context
24
+ /**
25
+ * Context properties for the advanced search functionality.
26
+ * Provides all necessary state and handlers for search components.
27
+ */
10
28
  type SearchContextProps = {
29
+ /** Current search query string */
11
30
  query: string;
31
+ /** Function to update the search query */
12
32
  setQuery: (query: string) => void;
33
+ /** Whether the search results dropdown is open */
13
34
  isOpen: boolean;
35
+ /** Function to control the dropdown open state */
14
36
  setIsOpen: (open: boolean) => void;
37
+ /** Array of current search results */
15
38
  results: SearchResult[];
39
+ /** Function to update the search results */
16
40
  setResults: (results: SearchResult[]) => void;
41
+ /** Whether a search request is currently in progress */
17
42
  isLoading: boolean;
43
+ /** Function to control the loading state */
18
44
  setIsLoading: (loading: boolean) => void;
45
+ /** Function to trigger a search with the given query */
19
46
  onSearch: (query: string) => void;
47
+ /** Function called when a search result is selected */
20
48
  onResultSelect: (result: SearchResult) => void;
49
+ /** Behavior configuration for empty states */
21
50
  emptyStateBehavior: EmptyStateBehavior;
51
+ /** Minimum number of characters required before triggering search */
22
52
  minQueryLength: number;
23
53
  };
24
54
 
55
+ /**
56
+ * React context for sharing search state between components.
57
+ * Created with null as default to ensure proper error handling.
58
+ */
25
59
  export const SearchContext = React.createContext<SearchContextProps | null>(
26
60
  null
27
61
  );
28
62
 
63
+ /**
64
+ * Hook to access the advanced search context.
65
+ * Must be used within an AdvancedSearchProvider component.
66
+ *
67
+ * @returns SearchContextProps - The search context containing state and handlers
68
+ * @throws Error if used outside of AdvancedSearchProvider
69
+ *
70
+ * @example
71
+ * ```tsx
72
+ * function SearchComponent() {
73
+ * const { query, setQuery, results, onSearch } = useAdvancedSearch();
74
+ *
75
+ * return (
76
+ * <div>
77
+ * <input
78
+ * value={query}
79
+ * onChange={(e) => setQuery(e.target.value)}
80
+ * />
81
+ * {results.map(result => (
82
+ * <div key={result.id}>{result.title}</div>
83
+ * ))}
84
+ * </div>
85
+ * );
86
+ * }
87
+ * ```
88
+ */
29
89
  export function useAdvancedSearch() {
30
90
  const context = React.useContext(SearchContext);
31
91
  if (!context) {
@@ -1,5 +1,38 @@
1
1
  import { useEffect, RefObject } from 'react';
2
2
 
3
+ /**
4
+ * Hook that detects clicks outside of a specified element.
5
+ * Useful for closing dropdowns, modals, or other overlay components.
6
+ *
7
+ * @template T - The HTML element type (defaults to HTMLElement)
8
+ * @param ref - React ref object pointing to the element to monitor
9
+ * @param handler - Function called when a click outside is detected
10
+ *
11
+ * @example
12
+ * ```tsx
13
+ * function Dropdown() {
14
+ * const [isOpen, setIsOpen] = useState(false);
15
+ * const dropdownRef = useRef<HTMLDivElement>(null);
16
+ *
17
+ * useClickOutside(dropdownRef, () => {
18
+ * setIsOpen(false);
19
+ * });
20
+ *
21
+ * return (
22
+ * <div ref={dropdownRef}>
23
+ * {isOpen && <div>Dropdown content</div>}
24
+ * </div>
25
+ * );
26
+ * }
27
+ * ```
28
+ *
29
+ * @example
30
+ * ```tsx
31
+ * // With custom element type
32
+ * const modalRef = useRef<HTMLDialogElement>(null);
33
+ * useClickOutside(modalRef, () => closeModal());
34
+ * ```
35
+ */
3
36
  export function useClickOutside<T extends HTMLElement = HTMLElement>(
4
37
  ref: RefObject<T>,
5
38
  handler: (event: MouseEvent | TouchEvent) => void
@@ -1,5 +1,49 @@
1
1
  import { useState, useEffect } from 'react';
2
2
 
3
+ /**
4
+ * Hook that returns a debounced version of the provided value.
5
+ * The returned value will only update after the specified delay has passed
6
+ * since the last time the input value changed.
7
+ *
8
+ * @template T - The type of the value to debounce
9
+ * @param value - The value to debounce
10
+ * @param delay - The delay in milliseconds
11
+ * @returns The debounced value
12
+ *
13
+ * @example
14
+ * ```tsx
15
+ * function SearchInput() {
16
+ * const [query, setQuery] = useState('');
17
+ * const debouncedQuery = useDebouncedValue(query, 300);
18
+ *
19
+ * useEffect(() => {
20
+ * if (debouncedQuery) {
21
+ * // Perform search with debounced query
22
+ * searchAPI(debouncedQuery);
23
+ * }
24
+ * }, [debouncedQuery]);
25
+ *
26
+ * return (
27
+ * <input
28
+ * value={query}
29
+ * onChange={(e) => setQuery(e.target.value)}
30
+ * />
31
+ * );
32
+ * }
33
+ * ```
34
+ *
35
+ * @example
36
+ * ```tsx
37
+ * // Debouncing form validation
38
+ * const debouncedEmail = useDebouncedValue(email, 500);
39
+ *
40
+ * useEffect(() => {
41
+ * if (debouncedEmail) {
42
+ * validateEmail(debouncedEmail);
43
+ * }
44
+ * }, [debouncedEmail]);
45
+ * ```
46
+ */
3
47
  export function useDebouncedValue<T>(value: T, delay: number): T {
4
48
  const [debouncedValue, setDebouncedValue] = useState<T>(value);
5
49
 
@@ -0,0 +1,49 @@
1
+ import * as React from 'react';
2
+ import {
3
+ useFormContext,
4
+ useFormState,
5
+ type FieldPath,
6
+ type FieldValues,
7
+ } from 'react-hook-form';
8
+
9
+ export type FormFieldContextValue<
10
+ TFieldValues extends FieldValues = FieldValues,
11
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
12
+ > = {
13
+ name: TName;
14
+ };
15
+
16
+ export const FormFieldContext = React.createContext<FormFieldContextValue>(
17
+ {} as FormFieldContextValue
18
+ );
19
+
20
+ export type FormItemContextValue = {
21
+ id: string;
22
+ };
23
+
24
+ export const FormItemContext = React.createContext<FormItemContextValue>(
25
+ {} as FormItemContextValue
26
+ );
27
+
28
+ export function useFormField() {
29
+ const fieldContext = React.useContext(FormFieldContext);
30
+ const itemContext = React.useContext(FormItemContext);
31
+ const { getFieldState } = useFormContext();
32
+ const formState = useFormState({ name: fieldContext.name });
33
+ const fieldState = getFieldState(fieldContext.name, formState);
34
+
35
+ if (!fieldContext) {
36
+ throw new Error('useFormField should be used within <FormField>');
37
+ }
38
+
39
+ const { id } = itemContext;
40
+
41
+ return {
42
+ id,
43
+ name: fieldContext.name,
44
+ formItemId: `${id}-form-item`,
45
+ formDescriptionId: `${id}-form-item-description`,
46
+ formMessageId: `${id}-form-item-message`,
47
+ ...fieldState,
48
+ } as const;
49
+ }
@@ -1,5 +1,48 @@
1
- import { useState, useEffect } from 'react';
1
+ import { useState } from 'react';
2
2
 
3
+ /**
4
+ * Hook that provides localStorage functionality with React state synchronization.
5
+ * Automatically handles serialization/deserialization and SSR safety.
6
+ *
7
+ * @template T - The type of the value to store
8
+ * @param key - The localStorage key
9
+ * @param initialValue - The initial value if no stored value exists
10
+ * @returns A tuple containing the stored value and a setter function
11
+ *
12
+ * @example
13
+ * ```tsx
14
+ * function UserPreferences() {
15
+ * const [theme, setTheme] = useLocalStorage('theme', 'light');
16
+ * const [language, setLanguage] = useLocalStorage('language', 'en');
17
+ *
18
+ * return (
19
+ * <div>
20
+ * <select value={theme} onChange={(e) => setTheme(e.target.value)}>
21
+ * <option value="light">Light</option>
22
+ * <option value="dark">Dark</option>
23
+ * </select>
24
+ * </div>
25
+ * );
26
+ * }
27
+ * ```
28
+ *
29
+ * @example
30
+ * ```tsx
31
+ * // With complex objects
32
+ * interface UserSettings {
33
+ * notifications: boolean;
34
+ * fontSize: number;
35
+ * }
36
+ *
37
+ * const [settings, setSettings] = useLocalStorage<UserSettings>('user-settings', {
38
+ * notifications: true,
39
+ * fontSize: 14
40
+ * });
41
+ *
42
+ * // Update with function (like useState)
43
+ * setSettings(prev => ({ ...prev, fontSize: 16 }));
44
+ * ```
45
+ */
3
46
  export function useLocalStorage<T>(key: string, initialValue: T) {
4
47
  // Get from local storage then parse stored json or return initialValue
5
48
  const [storedValue, setStoredValue] = useState<T>(() => {
@@ -1,5 +1,41 @@
1
1
  import { useState, useEffect } from 'react';
2
2
 
3
+ /**
4
+ * Hook that tracks whether a CSS media query matches the current viewport.
5
+ * Automatically updates when the viewport size changes.
6
+ *
7
+ * @param query - The CSS media query string to match
8
+ * @returns Boolean indicating whether the media query currently matches
9
+ *
10
+ * @example
11
+ * ```tsx
12
+ * function ResponsiveComponent() {
13
+ * const isMobile = useMediaQuery('(max-width: 768px)');
14
+ * const isTablet = useMediaQuery('(min-width: 769px) and (max-width: 1024px)');
15
+ * const isDesktop = useMediaQuery('(min-width: 1025px)');
16
+ *
17
+ * return (
18
+ * <div>
19
+ * {isMobile && <MobileLayout />}
20
+ * {isTablet && <TabletLayout />}
21
+ * {isDesktop && <DesktopLayout />}
22
+ * </div>
23
+ * );
24
+ * }
25
+ * ```
26
+ *
27
+ * @example
28
+ * ```tsx
29
+ * // Dark mode detection
30
+ * const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');
31
+ *
32
+ * // High contrast mode
33
+ * const prefersHighContrast = useMediaQuery('(prefers-contrast: high)');
34
+ *
35
+ * // Reduced motion
36
+ * const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');
37
+ * ```
38
+ */
3
39
  export function useMediaQuery(query: string): boolean {
4
40
  const [matches, setMatches] = useState(false);
5
41
 
@@ -1,7 +1,47 @@
1
1
  import * as React from 'react';
2
2
 
3
+ /** The breakpoint width in pixels below which a device is considered mobile */
3
4
  const MOBILE_BREAKPOINT = 768;
4
5
 
6
+ /**
7
+ * Hook that detects if the current viewport is mobile-sized.
8
+ * Uses a breakpoint of 768px to determine mobile vs desktop.
9
+ *
10
+ * @returns Boolean indicating whether the current viewport is mobile-sized
11
+ *
12
+ * @example
13
+ * ```tsx
14
+ * function ResponsiveHeader() {
15
+ * const isMobile = useIsMobile();
16
+ *
17
+ * return (
18
+ * <header>
19
+ * {isMobile ? (
20
+ * <MobileNavigation />
21
+ * ) : (
22
+ * <DesktopNavigation />
23
+ * )}
24
+ * </header>
25
+ * );
26
+ * }
27
+ * ```
28
+ *
29
+ * @example
30
+ * ```tsx
31
+ * // Conditional rendering based on mobile state
32
+ * function ProductGrid() {
33
+ * const isMobile = useIsMobile();
34
+ *
35
+ * return (
36
+ * <div className={isMobile ? 'grid-cols-1' : 'grid-cols-3'}>
37
+ * {products.map(product => (
38
+ * <ProductCard key={product.id} product={product} />
39
+ * ))}
40
+ * </div>
41
+ * );
42
+ * }
43
+ * ```
44
+ */
5
45
  export function useIsMobile() {
6
46
  const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
7
47
  undefined
package/src/index.ts CHANGED
@@ -4,6 +4,13 @@ export { useLocalStorage } from './hooks/use-local-storage.js';
4
4
  export { useMediaQuery } from './hooks/use-media-query.js';
5
5
  export { useClickOutside } from './hooks/use-click-outside.js';
6
6
  export { useIsMobile } from './hooks/use-mobile.js';
7
+ export {
8
+ useFormField,
9
+ FormFieldContext,
10
+ FormItemContext,
11
+ type FormFieldContextValue,
12
+ type FormItemContextValue,
13
+ } from './hooks/use-form-field.js';
7
14
  export {
8
15
  useAdvancedSearch,
9
16
  SearchContext,