@foundrykit/hooks 2.0.7 → 2.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +9 -10
- package/dist/index.js.map +1 -1
- package/package.json +8 -6
- package/src/hooks/use-local-storage.ts +10 -10
- package/tsup.config.ts +3 -0
- package/.turbo/turbo-build.log +0 -17
- package/.turbo/turbo-type-check.log +0 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @foundrykit/hooks
|
|
2
2
|
|
|
3
|
+
## 2.0.8
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#132](https://github.com/umi-labs/foundry/pull/132) [`c53bf3e`](https://github.com/umi-labs/foundry/commit/c53bf3e9bad2af8d9011932452fe3d435c9d3cab) Thanks [@sneddonisaac](https://github.com/sneddonisaac)! - `useLocalStorage` no longer causes hydration mismatches: it renders `initialValue` on the server and on the first client render, then reads the stored value in an effect. The built bundle keeps `'use client'` (tsup banner), so the module-level `createContext` calls no longer break Server Component imports. `react`/`react-dom` are peer dependencies only. `sideEffects: false`, and `verify:pack` runs publint and attw.
|
|
8
|
+
|
|
3
9
|
## 2.0.7
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
package/dist/index.d.ts
CHANGED
|
@@ -198,7 +198,9 @@ declare function useFormField(): {
|
|
|
198
198
|
|
|
199
199
|
/**
|
|
200
200
|
* Hook that provides localStorage functionality with React state synchronization.
|
|
201
|
-
* Automatically handles serialization/deserialization and SSR safety
|
|
201
|
+
* Automatically handles serialization/deserialization and SSR safety: the server
|
|
202
|
+
* and the first client render both use `initialValue`, and the stored value is
|
|
203
|
+
* read after mount, so hydration never mismatches.
|
|
202
204
|
*
|
|
203
205
|
* @template T - The type of the value to store
|
|
204
206
|
* @param key - The localStorage key
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
1
3
|
// src/hooks/use-advanced-search.ts
|
|
2
4
|
import * as React from "react";
|
|
3
5
|
var SearchContext = React.createContext(
|
|
@@ -85,20 +87,17 @@ function useFormField() {
|
|
|
85
87
|
}
|
|
86
88
|
|
|
87
89
|
// src/hooks/use-local-storage.ts
|
|
88
|
-
import { useState as useState2 } from "react";
|
|
90
|
+
import { useEffect as useEffect3, useState as useState2 } from "react";
|
|
89
91
|
function useLocalStorage(key, initialValue) {
|
|
90
|
-
const [storedValue, setStoredValue] = useState2(
|
|
91
|
-
|
|
92
|
-
return initialValue;
|
|
93
|
-
}
|
|
92
|
+
const [storedValue, setStoredValue] = useState2(initialValue);
|
|
93
|
+
useEffect3(() => {
|
|
94
94
|
try {
|
|
95
95
|
const item = window.localStorage.getItem(key);
|
|
96
|
-
|
|
96
|
+
if (item !== null) setStoredValue(JSON.parse(item));
|
|
97
97
|
} catch (error) {
|
|
98
98
|
console.log(error);
|
|
99
|
-
return initialValue;
|
|
100
99
|
}
|
|
101
|
-
});
|
|
100
|
+
}, [key]);
|
|
102
101
|
const setValue = (value) => {
|
|
103
102
|
try {
|
|
104
103
|
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
|
@@ -114,12 +113,12 @@ function useLocalStorage(key, initialValue) {
|
|
|
114
113
|
}
|
|
115
114
|
|
|
116
115
|
// src/hooks/use-media-query.ts
|
|
117
|
-
import { useEffect as
|
|
116
|
+
import { useEffect as useEffect4, useState as useState3 } from "react";
|
|
118
117
|
function useMediaQuery(query) {
|
|
119
118
|
const [matches, setMatches] = useState3(
|
|
120
119
|
() => typeof window !== "undefined" ? window.matchMedia(query).matches : false
|
|
121
120
|
);
|
|
122
|
-
|
|
121
|
+
useEffect4(() => {
|
|
123
122
|
const media = window.matchMedia(query);
|
|
124
123
|
const listener = () => setMatches(media.matches);
|
|
125
124
|
listener();
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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":";AACA,YAAY,WAAW;AAoEhB,IAAM,gBAAsB;AAAA,EACjC;AACF;AA4BO,SAAS,oBAAoB;AAClC,QAAM,UAAgB,iBAAW,aAAa;AAC9C,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;;;AC3GA,SAAyB,WAAW,cAAc;AAmC3C,SAAS,gBACd,KACA,SACA;AAGA,QAAM,aAAa,OAAO,OAAO;AACjC,YAAU,MAAM;AACd,eAAW,UAAU;AAAA,EACvB,GAAG,CAAC,OAAO,CAAC;AAEZ,YAAU,MAAM;AACd,UAAM,WAAW,CAAC,UAA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GvB,IAAM,oBAAoB;AAyCnB,SAAS,cAAc;AAC5B,QAAM,CAAC,UAAU,WAAW,IAAU;AAAA,IACpC;AAAA,EACF;AAEA,EAAM,iBAAU,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;;;AC3DO,SAAS,OAAO;AAEvB;","names":["useEffect","React","useState","useEffect","useState","React"]}
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-advanced-search.ts","../src/hooks/use-click-outside.ts","../src/hooks/use-debounced-value.ts","../src/hooks/use-form-field.ts","../src/hooks/use-local-storage.ts","../src/hooks/use-media-query.ts","../src/hooks/use-mobile.ts","../src/lib/utils.ts"],"sourcesContent":["import type { SearchResult } from '@foundrykit/types';\nimport * as React from 'react';\n\n/**\n * Defines the behavior when search results are empty or query is too short.\n *\n * @example\n * ```tsx\n * // Show \"No results found\" message\n * emptyStateBehaviour=\"show-empty-message\"\n *\n * // Hide results until minimum characters typed\n * emptyStateBehaviour=\"hide-until-min-chars\"\n *\n * // Show all results initially\n * emptyStateBehaviour=\"show-all-results\"\n * ```\n */\nexport type EmptyStateBehavior =\n | 'show-empty-message' // Show \"No results found\" message\n | 'hide-until-min-chars' // Don't show popover until min characters\n | 'show-all-results'; // Show all results initially or after min chars\n\n/** @deprecated Use EmptyStateBehavior instead. */\nexport type EmptyStateBehaviour = EmptyStateBehavior;\n\n/**\n * Context properties for the advanced search functionality.\n * Provides all necessary state and handlers for search components.\n */\ntype SearchContextProps = {\n /** Current search query string */\n query: string;\n /** Function to update the search query */\n setQuery: (query: string) => void;\n /** Whether the search results dropdown is open */\n isOpen: boolean;\n /** Function to control the dropdown open state */\n setIsOpen: (open: boolean) => void;\n /** Stable id for the input element */\n inputId: string;\n /** Stable id for the results container */\n resultsId: string;\n /** Currently highlighted result index for keyboard navigation */\n activeIndex: number;\n /** Function to update the highlighted result index */\n setActiveIndex: (index: number) => void;\n /** Array of current search results */\n results: SearchResult[];\n /** Function to update the search results */\n setResults: (results: SearchResult[]) => void;\n /** Whether a search request is currently in progress */\n isLoading: boolean;\n /** Function to control the loading state */\n setIsLoading: (loading: boolean) => void;\n /** Function to trigger a search with the given query */\n onSearch: (query: string) => void;\n /** Function called when a search result is selected */\n onResultSelect: (result: SearchResult) => void;\n /** Behavior configuration for empty states */\n emptyStateBehaviour: EmptyStateBehavior;\n /** Minimum number of characters required before triggering search */\n minQueryLength: number;\n};\n\n/**\n * React context for sharing search state between components.\n * Created with null as default to ensure proper error handling.\n */\nexport const SearchContext = React.createContext<SearchContextProps | null>(\n null\n);\n\n/**\n * Hook to access the advanced search context.\n * Must be used within an AdvancedSearchProvider component.\n *\n * @returns SearchContextProps - The search context containing state and handlers\n * @throws Error if used outside of AdvancedSearchProvider\n *\n * @example\n * ```tsx\n * function SearchComponent() {\n * const { query, setQuery, results, onSearch } = useAdvancedSearch();\n *\n * return (\n * <div>\n * <input\n * value={query}\n * onChange={(e) => setQuery(e.target.value)}\n * />\n * {results.map(result => (\n * <div key={result.id}>{result.title}</div>\n * ))}\n * </div>\n * );\n * }\n * ```\n */\nexport function useAdvancedSearch() {\n const context = React.useContext(SearchContext);\n if (!context) {\n throw new Error(\n 'useAdvancedSearch must be used within an AdvancedSearchProvider.'\n );\n }\n return context;\n}\n","import { type RefObject, useEffect, useRef } from 'react';\n\n/**\n * Hook that detects clicks outside of a specified element.\n * Useful for closing dropdowns, modals, or other overlay components.\n *\n * @template T - The HTML element type (defaults to HTMLElement)\n * @param ref - React ref object pointing to the element to monitor\n * @param handler - Function called when a click outside is detected\n *\n * @example\n * ```tsx\n * function Dropdown() {\n * const [isOpen, setIsOpen] = useState(false);\n * const dropdownRef = useRef<HTMLDivElement>(null);\n *\n * useClickOutside(dropdownRef, () => {\n * setIsOpen(false);\n * });\n *\n * return (\n * <div ref={dropdownRef}>\n * {isOpen && <div>Dropdown content</div>}\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // With custom element type\n * const modalRef = useRef<HTMLDialogElement>(null);\n * useClickOutside(modalRef, () => closeModal());\n * ```\n */\nexport function useClickOutside<T extends HTMLElement = HTMLElement>(\n ref: RefObject<T>,\n handler: (event: MouseEvent | TouchEvent) => void\n) {\n // Keep the latest handler in a ref so an inline handler (the common call\n // site) doesn't re-add/remove the listeners on every render.\n const handlerRef = useRef(handler);\n useEffect(() => {\n handlerRef.current = handler;\n }, [handler]);\n\n useEffect(() => {\n const listener = (event: MouseEvent | TouchEvent) => {\n const el = ref?.current;\n if (!el || el.contains((event?.target as Node) || null)) {\n return;\n }\n\n handlerRef.current(event);\n };\n\n document.addEventListener('mousedown', listener);\n document.addEventListener('touchstart', listener);\n\n return () => {\n document.removeEventListener('mousedown', listener);\n document.removeEventListener('touchstart', listener);\n };\n }, [ref]);\n}\n","import { useEffect, useState } from 'react';\n\n/**\n * Hook that returns a debounced version of the provided value.\n * The returned value will only update after the specified delay has passed\n * since the last time the input value changed.\n *\n * @template T - The type of the value to debounce\n * @param value - The value to debounce\n * @param delay - The delay in milliseconds\n * @returns The debounced value\n *\n * @example\n * ```tsx\n * function SearchInput() {\n * const [query, setQuery] = useState('');\n * const debouncedQuery = useDebouncedValue(query, 300);\n *\n * useEffect(() => {\n * if (debouncedQuery) {\n * // Perform search with debounced query\n * searchAPI(debouncedQuery);\n * }\n * }, [debouncedQuery]);\n *\n * return (\n * <input\n * value={query}\n * onChange={(e) => setQuery(e.target.value)}\n * />\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Debouncing form validation\n * const debouncedEmail = useDebouncedValue(email, 500);\n *\n * useEffect(() => {\n * if (debouncedEmail) {\n * validateEmail(debouncedEmail);\n * }\n * }, [debouncedEmail]);\n * ```\n */\nexport function useDebouncedValue<T>(value: T, delay: number): T {\n const [debouncedValue, setDebouncedValue] = useState<T>(value);\n\n useEffect(() => {\n const handler = setTimeout(() => {\n setDebouncedValue(value);\n }, delay);\n\n return () => {\n clearTimeout(handler);\n };\n }, [value, delay]);\n\n return debouncedValue;\n}\n","import * as React from 'react';\nimport {\n type FieldPath,\n type FieldValues,\n useFormContext,\n useFormState,\n} from 'react-hook-form';\n\nexport type FormFieldContextValue<\n TFieldValues extends FieldValues = FieldValues,\n TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n> = {\n name: TName;\n};\n\nexport const FormFieldContext = React.createContext<FormFieldContextValue>(\n {} as FormFieldContextValue\n);\n\nexport type FormItemContextValue = {\n id: string;\n};\n\nexport const FormItemContext = React.createContext<FormItemContextValue>(\n {} as FormItemContextValue\n);\n\nexport function useFormField() {\n const fieldContext = React.useContext(FormFieldContext);\n const itemContext = React.useContext(FormItemContext);\n const { getFieldState } = useFormContext();\n const formState = useFormState({ name: fieldContext.name });\n const fieldState = getFieldState(fieldContext.name, formState);\n\n if (!fieldContext) {\n throw new Error('useFormField should be used within <FormField>');\n }\n\n const { id } = itemContext;\n\n return {\n id,\n name: fieldContext.name,\n formItemId: `${id}-form-item`,\n formDescriptionId: `${id}-form-item-description`,\n formMessageId: `${id}-form-item-message`,\n ...fieldState,\n } as const;\n}\n","import { useEffect, useState } from 'react';\n\n/**\n * Hook that provides localStorage functionality with React state synchronization.\n * Automatically handles serialization/deserialization and SSR safety: the server\n * and the first client render both use `initialValue`, and the stored value is\n * read after mount, so hydration never mismatches.\n *\n * @template T - The type of the value to store\n * @param key - The localStorage key\n * @param initialValue - The initial value if no stored value exists\n * @returns A tuple containing the stored value and a setter function\n *\n * @example\n * ```tsx\n * function UserPreferences() {\n * const [theme, setTheme] = useLocalStorage('theme', 'light');\n * const [language, setLanguage] = useLocalStorage('language', 'en');\n *\n * return (\n * <div>\n * <select value={theme} onChange={(e) => setTheme(e.target.value)}>\n * <option value=\"light\">Light</option>\n * <option value=\"dark\">Dark</option>\n * </select>\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // With complex objects\n * interface UserSettings {\n * notifications: boolean;\n * fontSize: number;\n * }\n *\n * const [settings, setSettings] = useLocalStorage<UserSettings>('user-settings', {\n * notifications: true,\n * fontSize: 14\n * });\n *\n * // Update with function (like useState)\n * setSettings(prev => ({ ...prev, fontSize: 16 }));\n * ```\n */\nexport function useLocalStorage<T>(key: string, initialValue: T) {\n const [storedValue, setStoredValue] = useState<T>(initialValue);\n\n // Read the stored value after mount so the first client render matches the server.\n useEffect(() => {\n try {\n const item = window.localStorage.getItem(key);\n if (item !== null) setStoredValue(JSON.parse(item));\n } catch (error) {\n console.log(error);\n }\n }, [key]);\n\n // Return a wrapped version of useState's setter function that persists the new value to localStorage\n const setValue = (value: T | ((val: T) => T)) => {\n try {\n // Allow value to be a function so we have the same API as useState\n const valueToStore =\n value instanceof Function ? value(storedValue) : value;\n setStoredValue(valueToStore);\n if (typeof window !== 'undefined') {\n window.localStorage.setItem(key, JSON.stringify(valueToStore));\n }\n } catch (error) {\n console.log(error);\n }\n };\n\n return [storedValue, setValue] as const;\n}\n","import { useEffect, useState } from 'react';\n\n/**\n * Hook that tracks whether a CSS media query matches the current viewport.\n * Automatically updates when the viewport size changes.\n *\n * @param query - The CSS media query string to match\n * @returns Boolean indicating whether the media query currently matches\n *\n * @example\n * ```tsx\n * function ResponsiveComponent() {\n * const isMobile = useMediaQuery('(max-width: 768px)');\n * const isTablet = useMediaQuery('(min-width: 769px) and (max-width: 1024px)');\n * const isDesktop = useMediaQuery('(min-width: 1025px)');\n *\n * return (\n * <div>\n * {isMobile && <MobileLayout />}\n * {isTablet && <TabletLayout />}\n * {isDesktop && <DesktopLayout />}\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Dark mode detection\n * const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');\n *\n * // High contrast mode\n * const prefersHighContrast = useMediaQuery('(prefers-contrast: high)');\n *\n * // Reduced motion\n * const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');\n * ```\n */\nexport function useMediaQuery(query: string): boolean {\n // SSR-safe initial value; hydrated to the real match in the effect.\n const [matches, setMatches] = useState(() =>\n typeof window !== 'undefined' ? window.matchMedia(query).matches : false\n );\n\n useEffect(() => {\n const media = window.matchMedia(query);\n const listener = () => setMatches(media.matches);\n // Subscribe to the MediaQueryList's own `change` event so non-viewport\n // queries (prefers-color-scheme, prefers-reduced-motion, orientation, …)\n // update too — a `resize` listener never fires for those.\n listener();\n media.addEventListener('change', listener);\n return () => media.removeEventListener('change', listener);\n }, [query]);\n\n return matches;\n}\n","import * as React from 'react';\n\n/** The breakpoint width in pixels below which a device is considered mobile */\nconst MOBILE_BREAKPOINT = 768;\n\n/**\n * Hook that detects if the current viewport is mobile-sized.\n * Uses a breakpoint of 768px to determine mobile vs desktop.\n *\n * @returns Boolean indicating whether the current viewport is mobile-sized\n *\n * @example\n * ```tsx\n * function ResponsiveHeader() {\n * const isMobile = useIsMobile();\n *\n * return (\n * <header>\n * {isMobile ? (\n * <MobileNavigation />\n * ) : (\n * <DesktopNavigation />\n * )}\n * </header>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Conditional rendering based on mobile state\n * function ProductGrid() {\n * const isMobile = useIsMobile();\n *\n * return (\n * <div className={isMobile ? 'grid-cols-1' : 'grid-cols-3'}>\n * {products.map(product => (\n * <ProductCard key={product.id} product={product} />\n * ))}\n * </div>\n * );\n * }\n * ```\n */\nexport function useIsMobile() {\n const [isMobile, setIsMobile] = React.useState<boolean | undefined>(\n undefined\n );\n\n React.useEffect(() => {\n const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);\n const onChange = () => {\n setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);\n };\n mql.addEventListener('change', onChange);\n setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);\n return () => mql.removeEventListener('change', onChange);\n }, []);\n\n return !!isMobile;\n}\n","// Utility functions for hooks package\nexport function noop() {\n // No operation function\n}\n"],"mappings":";;;AACA,YAAY,WAAW;AAoEhB,IAAM,gBAAsB;AAAA,EACjC;AACF;AA4BO,SAAS,oBAAoB;AAClC,QAAM,UAAgB,iBAAW,aAAa;AAC9C,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;;;AC3GA,SAAyB,WAAW,cAAc;AAmC3C,SAAS,gBACd,KACA,SACA;AAGA,QAAM,aAAa,OAAO,OAAO;AACjC,YAAU,MAAM;AACd,eAAW,UAAU;AAAA,EACvB,GAAG,CAAC,OAAO,CAAC;AAEZ,YAAU,MAAM;AACd,UAAM,WAAW,CAAC,UAAmC;AACnD,YAAM,KAAK,KAAK;AAChB,UAAI,CAAC,MAAM,GAAG,SAAU,OAAO,UAAmB,IAAI,GAAG;AACvD;AAAA,MACF;AAEA,iBAAW,QAAQ,KAAK;AAAA,IAC1B;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,GAAG,CAAC;AACV;;;AChEA,SAAS,aAAAA,YAAW,gBAAgB;AA8C7B,SAAS,kBAAqB,OAAU,OAAkB;AAC/D,QAAM,CAAC,gBAAgB,iBAAiB,IAAI,SAAY,KAAK;AAE7D,EAAAA,WAAU,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,YA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AAQ,IAAI,KAAK;AAAA,IACnB;AAAA,EACF;AAEA,SAAO,CAAC,aAAa,QAAQ;AAC/B;;;AC5EA,SAAS,aAAAE,YAAW,YAAAC,iBAAgB;AAsC7B,SAAS,cAAc,OAAwB;AAEpD,QAAM,CAAC,SAAS,UAAU,IAAIA;AAAA,IAAS,MACrC,OAAO,WAAW,cAAc,OAAO,WAAW,KAAK,EAAE,UAAU;AAAA,EACrE;AAEA,EAAAD,WAAU,MAAM;AACd,UAAM,QAAQ,OAAO,WAAW,KAAK;AACrC,UAAM,WAAW,MAAM,WAAW,MAAM,OAAO;AAI/C,aAAS;AACT,UAAM,iBAAiB,UAAU,QAAQ;AACzC,WAAO,MAAM,MAAM,oBAAoB,UAAU,QAAQ;AAAA,EAC3D,GAAG,CAAC,KAAK,CAAC;AAEV,SAAO;AACT;;;ACxDA,YAAYE,YAAW;AAGvB,IAAM,oBAAoB;AAyCnB,SAAS,cAAc;AAC5B,QAAM,CAAC,UAAU,WAAW,IAAU;AAAA,IACpC;AAAA,EACF;AAEA,EAAM,iBAAU,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;;;AC3DO,SAAS,OAAO;AAEvB;","names":["useEffect","React","useEffect","useState","useEffect","useState","React"]}
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@foundrykit/hooks",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.8",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"private": false,
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"module": "./dist/index.js",
|
|
8
8
|
"types": "./dist/index.d.ts",
|
|
9
|
+
"sideEffects": false,
|
|
9
10
|
"publishConfig": {
|
|
10
11
|
"access": "public"
|
|
11
12
|
},
|
|
@@ -18,18 +19,18 @@
|
|
|
18
19
|
"./lib/*": "./src/lib/*.ts"
|
|
19
20
|
},
|
|
20
21
|
"dependencies": {
|
|
21
|
-
"react": "^19.1.1",
|
|
22
|
-
"react-dom": "^19.1.1",
|
|
23
22
|
"react-hook-form": "^7.62.0"
|
|
24
23
|
},
|
|
25
24
|
"devDependencies": {
|
|
26
25
|
"@types/node": "^20.19.9",
|
|
27
26
|
"@types/react": "^19.1.9",
|
|
28
27
|
"@types/react-dom": "^19.1.7",
|
|
28
|
+
"react": "^19.1.1",
|
|
29
|
+
"react-dom": "^19.1.1",
|
|
29
30
|
"tsup": "^8.0.0",
|
|
30
31
|
"typescript": "^5.9.2",
|
|
31
|
-
"@foundrykit/
|
|
32
|
-
"@foundrykit/
|
|
32
|
+
"@foundrykit/types": "3.0.0",
|
|
33
|
+
"@foundrykit/typescript-config": "1.0.6"
|
|
33
34
|
},
|
|
34
35
|
"peerDependencies": {
|
|
35
36
|
"react": "^19.1.1",
|
|
@@ -44,6 +45,7 @@
|
|
|
44
45
|
"scripts": {
|
|
45
46
|
"build": "tsup",
|
|
46
47
|
"dev": "tsup --watch",
|
|
47
|
-
"type-check": "tsc --noEmit"
|
|
48
|
+
"type-check": "tsc --noEmit",
|
|
49
|
+
"verify:pack": "publint && attw --pack . --profile esm-only"
|
|
48
50
|
}
|
|
49
51
|
}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import { useState } from 'react';
|
|
1
|
+
import { useEffect, useState } from 'react';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Hook that provides localStorage functionality with React state synchronization.
|
|
5
|
-
* Automatically handles serialization/deserialization and SSR safety
|
|
5
|
+
* Automatically handles serialization/deserialization and SSR safety: the server
|
|
6
|
+
* and the first client render both use `initialValue`, and the stored value is
|
|
7
|
+
* read after mount, so hydration never mismatches.
|
|
6
8
|
*
|
|
7
9
|
* @template T - The type of the value to store
|
|
8
10
|
* @param key - The localStorage key
|
|
@@ -44,19 +46,17 @@ import { useState } from 'react';
|
|
|
44
46
|
* ```
|
|
45
47
|
*/
|
|
46
48
|
export function useLocalStorage<T>(key: string, initialValue: T) {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
}
|
|
49
|
+
const [storedValue, setStoredValue] = useState<T>(initialValue);
|
|
50
|
+
|
|
51
|
+
// Read the stored value after mount so the first client render matches the server.
|
|
52
|
+
useEffect(() => {
|
|
52
53
|
try {
|
|
53
54
|
const item = window.localStorage.getItem(key);
|
|
54
|
-
|
|
55
|
+
if (item !== null) setStoredValue(JSON.parse(item));
|
|
55
56
|
} catch (error) {
|
|
56
57
|
console.log(error);
|
|
57
|
-
return initialValue;
|
|
58
58
|
}
|
|
59
|
-
});
|
|
59
|
+
}, [key]);
|
|
60
60
|
|
|
61
61
|
// Return a wrapped version of useState's setter function that persists the new value to localStorage
|
|
62
62
|
const setValue = (value: T | ((val: T) => T)) => {
|
package/tsup.config.ts
CHANGED
|
@@ -7,5 +7,8 @@ export default defineConfig({
|
|
|
7
7
|
splitting: false,
|
|
8
8
|
sourcemap: true,
|
|
9
9
|
clean: true,
|
|
10
|
+
// esbuild drops module directives when bundling; every export here is
|
|
11
|
+
// client-only, so mark the whole bundle for RSC consumers.
|
|
12
|
+
banner: { js: "'use client';" },
|
|
10
13
|
external: ['react', 'react-dom'],
|
|
11
14
|
});
|
package/.turbo/turbo-build.log
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
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
|