| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| import {useCallback, useEffect, useRef, useState} from 'react'; |
|
|
| export function useControlledState<T, C = T>(value: Exclude<T, undefined>, defaultValue: Exclude<T, undefined> | undefined, onChange?: (v: C, ...args: any[]) => void): [T, (value: T, ...args: any[]) => void]; |
| export function useControlledState<T, C = T>(value: Exclude<T, undefined> | undefined, defaultValue: Exclude<T, undefined>, onChange?: (v: C, ...args: any[]) => void): [T, (value: T, ...args: any[]) => void]; |
| export function useControlledState<T, C = T>(value: T, defaultValue: T, onChange?: (v: C, ...args: any[]) => void): [T, (value: T, ...args: any[]) => void] { |
| let [stateValue, setStateValue] = useState(value || defaultValue); |
|
|
| let isControlledRef = useRef(value !== undefined); |
| let isControlled = value !== undefined; |
| useEffect(() => { |
| let wasControlled = isControlledRef.current; |
| if (wasControlled !== isControlled) { |
| console.warn(`WARN: A component changed from ${wasControlled ? 'controlled' : 'uncontrolled'} to ${isControlled ? 'controlled' : 'uncontrolled'}.`); |
| } |
| isControlledRef.current = isControlled; |
| }, [isControlled]); |
|
|
| let currentValue = isControlled ? value : stateValue; |
| let setValue = useCallback((value, ...args) => { |
| let onChangeCaller = (value, ...onChangeArgs) => { |
| if (onChange) { |
| if (!Object.is(currentValue, value)) { |
| onChange(value, ...onChangeArgs); |
| } |
| } |
| if (!isControlled) { |
| |
| |
| |
| |
| |
| currentValue = value; |
| } |
| }; |
|
|
| if (typeof value === 'function') { |
| console.warn('We can not support a function callback. See Github Issues for details https://github.com/adobe/react-spectrum/issues/2320'); |
| |
| |
| |
| |
| |
| let updateFunction = (oldValue, ...functionArgs) => { |
| let interceptedValue = value(isControlled ? currentValue : oldValue, ...functionArgs); |
| onChangeCaller(interceptedValue, ...args); |
| if (!isControlled) { |
| return interceptedValue; |
| } |
| return oldValue; |
| }; |
| setStateValue(updateFunction); |
| } else { |
| if (!isControlled) { |
| setStateValue(value); |
| } |
| onChangeCaller(value, ...args); |
| } |
| }, [isControlled, currentValue, onChange]); |
|
|
| return [currentValue, setValue]; |
| } |
|
|