@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.
58 lines (54 loc) • 1.99 kB
JavaScript
;
var core = require('@liveblocks/core');
var react = require('react');
var useRerender = require('./use-rerender.cjs');
function useControllableState(defaultValue, value, onChange) {
const [uncontrolledValue, setUncontrolledValue] = react.useState(defaultValue);
const isControlled = value !== void 0;
const wasControlled = react.useRef(isControlled);
react.useEffect(() => {
if (process.env.NODE_ENV !== "production" && wasControlled.current !== isControlled) {
core.console.warn(
`A component is changing from ${wasControlled.current ? "controlled" : "uncontrolled"} to ${isControlled ? "controlled" : "uncontrolled"}.`
);
}
wasControlled.current = isControlled;
}, [isControlled]);
const currentValue = isControlled ? value : uncontrolledValue;
const setValue = react.useCallback(
(value2) => {
if (isControlled) {
return onChange?.(value2);
} else {
setUncontrolledValue(value2);
return onChange?.(value2);
}
},
[isControlled, onChange]
);
return [currentValue, setValue];
}
function useSemiControllableState(value, onChange) {
const [uncontrolledValue, setUncontrolledValue] = react.useState(value);
const lastChange = react.useRef("controlled");
const lastValue = react.useRef(value);
const [rerender] = useRerender.useRerender();
if (!Object.is(lastValue.current, value)) {
lastValue.current = value;
lastChange.current = "controlled";
}
const setValue = react.useCallback(
(value2) => {
lastChange.current = "uncontrolled";
setUncontrolledValue(value2);
rerender();
onChange?.(value2);
},
[onChange, rerender]
);
const currentValue = lastChange.current === "uncontrolled" ? uncontrolledValue : value;
return [currentValue, setValue];
}
exports.useControllableState = useControllableState;
exports.useSemiControllableState = useSemiControllableState;
//# sourceMappingURL=use-controllable-state.cjs.map