UNPKG

@liveblocks/react-ui

Version:

A set of React pre-built components for the Liveblocks products. Liveblocks is the all-in-one toolkit to build collaborative products like Figma, Notion, and more.

31 lines (28 loc) 979 B
import { useMemo, useState, useEffect, useCallback } from 'react'; import { clamp } from './clamp.js'; import { wrap } from './wrap.js'; const defaultOptions = { wrap: true }; function useIndex(initial, length, options) { const { wrap: shouldWrap } = useMemo(() => { return { ...defaultOptions, ...options }; }, [options]); const transform = useMemo(() => shouldWrap ? wrap : clamp, [shouldWrap]); const [index, setIndex] = useState(initial); useEffect(() => { setIndex((index2) => clamp(index2, 0, Math.max(length - 1, 0))); }, [length]); const previousIndex = useCallback(() => { setIndex((index2) => transform(index2 - 1, 0, Math.max(length, 0))); }, [length, transform]); const nextIndex = useCallback(() => { setIndex((index2) => transform(index2 + 1, 0, Math.max(length, 0))); }, [length, transform]); return [index, previousIndex, nextIndex, setIndex]; } export { useIndex }; //# sourceMappingURL=use-index.js.map