UNPKG

react-fast-hooks

Version:
655 lines (606 loc) 21.1 kB
import { RefObject } from 'react'; declare const LIGHT_THEME: "light"; declare const DARK_THEME: "dark"; type Theme = typeof LIGHT_THEME | typeof DARK_THEME; /** * Hook to get the system theme. * @returns {Theme} The current system theme value (light or dark). */ declare const useSystemTheme: () => Theme; /** * Hook to get the online status of the browser. * * @returns {boolean} A boolean true if the browser is online, otherwise false. */ declare const useOnlineStatus: () => boolean; interface ClipboardHook { copy: (text: string) => Promise<void>; isCopied: boolean; } /** * Hook to copy text to the clipboard. * * @returns An object with `copy` function and `isCopied` boolean state. */ declare const useClipboard: () => ClipboardHook; interface GeolocationState { accuracy: number | null; altitude: number | null; altitudeAccuracy: number | null; heading: number | null; latitude: number | null; longitude: number | null; speed: number | null; timestamp: number; error: GeolocationPositionError | null; } /** * Hook to get the current geolocation. * * @returns The geolocation state. */ declare const useGeolocation: () => GeolocationState; interface UseTitleResult { setTitle: (newTitle: string) => void; } /** * Hook to set and get the document title. * * @param {string} initialTitle - The initial title to set. * @returns An object with the setTitle function. */ declare const useTitle: (initialTitle: string) => UseTitleResult; interface BatteryState { supported: boolean; loading: boolean; level: number | null; charging: boolean | null; chargingTime: number | null; dischargingTime: number | null; } /** * Hook to get battery status. * * @returns An object with battery status. */ declare const useBattery: () => BatteryState; interface WindowSize { width: number | null; height: number | null; } /** * Hook to get the current window size. * * @param {number} [throttleTime=200] - The time in milliseconds to throttle the resize event handler. Defaults to 200ms. * @returns An object with the current window width and height. */ declare const useWindowSize: (throttleTime?: number) => WindowSize; interface WindowScrollPosition { x: number | null; y: number | null; } /** * Hook to get the current window scroll position. * * @param {number} [throttleTime=200] - The time in milliseconds to throttle the scroll event handler. Defaults to 200ms. * @returns An object with the current window scroll position (x and y). */ declare const useWindowScrollPosition: (throttleTime?: number) => WindowScrollPosition; interface ScrollPosition$2 { x: number; y: number; behavior?: ScrollBehavior; } interface UseWindowScrollIntoPosition { (): (position: ScrollPosition$2) => void; } /** * Hook to scroll the window to a specific position. * * @returns A function to scroll the window to the specified x and y coordinates. */ declare const useWindowScrollIntoPosition: UseWindowScrollIntoPosition; interface ScrollPosition$1 { x: number; y: number; } interface UseScrollPosition { (elementRef: React.RefObject<HTMLElement>, throttleTime?: number): ScrollPosition$1; } /** * Hook to get the current scroll position of a specified element. * * @param {React.RefObject<HTMLElement>} elementRef - A ref to the element to track the scroll position. * @param {number} [throttleTime=200] - The time in milliseconds to throttle the scroll event handler. Defaults to 200ms. * @returns The current scroll position of the element. */ declare const useScrollPosition: UseScrollPosition; interface ScrollPosition { x: number; y: number; behavior?: ScrollBehavior; } interface UseScrollIntoPosition { (elementRef: React.RefObject<HTMLElement>): (position: ScrollPosition) => void; } /** * Hook to scroll an element to a specific position. * * @param {React.RefObject<HTMLElement>} elementRef - A ref to the element to scroll. * @returns A function to scroll the element to the specified x and y coordinates. */ declare const useScrollIntoPosition: UseScrollIntoPosition; interface UseFocusBlur { (elementRef: React.RefObject<HTMLElement>): { focus: () => void; blur: () => void; }; } /** * Hook to get focus and blur functions for an element. * * @param {React.RefObject<HTMLElement>} elementRef - A ref to the element. * @returns An object with `focus` and `blur` functions. */ declare const useFocusBlur: UseFocusBlur; interface UseStopwatch { (): { time: number; isRunning: boolean; start: () => void; stop: () => void; reset: () => void; }; } /** * Hook to provide stopwatch functionality with SSR compatibility. * * @returns An object containing the current time in milliseconds, isRunning state, and functions to start, stop, and reset the stopwatch. */ declare const useStopwatch: UseStopwatch; type SetFaviconFn = (faviconUrl: string) => void; interface UseFavicon { (initialFaviconUrl: string): SetFaviconFn; } /** * Hook to set and update the favicon of the webpage. * * @param {string} initialFaviconUrl - The initial URL of the favicon to set. * @returns A function to change the favicon URL. */ declare const useFavicon: UseFavicon; interface ScriptStatus { loading: boolean; error: Error | null; } interface UseScript { (src: string, options: options): ScriptStatus; } interface options { removeOnUnmount?: boolean; async?: boolean; defer?: boolean; } /** * Hook to dynamically load an external script. * * @param src - The URL of the script to load. * @param options - An object containing options for the script. * @returns An object containing the script loading status and any potential error. */ declare const useScript: UseScript; interface UseHover { (ref: RefObject<HTMLElement>): boolean; } /** * Hook to determine if an element is hovered. * * @param {RefObject<HTMLElement>} ref - The ref to the element to track hover state. * @returns A boolean whether the element is hovered or not. */ declare const useHover: UseHover; /** * Hook to detect media query matches. * * @param query The media query string to match against. * @returns A boolean true if the media query matches, otherwise false. */ declare const useMediaQuery: (query: string) => boolean; interface UseLocalStorage<T> { (key: string, initialValue: T): [T, (value: T) => void]; } /** * Hook to manage a value in localStorage. * * @param key The key under which the value is stored in localStorage. * @param initialValue The initial value to use if there is no value in localStorage. * @returns An array with the current value and a function to update it. */ declare const useLocalStorage: UseLocalStorage<any>; interface UseSessionStorage<T> { (key: string, initialValue: T): [T, (value: T) => void]; } /** * Hook to manage a value in sessionStorage. * * @param key The key under which the value is stored in sessionStorage. * @param initialValue The initial value to use if there is no value in sessionStorage. * @returns An array with the current value and a function to update it. */ declare const useSessionStorage: UseSessionStorage<any>; type Orientation = "portrait" | "landscape"; /** * Hook to get the current orientation of the device. * * @returns A string indicating whether the device is in portrait or landscape mode. */ declare const useDeviceOrientation: () => Orientation; interface Dimensions { width: number | null; height: number | null; } interface UseDimensions { (elementRef: React.RefObject<HTMLElement>, throttleTime?: number): Dimensions; } /** * Hook to get the dimensions (width and height) of a specified element. * * @param {React.RefObject<HTMLElement>} elementRef - A ref to the element to track the dimensions. * @param {number} [throttleTime=200] - The time in milliseconds to throttle the resize event handler. Defaults to 200ms. * @returns An object with the width and height of the element. */ declare const useDimensions: UseDimensions; interface UseKeyPress { (targetKey: string): boolean; } /** * Hook to detect if a specified key is pressed. * * @param {string} targetKey - The key to detect. * @returns A boolean true if the key is pressed, false otherwise. */ declare const useKeyPress: UseKeyPress; interface UseKeyCombo { (keys: string[]): boolean; } /** * Hook to detect if a specified key combination is pressed. * * @param {string[]} keys - The key combination to detect. * @returns A boolean true if the key combination is pressed, false otherwise. */ declare const useKeyCombo: UseKeyCombo; interface UseClickOutside { (elementRef: React.RefObject<HTMLElement>, onClickOutside: () => void): void; } /** * Hook to detect clicks outside of a specified element. * * @param {React.RefObject<HTMLElement>} elementRef - A ref to the element to detect clicks outside of. * @param {onClickOutside} onClickOutside - A callback function to execute when a click outside is detected. */ declare const useClickOutside: UseClickOutside; interface IntersectionObserverOptions { root?: Element | null; rootMargin?: string; threshold?: number | number[]; } interface UseIntersectionObserver { (ref: RefObject<HTMLElement>, options?: IntersectionObserverOptions): IntersectionObserverEntry | null; } /** * Hook to observe the visibility of an element using the Intersection Observer API. * * @param {React.RefObject<HTMLElement>} ref - A ref to the element to observe. * @param {IntersectionObserverOptions} [options] - The Intersection Observer options. * @returns The IntersectionObserverEntry providing information about the intersection of the target with the root. */ declare const useIntersectionObserver: UseIntersectionObserver; interface UseMutationObserverOptions { childList?: boolean; attributes?: boolean; characterData?: boolean; subtree?: boolean; attributeOldValue?: boolean; characterDataOldValue?: boolean; attributeFilter?: string[]; } type MutationCallback = (mutations: MutationRecord[], observer: MutationObserver) => void; /** * Hook to observe changes to a DOM element using MutationObserver. * * @param {React.RefObject<HTMLElement>} ref - A React ref to the element to observe. * @param {MutationCallback} callback - A function to handle mutations. * @param {UseMutationObserverOptions} options - An object specifying which DOM mutations to observe. */ declare const useMutationObserver: (ref: React.RefObject<HTMLElement>, callback: MutationCallback, options: UseMutationObserverOptions) => void; /** * Hook to attach an event listener to a DOM element and clean it up on unmount. * * @param {string} eventName - The name of the event to listen for. * @param {Function} handler - The callback function to handle the event. * @param {React.RefObject<HTMLElement>} elementRef - A ref to the element to attach the event listener to. Defaults to window. * @param {boolean | AddEventListenerOptions} options - An options object that specifies characteristics about the event listener. */ declare const useEventListener: (eventName: string, handler: (event: Event) => void, elementRef?: React.RefObject<HTMLElement>, options?: boolean | AddEventListenerOptions) => void; /** * Hook to track the focus state of the window. * * @returns A boolean indicating whether the window is focused. */ declare const useWindowFocus: () => boolean; interface UseIdleOptions { timeout: number; } interface UseIdle { (options: UseIdleOptions): boolean; } /** * Hook to detect user inactivity. * * @param {UseIdleOptions} options - An object containing the timeout in milliseconds. * @returns A boolean indicating whether the user is idle. */ declare const useIdle: UseIdle; interface MousePosition { x: number; y: number; elementX: number; elementY: number; pageX: number; pageY: number; } interface UseMouse { (elementRef: React.RefObject<HTMLElement>): MousePosition; } /** * Hook to track the mouse position relative to a specified element. * * @param {React.RefObject<HTMLElement>} elementRef - A ref to the element to track the mouse position. * @returns An object with the current mouse x and y coordinates relative to the element. */ declare const useMouse: UseMouse; interface UseLongPressOptions { threshold?: number; onLongPress: () => void; onPress?: () => void; onRelease?: () => void; } interface UseLongPress { (elementRef: React.RefObject<HTMLElement>, options: UseLongPressOptions): void; } /** * Hook to enable precise control of long-press interactions for both touch and mouse events. * * @param {React.RefObject<HTMLElement>} elementRef - A ref to the element to track the long press. * @param {UseLongPressOptions} options - Configuration options for the long press. */ declare const useLongPress: UseLongPress; interface FetchOptions { method?: string; headers?: HeadersInit; body?: BodyInit | null; } interface FetchResult<T> { data: T | null; loading: boolean; error: Error | null; refetch: () => void; } /** * Hook to fetch data from an API endpoint. * * @param {string} url - The URL of the API endpoint. * @param {FetchOptions} [options] - Optional configuration for the fetch request. * @returns An object containing the fetched data, loading state, error state, and a refetch function. */ declare const useFetch: <T>(url: string, options?: FetchOptions) => FetchResult<T>; interface UseScrollLock { (): { lockScroll: () => void; unlockScroll: () => void; isLocked: boolean; }; } /** * Hook to lock and unlock scrolling on the body element with an extra layer of security using MutationObserver. * * @returns An object containing methods to lock/unlock scrolling and a boolean indicating if the scroll is locked. */ declare const useScrollLock: UseScrollLock; interface UseRandomColorResult { color: string; generateNewColor: () => void; } /** * Hook to generate a random color. * * @returns An object containing a string representing a random color in hexadecimal format and a function to generate a new random color. */ declare const useRandomColor: () => UseRandomColorResult; /** * Hook to debounce a value. * * @param value The value to debounce. * @param delay The debounce delay in milliseconds. * @returns The debounced value. */ declare const useDebounce: <T>(value: T, delay: number) => T; /** Hook to get the previous value of a state or prop. * * @returns {T | undefined} The previous value of the state or prop. */ declare function usePrevious<T>(value: T): T | undefined; /** * Hook to create a debounced version of a callback function. * * @param {Function} callback - The original callback function to debounce. * @param {number} delay - The debounce delay in milliseconds. * @returns A debounced version of the callback function. */ declare const useDebouncedCallback: (callback: Function, delay: number) => Function; interface CookieOptions { expires?: number | Date; path?: string; domain?: string; secure?: boolean; sameSite?: "Lax" | "Strict" | "None"; } interface UseCookie { value: string | undefined; setCookie: (value: string, options?: CookieOptions) => void; removeCookie: () => void; hasCookie: () => boolean; } /** * Hook to manage a cookie in React state. * * @param {string} name - The name of the cookie. * @returns An object containing the cookie value and helper methods to interact with it. */ declare const useCookie: (name: string) => UseCookie; /** * Hook to run an effect only on updates, not on initial mount. * * @param {Function} effect - The effect function to run. * @param {Array<any>} deps - The dependency array for the effect. */ declare const useUpdateEffect: (effect: React.EffectCallback, deps: React.DependencyList) => void; interface UseSound { play: () => void; pause: () => void; stop: () => void; setVolume: (volume: number) => void; isPlaying: boolean; error: Error | null; } /** * Hook to play and manage sound effects. * * @param {string} url - The URL of the sound file. * @returns An object containing functions to play, pause, stop the sound, set volume, and state variables for the playing status and errors. */ declare const useSound: (url: string) => UseSound; interface UseVibration { vibrate: (pattern: number | number[]) => void; stop: () => void; isSupported: boolean; error: Error | null; } /** * Hook to manage vibration on supported devices. * * @returns {UseVibration} An object containing functions to vibrate, stop vibration, check support, and state variables for error. */ declare const useVibration: () => UseVibration; interface UsePreferredLanguage { language: string; languages: Array<string>; isSupported: boolean; } /** * Hook to get the user's preferred language from the browser. * * @returns {UsePreferredLanguage} An object containing the preferred language and a boolean indicating support. */ declare const usePreferredLanguage: () => UsePreferredLanguage; interface NotificationOptions { body?: string; icon?: string; dir?: NotificationDirection; lang?: string; tag?: string; renotify?: boolean; silent?: boolean; requireInteraction?: boolean; badge?: string; vibrate?: number | number[]; timestamp?: number; image?: string; } interface UseNotificationReturn { permission: NotificationPermission; showNotification: () => void; requestPermission: () => void; updateNotification: (newTitle: string, newOptions?: NotificationOptions) => void; } /** * Hook to trigger browser notifications. * * @param {string} title - The title of the notification. * @param {NotificationOptions} [options] - Optional configuration for the notification. * @returns An object containing the notification permission status and functions to trigger, request permission, and update the notification. */ declare const useNotification: (title: string, options?: NotificationOptions) => UseNotificationReturn; interface HistoryState { [key: string]: any; } interface UseHistory { history: History; state: HistoryState | null; push: (path: string, state?: HistoryState) => void; replace: (path: string, state?: HistoryState) => void; goBack: () => void; goForward: () => void; } /** * Hook to manage browser history. * * @returns {UseHistory} An object containing the history instance and utility functions to interact with it. */ declare const useHistory: () => UseHistory; interface TouchPosition { x: number | null; y: number | null; } interface UseTouch { (elementRef: React.RefObject<HTMLElement>): { touchStart: TouchPosition; touchMove: TouchPosition; touchEnd: TouchPosition; }; } /** * Hook to track touch events on a specified element. * * @param {React.RefObject<HTMLElement>} elementRef - A ref to the element to track touch events. * @returns An object with the current touch start, move, and end positions. */ declare const useTouch: UseTouch; interface SwipeState$1 { startX: number | null; startY: number | null; endX: number | null; endY: number | null; direction: "left" | "right" | "up" | "down" | null; } interface useWindowTouchSwipe { swipeState: SwipeState$1; reset: () => void; } /** * Hook to detect touch swipe gestures. * * @returns {useWindowTouchSwipe} The current swipe state and a reset function. */ declare const useWindowTouchSwipe: () => useWindowTouchSwipe; interface SwipeState { startX: number | null; startY: number | null; endX: number | null; endY: number | null; direction: 'left' | 'right' | 'up' | 'down' | null; } interface UseTouchSwipe { swipeState: SwipeState; reset: () => void; } /** * Hook to detect touch swipe gestures. * * @param {React.RefObject<HTMLElement>} ref - The ref of the element to attach the touch events to. * @returns {UseTouchSwipe} The current swipe state and a reset function. */ declare const useTouchSwipe: (ref: React.RefObject<HTMLElement>) => UseTouchSwipe; export { useBattery, useClickOutside, useClipboard, useCookie, useDebounce, useDebouncedCallback, useDeviceOrientation, useDimensions, useEventListener, useFavicon, useFetch, useFocusBlur, useGeolocation, useHistory, useHover, useIdle, useIntersectionObserver, useKeyCombo, useKeyPress, useLocalStorage, useLongPress, useMediaQuery, useMouse, useMutationObserver, useNotification, useOnlineStatus, usePreferredLanguage, usePrevious, useRandomColor, useScript, useScrollIntoPosition, useScrollLock, useScrollPosition, useSessionStorage, useSound, useStopwatch, useSystemTheme, useTitle, useTouch, useTouchSwipe, useUpdateEffect, useVibration, useWindowFocus, useWindowScrollIntoPosition, useWindowScrollPosition, useWindowSize, useWindowTouchSwipe };