UNPKG

@pastable/react

Version:
37 lines (36 loc) 2.01 kB
import { Dispatch, SetStateAction } from "react"; export declare function useSelection<T = any, Id = string | number>({ getId, max, initial, sortBy: sortByProp, sortDirection, sortFn: sortFnProp, updateFromInitial, onUpdate, }: UseSelectionProps<T, Id>): Selection<T>; export declare type UseSelectionProps<T = any, Id = string | number> = { /** Main (& required !) option, defines how to access a property that will be unique to each items */ getId: (item: T) => Id; /** Initial selection values */ initial?: T[]; /** Sort function to apply automatically to selection */ sortFn?: (a: T, b: T) => number; /** An item property from which the selection will be automatically sorted */ sortBy?: keyof T; /** Sort direction, either asc or desc, defaults to asc */ sortDirection?: "asc" | "desc"; /** If true, the selection will mirror the initial property */ updateFromInitial?: boolean; /** Callback invoked on any set action */ onUpdate?: (value: T[]) => void; /** Defines a maximum selection length, if trying to add items when max is always reached, they will be ignored */ max?: number; }; export declare type SelectionActions<T = any, Id = any> = { get: () => T[]; set: Dispatch<SetStateAction<T[]>>; clear: () => void; reset: () => void; add: (item: T | T[]) => void; remove: (indexOrItem: number | T) => void; find: <ReturnIndex extends boolean = false>(item: T, returnIndex?: ReturnIndex) => ReturnIndex extends true ? number : T; findById: <ReturnIndex extends boolean = false>(id: ReturnType<UseSelectionProps<T, Id>["getId"]>, returnIndex?: ReturnIndex) => ReturnIndex extends true ? number : T; has: (item: T) => boolean; toggle: (item: T) => boolean; update: (item: T) => void; upsert: (item: T) => void; sortBy: (compareFn: (a: T, b: T) => number) => void; }; export declare type Selection<T = any, Id = any> = [T[], SelectionActions<T, Id>];