UNPKG

@blockstack/ui

Version:

Blockstack UI components built using React and styled-components with styled-system.

72 lines (61 loc) 3.03 kB
import { useRef, useState, useEffect, useCallback } from 'react'; import { warn, runIfFn } from '../utils/index.esm.js'; function useControllableProp(propValue, stateValue) { var _React$useRef = useRef(propValue !== undefined), isControlled = _React$useRef.current; var value = isControlled && typeof propValue !== 'undefined' ? propValue : stateValue; return [isControlled, value]; } var defaultPropsMap = { value: 'value', defaultValue: 'defaultValue', onChange: 'onChange' }; function useControllableState(props) { var valueProp = props.value, defaultValue = props.defaultValue, onChange = props.onChange, _props$shouldUpdate = props.shouldUpdate, shouldUpdate = _props$shouldUpdate === void 0 ? function () { return true; } : _props$shouldUpdate, _props$name = props.name, name = _props$name === void 0 ? 'Component' : _props$name, _props$propsMap = props.propsMap, propsMap = _props$propsMap === void 0 ? defaultPropsMap : _props$propsMap; var _React$useState = useState(defaultValue), valueState = _React$useState[0], setValue = _React$useState[1]; var _React$useRef2 = useRef(valueProp !== undefined), isControlled = _React$useRef2.current; useEffect(function () { var nextIsControlled = valueProp !== undefined; var nextMode = nextIsControlled ? 'a controlled' : 'an uncontrolled'; var mode = isControlled ? 'a controlled' : 'an uncontrolled'; warn({ condition: isControlled !== nextIsControlled, message: "Warning: " + name + " is changing from " + mode + " to " + nextMode + " component. " + 'Components should not switch from controlled to uncontrolled (or vice versa). ' + ("Use the '" + propsMap['value'] + "' with an '" + propsMap['onChange'] + "' handler. ") + ("If you want an uncontrolled component, remove the " + propsMap['value'] + " prop and use '" + propsMap['defaultValue'] + "' instead. \"") + 'More info: https://fb.me/react-controlled-components' }); }, [valueProp, isControlled, name]); var _React$useRef3 = useRef(defaultValue), _defaultValue = _React$useRef3.current; useEffect(function () { warn({ condition: _defaultValue !== defaultValue, message: "Warning: A component is changing the default value of an uncontrolled " + name + " after being initialized. " + ("To suppress this warning opt to use a controlled " + name + ".") }); }, [JSON.stringify(defaultValue)]); var value = isControlled ? valueProp : valueState; var updateValue = useCallback(function (next) { var nextValue = runIfFn(next, value); var shouldUpdateState = shouldUpdate(value, nextValue); if (!shouldUpdateState) return; if (!isControlled) { setValue(next); } onChange === null || onChange === void 0 ? void 0 : onChange(nextValue); }, [onChange, shouldUpdate, isControlled, value]); return [value, updateValue]; } export { useControllableProp, useControllableState }; //# sourceMappingURL=use-controllable.esm.js.map