@foundrykit/hooks 1.0.7 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @foundrykit/hooks
2
2
 
3
+ ## 1.0.8
4
+
5
+ ### Patch Changes
6
+
7
+ - Adding in JSdocs for better DX
8
+
3
9
  ## 1.0.7
4
10
 
5
11
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -3,32 +3,288 @@ import { RefObject } from 'react';
3
3
  import { SearchResult } from '@foundrykit/types';
4
4
  export { SearchResult, SearchSection } from '@foundrykit/types';
5
5
 
6
+ /**
7
+ * Hook that returns a debounced version of the provided value.
8
+ * The returned value will only update after the specified delay has passed
9
+ * since the last time the input value changed.
10
+ *
11
+ * @template T - The type of the value to debounce
12
+ * @param value - The value to debounce
13
+ * @param delay - The delay in milliseconds
14
+ * @returns The debounced value
15
+ *
16
+ * @example
17
+ * ```tsx
18
+ * function SearchInput() {
19
+ * const [query, setQuery] = useState('');
20
+ * const debouncedQuery = useDebouncedValue(query, 300);
21
+ *
22
+ * useEffect(() => {
23
+ * if (debouncedQuery) {
24
+ * // Perform search with debounced query
25
+ * searchAPI(debouncedQuery);
26
+ * }
27
+ * }, [debouncedQuery]);
28
+ *
29
+ * return (
30
+ * <input
31
+ * value={query}
32
+ * onChange={(e) => setQuery(e.target.value)}
33
+ * />
34
+ * );
35
+ * }
36
+ * ```
37
+ *
38
+ * @example
39
+ * ```tsx
40
+ * // Debouncing form validation
41
+ * const debouncedEmail = useDebouncedValue(email, 500);
42
+ *
43
+ * useEffect(() => {
44
+ * if (debouncedEmail) {
45
+ * validateEmail(debouncedEmail);
46
+ * }
47
+ * }, [debouncedEmail]);
48
+ * ```
49
+ */
6
50
  declare function useDebouncedValue<T>(value: T, delay: number): T;
7
51
 
52
+ /**
53
+ * Hook that provides localStorage functionality with React state synchronization.
54
+ * Automatically handles serialization/deserialization and SSR safety.
55
+ *
56
+ * @template T - The type of the value to store
57
+ * @param key - The localStorage key
58
+ * @param initialValue - The initial value if no stored value exists
59
+ * @returns A tuple containing the stored value and a setter function
60
+ *
61
+ * @example
62
+ * ```tsx
63
+ * function UserPreferences() {
64
+ * const [theme, setTheme] = useLocalStorage('theme', 'light');
65
+ * const [language, setLanguage] = useLocalStorage('language', 'en');
66
+ *
67
+ * return (
68
+ * <div>
69
+ * <select value={theme} onChange={(e) => setTheme(e.target.value)}>
70
+ * <option value="light">Light</option>
71
+ * <option value="dark">Dark</option>
72
+ * </select>
73
+ * </div>
74
+ * );
75
+ * }
76
+ * ```
77
+ *
78
+ * @example
79
+ * ```tsx
80
+ * // With complex objects
81
+ * interface UserSettings {
82
+ * notifications: boolean;
83
+ * fontSize: number;
84
+ * }
85
+ *
86
+ * const [settings, setSettings] = useLocalStorage<UserSettings>('user-settings', {
87
+ * notifications: true,
88
+ * fontSize: 14
89
+ * });
90
+ *
91
+ * // Update with function (like useState)
92
+ * setSettings(prev => ({ ...prev, fontSize: 16 }));
93
+ * ```
94
+ */
8
95
  declare function useLocalStorage<T>(key: string, initialValue: T): readonly [T, (value: T | ((val: T) => T)) => void];
9
96
 
97
+ /**
98
+ * Hook that tracks whether a CSS media query matches the current viewport.
99
+ * Automatically updates when the viewport size changes.
100
+ *
101
+ * @param query - The CSS media query string to match
102
+ * @returns Boolean indicating whether the media query currently matches
103
+ *
104
+ * @example
105
+ * ```tsx
106
+ * function ResponsiveComponent() {
107
+ * const isMobile = useMediaQuery('(max-width: 768px)');
108
+ * const isTablet = useMediaQuery('(min-width: 769px) and (max-width: 1024px)');
109
+ * const isDesktop = useMediaQuery('(min-width: 1025px)');
110
+ *
111
+ * return (
112
+ * <div>
113
+ * {isMobile && <MobileLayout />}
114
+ * {isTablet && <TabletLayout />}
115
+ * {isDesktop && <DesktopLayout />}
116
+ * </div>
117
+ * );
118
+ * }
119
+ * ```
120
+ *
121
+ * @example
122
+ * ```tsx
123
+ * // Dark mode detection
124
+ * const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');
125
+ *
126
+ * // High contrast mode
127
+ * const prefersHighContrast = useMediaQuery('(prefers-contrast: high)');
128
+ *
129
+ * // Reduced motion
130
+ * const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');
131
+ * ```
132
+ */
10
133
  declare function useMediaQuery(query: string): boolean;
11
134
 
135
+ /**
136
+ * Hook that detects clicks outside of a specified element.
137
+ * Useful for closing dropdowns, modals, or other overlay components.
138
+ *
139
+ * @template T - The HTML element type (defaults to HTMLElement)
140
+ * @param ref - React ref object pointing to the element to monitor
141
+ * @param handler - Function called when a click outside is detected
142
+ *
143
+ * @example
144
+ * ```tsx
145
+ * function Dropdown() {
146
+ * const [isOpen, setIsOpen] = useState(false);
147
+ * const dropdownRef = useRef<HTMLDivElement>(null);
148
+ *
149
+ * useClickOutside(dropdownRef, () => {
150
+ * setIsOpen(false);
151
+ * });
152
+ *
153
+ * return (
154
+ * <div ref={dropdownRef}>
155
+ * {isOpen && <div>Dropdown content</div>}
156
+ * </div>
157
+ * );
158
+ * }
159
+ * ```
160
+ *
161
+ * @example
162
+ * ```tsx
163
+ * // With custom element type
164
+ * const modalRef = useRef<HTMLDialogElement>(null);
165
+ * useClickOutside(modalRef, () => closeModal());
166
+ * ```
167
+ */
12
168
  declare function useClickOutside<T extends HTMLElement = HTMLElement>(ref: RefObject<T>, handler: (event: MouseEvent | TouchEvent) => void): void;
13
169
 
170
+ /**
171
+ * Hook that detects if the current viewport is mobile-sized.
172
+ * Uses a breakpoint of 768px to determine mobile vs desktop.
173
+ *
174
+ * @returns Boolean indicating whether the current viewport is mobile-sized
175
+ *
176
+ * @example
177
+ * ```tsx
178
+ * function ResponsiveHeader() {
179
+ * const isMobile = useIsMobile();
180
+ *
181
+ * return (
182
+ * <header>
183
+ * {isMobile ? (
184
+ * <MobileNavigation />
185
+ * ) : (
186
+ * <DesktopNavigation />
187
+ * )}
188
+ * </header>
189
+ * );
190
+ * }
191
+ * ```
192
+ *
193
+ * @example
194
+ * ```tsx
195
+ * // Conditional rendering based on mobile state
196
+ * function ProductGrid() {
197
+ * const isMobile = useIsMobile();
198
+ *
199
+ * return (
200
+ * <div className={isMobile ? 'grid-cols-1' : 'grid-cols-3'}>
201
+ * {products.map(product => (
202
+ * <ProductCard key={product.id} product={product} />
203
+ * ))}
204
+ * </div>
205
+ * );
206
+ * }
207
+ * ```
208
+ */
14
209
  declare function useIsMobile(): boolean;
15
210
 
211
+ /**
212
+ * Defines the behavior when search results are empty or query is too short.
213
+ *
214
+ * @example
215
+ * ```tsx
216
+ * // Show "No results found" message
217
+ * emptyStateBehavior="show-empty-message"
218
+ *
219
+ * // Hide results until minimum characters typed
220
+ * emptyStateBehavior="hide-until-min-chars"
221
+ *
222
+ * // Show all results initially
223
+ * emptyStateBehavior="show-all-results"
224
+ * ```
225
+ */
16
226
  type EmptyStateBehavior = 'show-empty-message' | 'hide-until-min-chars' | 'show-all-results';
227
+ /**
228
+ * Context properties for the advanced search functionality.
229
+ * Provides all necessary state and handlers for search components.
230
+ */
17
231
  type SearchContextProps = {
232
+ /** Current search query string */
18
233
  query: string;
234
+ /** Function to update the search query */
19
235
  setQuery: (query: string) => void;
236
+ /** Whether the search results dropdown is open */
20
237
  isOpen: boolean;
238
+ /** Function to control the dropdown open state */
21
239
  setIsOpen: (open: boolean) => void;
240
+ /** Array of current search results */
22
241
  results: SearchResult[];
242
+ /** Function to update the search results */
23
243
  setResults: (results: SearchResult[]) => void;
244
+ /** Whether a search request is currently in progress */
24
245
  isLoading: boolean;
246
+ /** Function to control the loading state */
25
247
  setIsLoading: (loading: boolean) => void;
248
+ /** Function to trigger a search with the given query */
26
249
  onSearch: (query: string) => void;
250
+ /** Function called when a search result is selected */
27
251
  onResultSelect: (result: SearchResult) => void;
252
+ /** Behavior configuration for empty states */
28
253
  emptyStateBehavior: EmptyStateBehavior;
254
+ /** Minimum number of characters required before triggering search */
29
255
  minQueryLength: number;
30
256
  };
257
+ /**
258
+ * React context for sharing search state between components.
259
+ * Created with null as default to ensure proper error handling.
260
+ */
31
261
  declare const SearchContext: React.Context<SearchContextProps | null>;
262
+ /**
263
+ * Hook to access the advanced search context.
264
+ * Must be used within an AdvancedSearchProvider component.
265
+ *
266
+ * @returns SearchContextProps - The search context containing state and handlers
267
+ * @throws Error if used outside of AdvancedSearchProvider
268
+ *
269
+ * @example
270
+ * ```tsx
271
+ * function SearchComponent() {
272
+ * const { query, setQuery, results, onSearch } = useAdvancedSearch();
273
+ *
274
+ * return (
275
+ * <div>
276
+ * <input
277
+ * value={query}
278
+ * onChange={(e) => setQuery(e.target.value)}
279
+ * />
280
+ * {results.map(result => (
281
+ * <div key={result.id}>{result.title}</div>
282
+ * ))}
283
+ * </div>
284
+ * );
285
+ * }
286
+ * ```
287
+ */
32
288
  declare function useAdvancedSearch(): SearchContextProps;
33
289
 
34
290
  declare function noop(): void;
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)) {
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,M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
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\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 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,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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ACnD,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;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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foundrykit/hooks",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "main": "./dist/index.js",
@@ -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
 
@@ -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