UNPKG

@yamada-ui/react

Version:

React UI components of the Yamada, by the Yamada, for the Yamada built with React and Emotion

49 lines (45 loc) 1.96 kB
"use client"; import { useCallbackRef } from "../../utils/ref.js"; import { utils_exports } from "../../utils/index.js"; import { useState } from "react"; //#region src/hooks/use-controllable-state/index.ts function useControllableState({ defaultValue: defaultValueProp, value, onChange: onChangeProp, onUpdate: onUpdateProp = (prev, next) => prev !== next }) { const onChange = useCallbackRef(onChangeProp); const onUpdate = useCallbackRef(onUpdateProp); const [defaultValue, setDefaultValue] = useState(defaultValueProp); const controlled = !(0, utils_exports.isUndefined)(value); const currentValue = controlled ? value : defaultValue; return [currentValue, useCallbackRef((next) => { const nextValue = (0, utils_exports.runIfFn)(next, currentValue); if (!onUpdate(currentValue, nextValue)) return; if (!controlled || (0, utils_exports.isUndefined)(nextValue) || (0, utils_exports.isNull)(nextValue)) setDefaultValue(nextValue); onChange(nextValue); }, [ controlled, currentValue, onChange, onUpdate ])]; } function isHTMLInputElement(el) { return el instanceof HTMLInputElement; } function useControllableEventState({ defaultValue: defaultValueProp, value, onChange: onChangeProp }) { const onChange = useCallbackRef(onChangeProp); const [defaultValue, setDefaultValue] = useState(defaultValueProp); const controlled = !(0, utils_exports.isUndefined)(value); const currentValue = controlled ? value : defaultValue; const boolean = (0, utils_exports.isBoolean)(currentValue); return [currentValue, useCallbackRef((ev) => { const value$1 = boolean && isHTMLInputElement(ev.target) ? ev.target.checked : ev.target.value; if (!controlled || (0, utils_exports.isUndefined)(value$1) || (0, utils_exports.isNull)(value$1)) setDefaultValue(value$1); onChange(ev); }, [ controlled, currentValue, onChange ])]; } //#endregion export { useControllableEventState, useControllableState }; //# sourceMappingURL=index.js.map