UNPKG

ivt

Version:

Ivt Components Library

78 lines (75 loc) 2.53 kB
import * as React from 'react'; import { u as useLayoutEffect2 } from './index-DKOlG3mh.mjs'; // src/use-controllable-state.tsx var useInsertionEffect = React[" useInsertionEffect ".trim().toString()] || useLayoutEffect2; function useControllableState({ prop, defaultProp, onChange = ()=>{}, caller }) { const [uncontrolledProp, setUncontrolledProp, onChangeRef] = useUncontrolledState({ defaultProp, onChange }); const isControlled = prop !== void 0; const value = isControlled ? prop : uncontrolledProp; { const isControlledRef = React.useRef(prop !== void 0); React.useEffect(()=>{ const wasControlled = isControlledRef.current; if (wasControlled !== isControlled) { const from = wasControlled ? "controlled" : "uncontrolled"; const to = isControlled ? "controlled" : "uncontrolled"; console.warn(`${caller} is changing from ${from} to ${to}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`); } isControlledRef.current = isControlled; }, [ isControlled, caller ]); } const setValue = React.useCallback((nextValue)=>{ if (isControlled) { const value2 = isFunction(nextValue) ? nextValue(prop) : nextValue; if (value2 !== prop) { onChangeRef.current?.(value2); } } else { setUncontrolledProp(nextValue); } }, [ isControlled, prop, setUncontrolledProp, onChangeRef ]); return [ value, setValue ]; } function useUncontrolledState({ defaultProp, onChange }) { const [value, setValue] = React.useState(defaultProp); const prevValueRef = React.useRef(value); const onChangeRef = React.useRef(onChange); useInsertionEffect(()=>{ onChangeRef.current = onChange; }, [ onChange ]); React.useEffect(()=>{ if (prevValueRef.current !== value) { onChangeRef.current?.(value); prevValueRef.current = value; } }, [ value, prevValueRef ]); return [ value, setValue, onChangeRef ]; } function isFunction(value) { return typeof value === "function"; } export { useControllableState as u }; //# sourceMappingURL=index-D4FMFHi9.mjs.map