Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/metal-hotels-study.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@codiume/hooks": patch
---

Added comments to the function along with an explanation of its functionality.
31 changes: 31 additions & 0 deletions src/use-clipboard/use-clipboard.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,37 @@
import { useCallback, useState } from 'react';
import { rescue } from '../utils';

/**
* Custom hook for handling clipboard text copying
*
* This hook uses the Clipboard API to copy the provided text to the clipboard and tracks
* whether the text has been successfully copied or not.
*
* @returns An object containing:
* - `copy`: A function that accepts a string as a parameter and copies it to the clipboard
* - `copied`: A boolean status indicating whether the text was successfully copied or not
*
* Usage:
* 1. Call `useClipboard` within your React component.
* 2. Use the `copy` function to copy text to the clipboard.
* 3. Use the `copied` status to display a message or update the UI based on whether the text has been copied.
*
* Example usage:
* ```tsx
* const { copy, copied } = useClipboard();
*
* const handleCopy = () => {
* copy('Text you want to copy');
* };
*
* return (
* <div>
* <button onClick={handleCopy}>Copy Text</button>
* {copied && <span>Text copied!</span>}
* </div>
* );
* ```
*/
export function useClipboard() {
const [copied, setCopied] = useState(false);

Expand Down
33 changes: 33 additions & 0 deletions src/use-hover/use-hover.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,38 @@
import { type RefObject, useEffect, useState } from 'react';

/**
* Custom hook for detecting hover state on an element
*
* This hook tracks whether an element is being hovered over or not. It listens for
* `mouseenter` and `mouseleave` events and sets the hover state accordingly.
*
* @param ref A `ref` object that is attached to the element you want to track hover state for.
*
* @returns An object containing:
* - `isHovered`: A boolean that indicates whether the element is currently being hovered over.
*
* Usage:
* 1. Create a `ref` using `useRef` and attach it to the element you want to track hover state for.
* 2. Pass the `ref` to the `useHover` hook to get the `isHovered` status.
* 3. Use the `isHovered` status to apply styles, show or hide content, etc., based on hover state.
*
* Example usage:
* ```tsx
* const hoverRef = useRef(null);
* const { isHovered } = useHover(hoverRef);
*
* return (
* <div>
* <div
* ref={hoverRef}
* style={{ backgroundColor: isHovered ? 'blue' : 'red' }}
* >
* Hover over me!
* </div>
* </div>
* );
* ```
*/
export function useHover<T extends HTMLElement | null>(ref: RefObject<T>) {
const [isHovered, setIsHovered] = useState(false);

Expand Down
34 changes: 34 additions & 0 deletions src/use-in-viewport/use-in-viewport.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,39 @@
import { useEffect, useMemo, useRef, useState } from 'react';

/**
* Custom hook to detect if an element is in the viewport using Intersection Observer API
*
* This hook tracks whether the element referenced by the `ref` is currently in the viewport
* (i.e., visible on the screen). It uses the `IntersectionObserver` API to observe the element's
* visibility within the viewport and updates the `inViewport` state accordingly.
*
* @param options Optional configuration options for the Intersection Observer.
*
* @returns A tuple:
* - `ref`: A `ref` object to be attached to the element you want to track.
* - `inViewport`: A boolean that indicates whether the element is in the viewport or not.
*
* Usage:
* 1. Create a `ref` using `useRef` and attach it to the element you want to track visibility for.
* 2. Pass the `ref` to the `useInViewport` hook to get the `inViewport` status.
* 3. Use the `inViewport` status to trigger actions or change styles when the element enters or exits the viewport.
*
* Example usage:
* ```tsx
* const [ref, inViewport] = useInViewport();
*
* return (
* <div>
* <div
* ref={ref}
* style={{ opacity: inViewport ? 1 : 0.5 }}
* >
* I am visible when in viewport!
* </div>
* </div>
* );
* ```
*/
export function useInViewport<T extends HTMLElement = HTMLElement>(
options?: IntersectionObserverInit
) {
Expand Down
35 changes: 35 additions & 0 deletions src/use-local-storage/use-local-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,41 @@ import { rescue } from '../utils';

type SetValue<T> = T | ((val: T) => T);

/**
* Custom hook for managing state with localStorage persistence
*
* This hook synchronizes a state value with `localStorage`, allowing it to persist
* across page reloads and different browser tabs. It offers the same API as `useState`,
* with the added functionality of storing the value in `localStorage`.
*
* @param key The key under which the value is stored in `localStorage`.
* @param initialValue The initial value to be used if no value is found in `localStorage`.
*
* @returns A tuple:
* - `storedValue`: The current value from `localStorage` or the initial value if none exists.
* - `setValue`: A function to update the value, which will also update `localStorage`.
*
* Usage:
* 1. Call `useLocalStorage` with a key and initial value.
* 2. Use `storedValue` in your component to get the persisted state value.
* 3. Use `setValue` to update the state and the value in `localStorage`.
*
* Example usage:
* ```tsx
* const [name, setName] = useLocalStorage('name', 'John Doe');
*
* return (
* <div>
* <input
* type="text"
* value={name}
* onChange={(e) => setName(e.target.value)}
* />
* <p>The stored name is: {name}</p>
* </div>
* );
* ```
*/
export function useLocalStorage<T>(
key: string,
initialValue: T
Expand Down
27 changes: 27 additions & 0 deletions src/use-media-query/use-media-query.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
import { useEffect, useState } from 'react';

/**
* Custom hook to evaluate a media query and return a boolean indicating whether the query matches.
*
* This hook checks if the specified media query (e.g., for screen size or other conditions)
* matches the current state of the window. It also listens for changes in the media query
* (e.g., window resizing) and updates the state accordingly.
*
* @param query A valid CSS media query string to test against the current window state.
*
* @returns A boolean indicating whether the media query matches the current window state.
*
* Usage:
* 1. Pass a valid media query string (e.g., `'(max-width: 600px)'`) to the hook.
* 2. The hook will return `true` if the query matches the current window state, or `false` otherwise.
* 3. The value updates automatically when the window state changes (e.g., when resizing).
*
* Example usage:
* ```tsx
* const isMobile = useMediaQuery('(max-width: 600px)');
*
* return (
* <div>
* {isMobile ? <MobileComponent /> : <DesktopComponent />}
* </div>
* );
* ```
*/
export function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(
() => window.matchMedia(query).matches
Expand Down
35 changes: 35 additions & 0 deletions src/use-queue/use-queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,41 @@ type QueueActions<T> = {
clearActive: () => void;
};

/**
* Custom hook for managing a queue with an active list and a queue list.
*
* This hook provides functionality to enqueue, dequeue, and clear items
* from a queue while managing the separation of active and queued items.
* It also handles limiting the number of active items in the queue.
*
* @param initialValues The initial values for the queue. These will be split
* into the active list and the queue list based on the limit.
* @param limit The maximum number of active items in the queue. Items exceeding
* this limit are placed in the queue. A value of 0 means no limit.
*
* @returns A tuple with two elements:
* - The first element is the `QueueState`, containing the `active` and `queue` lists.
* - The second element is an object containing actions for manipulating the queue:
* - `enqueue`: Adds an item to the queue.
* - `dequeue`: Removes and returns the first item from the queue.
* - `clear`: Clears both the `active` and `queue` lists.
* - `clearActive`: Clears only the `active` list, leaving the `queue` intact.
* - `clearQueue`: Clears only the `queue` list, leaving the `active` list intact.
*
* Example usage:
* ```tsx
* const [queueState, queueActions] = useQueue<number>([1, 2, 3], 2);
*
* // Enqueue a new item
* queueActions.enqueue(4);
*
* // Dequeue an item
* const dequeuedItem = queueActions.dequeue();
*
* // Clear the queue
* queueActions.clear();
* ```
*/
export function useQueue<T>(
initialValues: T[] = [],
limit = 0
Expand Down
41 changes: 41 additions & 0 deletions src/use-scroll/use-scroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,47 @@ type ScrollPosition = {
y: number;
};

/**
* Custom hook for tracking and controlling the scroll position of an element.
*
* This hook provides two main functionalities:
* 1. Tracks the current scroll position (`x` and `y` coordinates) of a specified element.
* 2. Provides a function to programmatically scroll the element to specific coordinates (`x`, `y`).
*
* @param ref A reference to the HTML element whose scroll position you want to track or control.
*
* @returns A tuple containing:
* - The current scroll position object, containing `x` (horizontal scroll) and `y` (vertical scroll).
* - A function `scrollTo` that allows you to scroll the element to a specified position.
*
* Example usage:
* ```tsx
* import { useScroll } from "@codiume/hooks";
*
* function Demo() {
* const ref = useRef<HTMLDivElement>(null);
* const [{ x, y }, scrollTo] = useScroll(ref);
*
* return (
* <div>
* <p>Scroll position: x: {x}, y: {y}</p>
* <button onClick={() => scrollTo({ y: 0 })}>Scroll to top</button>
* <div
* ref={ref}
* style={{ height: "300px", width: "300px", overflow: "auto" }}
* >
* <div style={{ height: "1000px", width: "1000px" }}>Scroll me!</div>
* </div>
* </div>
* );
* }
* ```
*
* In this example:
* - `ref` is used to track a scrollable container's position.
* - The scroll position (`x`, `y`) is shown on the screen.
* - The `scrollTo` function allows you to scroll the container to a specific position (`y: 0` in this case).
*/
export function useScroll(ref: RefObject<HTMLElement>) {
const [scrollPosition, setScrollPosition] = useState<ScrollPosition>({
x: 0,
Expand Down
11 changes: 11 additions & 0 deletions src/use-window-scroll/use-window-scroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ type ScrollPosition = {
y: number;
};

/**
* Function to scroll the window to a specific position.
*
* @param {Partial<ScrollPosition>} position - The target position to scroll to. It can contain `x` (horizontal) and/or `y` (vertical) properties.
* @param {ScrollOptions} options - Optional scroll behavior settings (default is `smooth`).
*/
const scrollTo = (
{ x, y }: Partial<ScrollPosition>,
options: ScrollOptions = { behavior: 'smooth' }
Expand All @@ -22,6 +28,11 @@ const scrollTo = (
window.scrollTo(scrollOptions);
};

/**
* Custom hook for tracking the window's scroll position.
*
* @returns A tuple containing the current scroll position (`x`, `y`) and a `scrollTo` function to control window scrolling.
*/
export function useWindowScroll() {
const [position, setPosition] = useState<ScrollPosition>({ x: 0, y: 0 });

Expand Down